Skip to content
Browse files

Upgrade to Entity::modified() so it can check for the status for a given

field as argument and return a boolean for its current state or null if
the field doesn't exist at all in the entity.
  • Loading branch information...
1 parent 884e839 commit a97b2e6589c20057d548c2a4a9aa415c1d8a6539 @rapzo rapzo committed Sep 11, 2012
Showing with 36 additions and 4 deletions.
  1. +22 −4 data/Entity.php
  2. +14 −0 tests/cases/data/EntityTest.php
View
26 data/Entity.php
@@ -362,12 +362,30 @@ public function decrement($field, $value = 1) {
}
/**
- * Gets the array of fields modified on this entity.
+ * Gets the current state for a given field or, if no field is given, gets the array of
+ * fields modified on this entity.
*
- * @return array Returns an array where the keys are entity field names, and the values are
- * `true` for changed fields.
+ * @param string The field name to check its state.
+ * @return mixed Returns `true` if a field is given and was updated, `false` otherwise and
+ * `null` if the field was not set at all. If no field is given returns an arra
+ * where the keys are entity field names, and the values are `true` for changed fields.
*/
- public function modified() {
+ public function modified($field = null) {
+ if ($field) {
+ if (!isset($this->_updated[$field]) && !isset($this->_data[$field])) {
+ return null;
+ }
+
+ $value = !($value = isset($this->_updated[$field])) ?: $this->_updated[$field];
+ if (!$value) {
+ return false;
+ } elseif (is_object($value) && method_exists($value, 'modified')) {
+ $modified = $value->modified();
+ return $modified === true || is_array($modified) && in_array(true, $modified, true);
+ }
+ return !isset($this->_data[$field]) || $this->_data[$field] !== $this->_updated[$field];
+ }
+
$fields = array_fill_keys(array_keys($this->_data), false);
foreach ($this->_updated as $field => $value) {
if (is_object($value) && method_exists($value, 'modified')) {
View
14 tests/cases/data/EntityTest.php
@@ -122,6 +122,20 @@ public function testModified() {
$data = array('foo' => 'bar', 'baz' => 'dib');
$entity->set($data);
$this->assertEqual(array('foo' => true, 'baz' => true), $entity->modified());
+
+ $this->assertTrue($entity->modified('foo'));
+ $this->assertTrue($entity->modified('baz'));
+
+ $this->assertNull($entity->modified('ole'));
+
+ $subentity = new Entity();
+ $subentity->set($data);
+ $entity->set(array('ble' => $subentity));
+ $this->assertEqual(array('foo' => true, 'baz' => true, 'ble' => true), $entity->modified());
+
+ $this->assertTrue($entity->ble->modified('foo'));
+ $this->assertFalse($entity->ble->modified('iak'));
+ $this->assertEqual($entity->ble->modified(), array('foo' => true, 'baz' => true));
}
/**

0 comments on commit a97b2e6

Please sign in to comment.
Something went wrong with that request. Please try again.