Skip to content

Commit

Permalink
Merge pull request #196 from cakephp/issue-182
Browse files Browse the repository at this point in the history
Generate isUnique rules for single column unique key indexes.
  • Loading branch information
markstory committed Dec 12, 2015
2 parents 567ee14 + 7927edd commit 651664a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/Shell/Task/ModelTask.php
Expand Up @@ -650,7 +650,8 @@ public function getRules($model, array $associations)
if (!empty($this->params['no-rules'])) {
return [];
}
$fields = $model->schema()->columns();
$schema = $model->schema();
$fields = $schema->columns();
if (empty($fields)) {
return [];
}
Expand All @@ -661,6 +662,16 @@ public function getRules($model, array $associations)
$rules[$fieldName] = ['name' => 'isUnique'];
}
}
foreach ($schema->constraints() as $name) {
$constraint = $schema->constraint($name);
if ($constraint['type'] !== SchemaTable::CONSTRAINT_UNIQUE) {
continue;
}
if (count($constraint['columns']) > 1) {
continue;
}
$rules[$constraint['columns'][0]] = ['name' => 'isUnique'];
}

if (empty($associations['belongsTo'])) {
return $rules;
Expand Down
29 changes: 29 additions & 0 deletions tests/TestCase/Shell/Task/ModelTaskTest.php
Expand Up @@ -812,6 +812,35 @@ public function testGetRules()
$this->assertEquals($expected, $result);
}

/**
* Tests the getRules with unique keys.
*
* Multi-column constraints are ignored as they would
* require a break in compatibility.
*
* @return void
*/
public function testGetRulesUniqueKeys()
{
$model = TableRegistry::get('BakeArticles');
$model->schema()->addConstraint('unique_title', [
'type' => 'unique',
'columns' => ['title']
]);
$model->schema()->addConstraint('ignored_constraint', [
'type' => 'unique',
'columns' => ['title', 'bake_user_id']
]);

$result = $this->Task->getRules($model, []);
$expected = [
'title' => [
'name' => 'isUnique'
],
];
$this->assertEquals($expected, $result);
}

/**
* test non interactive doActsAs
*
Expand Down

0 comments on commit 651664a

Please sign in to comment.