Skip to content

Commit

Permalink
Adding unit test for EntityContext extracting _ids
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Mar 1, 2014
1 parent 435d181 commit 305958c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/View/Form/EntityContext.php
Expand Up @@ -210,12 +210,20 @@ public function val($field) {
return null;
}

/**
* Helper method used to extract all the primary key values out of an array, The
* primary key column is guessed out of the provided $path array
*
* @param array|\Traversable $values The list from wich to extract primary keys from
* @param array $path Each one of the parts in a path for a field name
* @return array
*/
protected function _extractMultiple($values, $path) {
if (!(is_array($values) || $values instanceof \Traversable)) {
return null;
}
$table = $this->_getTable($path);
$primary = (array)$table->primaryKey();
$table = $this->_getTable($path, false);
$primary = $table ? (array)$table->primaryKey() : ['id'];
return (new Collection($values))->extract($primary[0])->toArray();
}

Expand Down Expand Up @@ -336,7 +344,7 @@ protected function _getValidator($parts) {
* @return array containing the table instance in the first position and the
* property name in the second position
*/
protected function _getTable($parts) {
protected function _getTable($parts, $rootFallback = true) {
if (count($parts) === 1) {
return $this->_tables[$this->_rootName];
}
Expand All @@ -357,9 +365,12 @@ protected function _getTable($parts) {
$table = $this->_tables[$this->_rootName];
foreach ($normalized as $part) {
$assoc = $table->associations()->getByProperty($part);
if (!$assoc) {
if (!$assoc && $rootFallback) {
break;
}
if (!$assoc && !$rootFallback) {
return false;
}

$table = $assoc->target();
}
Expand Down
26 changes: 26 additions & 0 deletions tests/TestCase/View/Form/EntityContextTest.php
Expand Up @@ -444,6 +444,32 @@ public function testValAssociatedHasMany() {
$this->assertEquals('Second post', $result);
}

/**
* Test reading values for magic _ids input
*
* @return void
*/
public function testValAssociatedIds() {
$row = new Entity([
'title' => 'First post',
'user' => new Entity([
'username' => 'mark',
'fname' => 'Mark',
'groups' => [
new Entity(['title' => 'PHP', 'id' => 1]),
new Entity(['title' => 'Javascript', 'id' => 2]),
]
]),
]);
$context = new EntityContext($this->request, [
'entity' => $row,
'table' => 'Articles',
]);

$result = $context->val('user.groups._ids');
$this->assertEquals([1, 2], $result);
}

/**
* Test validator as a string.
*
Expand Down

0 comments on commit 305958c

Please sign in to comment.