Adding ability to Set class to iterate on ArrayObjects, or any object implementing ArrayAccess and Traversable

This commit is contained in:
Jose Lorenzo Rodriguez 2011-08-11 13:26:06 -04:30
parent 9b6ea7dc45
commit 1726bad396
3 changed files with 29 additions and 7 deletions

View file

@ -299,10 +299,10 @@ class AclNodeTest extends CakeTestCase {
$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);

View file

@ -1594,6 +1594,25 @@ class SetTest extends CakeTestCase {
$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);
}
/**

View file

@ -565,12 +565,13 @@ class Set {
return $data;
}
if (is_object($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)) {
@ -877,8 +878,10 @@ class Set {
}
if (is_object($data)) {
if (!($data instanceof ArrayAccess || $data instanceof Traversable)) {
$data = get_object_vars($data);
}
}
if (is_array($path1)) {
$format = array_shift($path1);