Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions src/Shell/Task/ModelTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public function bake($name)
$primaryKey = $this->getPrimaryKey($model);
$displayField = $this->getDisplayField($model);
$fields = $this->getFields($model);
$validation = $this->getValidation($model);
$validation = $this->getValidation($model, $associations);
$rulesChecker = $this->getRules($model, $associations);
$behaviors = $this->getBehaviors($model);

Expand Down Expand Up @@ -444,9 +444,10 @@ public function getHiddenFields($model)
* Generate default validation rules.
*
* @param \Cake\ORM\Table $model The model to introspect.
* @param array $associations The associations list.
* @return array The validation rules.
*/
public function getValidation($model)
public function getValidation($model, $associations = [])
{
if (!empty($this->params['no-validation'])) {
return [];
Expand All @@ -459,8 +460,16 @@ public function getValidation($model)

$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($fieldName, $field, $primaryKey);
if (!empty($validation)) {
Expand Down
23 changes: 23 additions & 0 deletions tests/TestCase/Shell/Task/ModelTaskTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,29 @@ public function testGetValidation()
$this->assertEquals($expected, $result);
}

/**
* 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' => 'numeric', 'allowEmpty' => 'create']]
];
$this->assertEquals($expected, $result);
}

/**
* test getting validation rules with the no-rules param.
*
Expand Down