diff --git a/test/CollectionsTest.php b/test/CollectionsTest.php index de2fe7b..64515e7 100644 --- a/test/CollectionsTest.php +++ b/test/CollectionsTest.php @@ -1,5 +1,7 @@ assertEquals(array(40, 50, 60), __::pluck($stooges, 'age')); $this->assertEquals(array('bar'), __::pluck($stooges, 'foo')); $this->assertEquals(array('bar'), __($stooges)->pluck('foo'), 'works with OO-style call'); + + // extra: ArrayAccess + $persons = array( + self::createPerson('moe', 40), + self::createPerson('larry', 50), + self::createPerson('curly', 60) + ); + $this->assertEquals(array('moe', 'larry', 'curly'), __::pluck($persons, 'name'), 'pulls names out of ArrayAccess objects'); // docs $stooges = array( @@ -324,6 +334,14 @@ public function testPluck() { $this->assertEquals(array('moe', 'larry', 'curly'), __::pluck($stooges, 'name')); } + private static function createPerson($name, $age) { + $person = new CustomArray(); + $person['name'] = $name; + $person['age'] = $age; + + return $person; + } + public function testMax() { // from js $this->assertEquals(3, __::max(array(1,2,3)), 'can perform a regular max'); diff --git a/test/CustomArray.php b/test/CustomArray.php new file mode 100644 index 0000000..8a9f5c1 --- /dev/null +++ b/test/CustomArray.php @@ -0,0 +1,23 @@ +_data); + } + + public function offsetGet($offset) { + return $this->_data[$offset]; + } + + public function offsetSet($offset, $value) { + $this->_data[$offset] = $value; + } + + public function offsetUnset($offset) { + unset($this->_data[$offset]); + } + +} diff --git a/underscore.php b/underscore.php index 1482eed..b2075dc 100644 --- a/underscore.php +++ b/underscore.php @@ -112,8 +112,16 @@ public function pluck($collection=null, $key=null) { $return = array(); foreach($collection as $item) { + $found = false; foreach($item as $k=>$v) { if($k === $key) $return[] = $v; + $found = true; + } + + // Classes implementing ArrayAccess don't fully work like normal arrays. It's not possible to get the list of set + // keys and values by iterating over an object of such class. isset works though. + if (!$found && $item instanceof ArrayAccess && isset($item[$key])) { + $return[] = $item[$key]; } } return self::_wrap($return);