Skip to content

Commit

Permalink
Adding the ability to extract only dirty properties in Entity::extract
Browse files Browse the repository at this point in the history
and refactoring Table::save to use this new feature
  • Loading branch information
lorenzo committed Oct 28, 2013
1 parent 9da6404 commit 9b66877
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 15 deletions.
7 changes: 5 additions & 2 deletions Cake/ORM/Entity.php
Expand Up @@ -352,12 +352,15 @@ public function jsonSerialize() {
* stored in this entity, indexed by property name
*
* @param array $properties list of properties to be returned
* @param boolean $onlyDirty Return the requested property only if it is dirty
* @return array
*/
public function extract(array $properties) {
public function extract(array $properties, $onlyDirty = false) {
$result = [];
foreach ($properties as $property) {
$result[$property] = $this->get($property);
if (!$onlyDirty || $this->dirty($property)) {
$result[$property] = $this->get($property);
}
}
return $result;
}
Expand Down
16 changes: 3 additions & 13 deletions Cake/ORM/Table.php
Expand Up @@ -738,7 +738,7 @@ public function exists(array $conditions) {
* @return \Cake\ORM\Entity|boolean
*/
public function save(Entity $entity, array $options = []) {
$options = new \ArrayObject($options + ['atomic' => true]);
$options = new \ArrayObject($options + ['atomic' => true, 'fieldList' => []]);
if ($options['atomic']) {
$connection = $this->connection();
$success = $connection->transactional(function() use ($entity, $options) {
Expand Down Expand Up @@ -766,20 +766,10 @@ protected function _processSave($entity, $options) {
return $event->result;
}

$data = empty($options['fieldList']) ?
$entity->toArray() :
$entity->extract($options['fieldList']);

$schema = $this->schema();
$data = array_intersect_key($data, array_flip($schema->columns()));
$list = $options['fieldList'] ?: $this->schema()->columns();
$data = $entity->extract($list, true);
$keys = array_keys($data);

foreach ($keys as $i => $property) {
if (!$entity->dirty($property)) {
unset($keys[$i], $data[$property]);
}
}

$primary = $entity->extract((array)$this->primaryKey());
if ($primary && $entity->isNew() === null) {
$entity->isNew(!$this->exists($primary));
Expand Down
18 changes: 18 additions & 0 deletions Cake/Test/TestCase/ORM/EntityTest.php
Expand Up @@ -492,6 +492,24 @@ public function testDirtyChangingProperties() {
$this->assertTrue($entity->dirty('something'));
}

/**
* Tests extract only dirty properties
*
* @return void
*/
public function testExtractDirty() {
$entity = new \Cake\ORM\Entity([
'id' => 1,
'title' => 'Foo',
'author_id' => 3
]);
$entity->dirty('id', false);
$entity->dirty('title', false);
$expected = ['author_id' => 3];
$result = $entity->extract(['id', 'title', 'author_id'], true);
$this->assertEquals($expected, $result);
}

/**
* Tests the clean method
*
Expand Down

0 comments on commit 9b66877

Please sign in to comment.