Skip to content

Commit

Permalink
feat: always add max: validation to string type fields. (#1046)
Browse files Browse the repository at this point in the history
* Always add max: validation to string type fields.
  • Loading branch information
jarkko-hautakorpi authored Dec 22, 2022
1 parent 2eebc3b commit 8c5d03c
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 8 deletions.
2 changes: 2 additions & 0 deletions src/Common/GeneratorField.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ class GeneratorField
public string $foreignKeyText = '';

public int $numberDecimalPoints = 2;
/** @var \Doctrine\DBAL\Schema\Column */
public $fieldDetails = null;

public function parseDBType(string $dbInput)
{
Expand Down
10 changes: 3 additions & 7 deletions src/Generators/ModelGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,18 +199,14 @@ protected function generateRules(): array
$rule[] = 'numeric';
break;
case 'string':
case 'text':
$rule[] = 'string';

// Enforce a maximum string length if possible.
foreach (explode(':', $field->dbType) as $key => $value) {
if (preg_match('/string,(\d+)/', $value, $matches)) {
$rule[] = 'max:'.$matches[1];
}
if ((int) $field->fieldDetails->getLength() > 0) {
$rule[] = 'max:'.$field->fieldDetails->getLength();
}
break;
case 'text':
$rule[] = 'string';
break;
}

$field->validations = implode('|', $rule);
Expand Down
6 changes: 6 additions & 0 deletions src/Utils/TableFieldsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ class TableFieldsGenerator
/** @var array */
public $ignoredFields;

/** @var \Doctrine\DBAL\Schema\Table */
public $tableDetails;

public function __construct($tableName, $ignoredFields, $connection = '')
{
$this->tableName = $tableName;
Expand All @@ -74,6 +77,8 @@ public function __construct($tableName, $ignoredFields, $connection = '')
'bit' => 'boolean',
];

$this->tableDetails = $this->schemaManager->listTableDetails($this->tableName);

$mappings = config('laravel_generator.from_table.doctrine_mappings', []);
$mappings = array_merge($mappings, $defaultMappings);
foreach ($mappings as $dbType => $doctrineType) {
Expand Down Expand Up @@ -254,6 +259,7 @@ private function generateField($column, $dbType, $htmlType)
{
$field = new GeneratorField();
$field->name = $column->getName();
$field->fieldDetails = $this->tableDetails->getColumn($field->name);
$field->parseDBType($dbType); //, $column); TODO: handle column param
$field->parseHtmlInput($htmlType);

Expand Down
2 changes: 1 addition & 1 deletion views/model/model.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class {{ $config->modelNames->name }} extends Model
{!! $casts !!}
];

public static $rules = [
public static array $rules = [
{!! $rules !!}
];

Expand Down

0 comments on commit 8c5d03c

Please sign in to comment.