Skip to content

Commit

Permalink
Implemented Entity::extract(), a pluck utility method to quickly grab
Browse files Browse the repository at this point in the history
selected properties out of an entity object
  • Loading branch information
lorenzo committed Oct 21, 2013
1 parent d5227c3 commit 8e4ddb5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Cake/ORM/Entity.php
Expand Up @@ -305,4 +305,19 @@ public function jsonSerialize() {
return $this->_properties;
}

/**
* Returns an array with the requested properties
* stored in this entity, indexed by property name
*
* @param array $properties list of properties to be returned
* @return array
*/
public function extract(array $properties) {
$result = [];
foreach ($properties as $property) {
$result[$property] = $this->get($property);
}
return $result;
}

}
24 changes: 24 additions & 0 deletions Cake/Test/TestCase/ORM/EntityTest.php
Expand Up @@ -423,4 +423,28 @@ public function testJsonSerialize() {
$entity = new Entity($data);
$this->assertEquals(json_encode($data), json_encode($entity));
}

/**
* Tests the extract method
*
* @return void
*/
public function testExtract() {
$entity = new \Cake\ORM\Entity([
'id' => 1,
'title' => 'Foo',
'author_id' => 3
]);
$expected = ['author_id' => 3, 'title' => 'Foo', ];
$this->assertEquals($expected, $entity->extract(['author_id', 'title']));

$expected = ['id' => 1];
$this->assertEquals($expected, $entity->extract(['id']));

$expected = [];
$this->assertEquals($expected, $entity->extract([]));

$expected = ['id' => 1, 'crazyness' => null];
$this->assertEquals($expected, $entity->extract(['id', 'crazyness']));
}
}

0 comments on commit 8e4ddb5

Please sign in to comment.