Bake\Shell\Task\ModelTask::getValidation PHP Method

getValidation() public method

Generate default validation rules.
public getValidation ( Table $model, array $associations = [] ) : array
$model Cake\ORM\Table The model to introspect.
$associations array The associations list.
return array The validation rules.
    public function getValidation($model, $associations = [])
    {
        if (!empty($this->params['no-validation'])) {
            return [];
        }
        $schema = $model->schema();
        $fields = $schema->columns();
        if (empty($fields)) {
            return false;
        }
        $validate = [];
        $primaryKey = (array) $schema->primaryKey();
        $foreignKeys = [];
        if (isset($associations['belongsTo'])) {
            foreach ($associations['belongsTo'] as $assoc) {
                $foreignKeys[] = $assoc['foreignKey'];
            }
        }
        foreach ($fields as $fieldName) {
            if (in_array($fieldName, $foreignKeys)) {
                continue;
            }
            $field = $schema->column($fieldName);
            $validation = $this->fieldValidation($schema, $fieldName, $field, $primaryKey);
            if (!empty($validation)) {
                $validate[$fieldName] = $validation;
            }
        }
        return $validate;
    }

Usage Example

Example #1
0
 /**
  * test getting validation rules and exempting foreign keys
  *
  * @return void
  */
 public function testGetValidationExcludeForeignKeys()
 {
     $model = TableRegistry::get('BakeArticles');
     $associations = ['belongsTo' => ['BakeUsers' => ['foreignKey' => 'bake_user_id']]];
     $result = $this->Task->getValidation($model, $associations);
     $expected = ['title' => ['valid' => ['rule' => false, 'allowEmpty' => false]], 'body' => ['valid' => ['rule' => false, 'allowEmpty' => true]], 'published' => ['valid' => ['rule' => 'boolean', 'allowEmpty' => true]], 'id' => ['valid' => ['rule' => 'integer', 'allowEmpty' => 'create']]];
     $this->assertEquals($expected, $result);
 }