Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions test/CollectionsTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

include_once 'CustomArray.php';

class UnderscoreCollectionsTest extends PHPUnit_Framework_TestCase {

public function testEach() {
Expand Down Expand Up @@ -314,6 +316,14 @@ public function testPluck() {
$this->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(
Expand All @@ -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');
Expand Down
23 changes: 23 additions & 0 deletions test/CustomArray.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

class CustomArray implements ArrayAccess {

private $_data;

public function offsetExists($offset) {
return array_key_exists($offset, $this->_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]);
}

}
8 changes: 8 additions & 0 deletions underscore.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down