Skip to content

Commit

Permalink
Adding ability to Set class to iterate on ArrayObjects, or any object…
Browse files Browse the repository at this point in the history
… implementing ArrayAccess and Traversable
  • Loading branch information
lorenzo committed Aug 11, 2011
1 parent 9b6ea7d commit 1726bad
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
4 changes: 2 additions & 2 deletions lib/Cake/Test/Case/Model/DbAclTest.php
Expand Up @@ -299,10 +299,10 @@ public function testNode() {
$this->assertEqual($expected, $result);

$result = Set::extract($Aco->node('Controller2/action3'), '{n}.DbAcoTest.id');
$this->assertFalse($result);
$this->assertNull($result);

$result = Set::extract($Aco->node('Controller2/action3/record5'), '{n}.DbAcoTest.id');
$this->assertFalse($result);
$this->assertNull($result);

$result = $Aco->node('');
$this->assertEqual($result, null);
Expand Down
19 changes: 19 additions & 0 deletions lib/Cake/Test/Case/Utility/SetTest.php
Expand Up @@ -1594,6 +1594,25 @@ public function testClassicExtract() {
$result = Set::extract($a, 'articles.{n}.Article.title');
$expected = array('Article 1', 'Article 2', 'Article 3');
$this->assertEquals($expected, $result);

$a = new ArrayObject();
$a['articles'] = array(
array('Article' => array('id' => 1, 'title' => 'Article 1')),
array('Article' => array('id' => 2, 'title' => 'Article 2')),
array('Article' => array('id' => 3, 'title' => 'Article 3'))
);

$result = Set::extract($a, 'articles.{n}.Article.id');
$expected = array(1, 2, 3);
$this->assertEquals($expected, $result);

$result = Set::extract($a, 'articles.{n}.Article.title');
$expected = array('Article 1', 'Article 2', 'Article 3');
$this->assertEquals($expected, $result);

$result = Set::extract($a, 'articles.0.Article.title');
$expected = 'Article 1';
$this->assertEquals($expected, $result);
}

/**
Expand Down
13 changes: 8 additions & 5 deletions lib/Cake/Utility/Set.php
Expand Up @@ -565,12 +565,13 @@ public static function classicExtract($data, $path = null) {
return $data;
}
if (is_object($data)) {
$data = get_object_vars($data);
if (!($data instanceof ArrayAccess || $data instanceof Traversable)) {
$data = get_object_vars($data);
}
}
if (!is_array($data)) {
return $data;
if (empty($data)) {
return null;
}

if (is_string($path) && strpos($path, '{') !== false) {
$path = String::tokenize($path, '.', '{', '}');
} elseif (is_string($path)) {
Expand Down Expand Up @@ -877,7 +878,9 @@ public static function combine($data, $path1 = null, $path2 = null, $groupPath =
}

if (is_object($data)) {
$data = get_object_vars($data);
if (!($data instanceof ArrayAccess || $data instanceof Traversable)) {
$data = get_object_vars($data);
}
}

if (is_array($path1)) {
Expand Down

0 comments on commit 1726bad

Please sign in to comment.