Skip to content

Instantly share code, notes, and snippets.

@markstory
Created September 12, 2017 02:43
Show Gist options
  • Save markstory/998e93a73c4be6df40b811fb3e0f42bf to your computer and use it in GitHub Desktop.
Save markstory/998e93a73c4be6df40b811fb3e0f42bf to your computer and use it in GitHub Desktop.
Should the Marshaller warn on 'extra' properties. We could log, but it will add a dependency to the ORM package.
diff --git a/src/ORM/Marshaller.php b/src/ORM/Marshaller.php
index e4a1894..f7c092b 100644
--- a/src/ORM/Marshaller.php
+++ b/src/ORM/Marshaller.php
@@ -16,6 +16,7 @@ namespace Cake\ORM;
use ArrayObject;
use Cake\Collection\Collection;
+use Cake\Core\Configure;
use Cake\Database\Expression\TupleComparison;
use Cake\Database\Type;
use Cake\Datasource\EntityInterface;
@@ -212,6 +213,17 @@ class Marshaller
$entity->set($properties);
}
+ if (Configure::read('debug')) {
+ $diff = array_diff(array_keys($properties), $entity->getDirty());
+ if (count($diff) > 0) {
+ $keys = implode(', ', $diff);
+ trigger_error(
+ "Found extra data in request. Got the following unexpected properties: {$keys}",
+ E_USER_WARNING
+ );
+ }
+ }
+
// Don't flag clean association entities as
// dirty so we don't persist empty records.
foreach ($properties as $field => $value) {
diff --git a/tests/TestCase/ORM/MarshallerTest.php b/tests/TestCase/ORM/MarshallerTest.php
index e887698..8229bd2 100644
--- a/tests/TestCase/ORM/MarshallerTest.php
+++ b/tests/TestCase/ORM/MarshallerTest.php
@@ -198,6 +198,29 @@ class MarshallerTest extends TestCase
$this->assertEquals('Articles', $result->source());
}
+ /**
+ * Test one() in a simple use.
+ *
+ * @return void
+ */
+ public function testOneSimpleUnmarshalledProperties()
+ {
+ $data = [
+ 'title' => 'My title',
+ 'body' => 'My content',
+ 'author_id' => 1,
+ 'not_in_schema' => true
+ ];
+ $this->articles->setEntityClass(ProtectedArticle::class);
+ $marshall = new Marshaller($this->articles);
+ $result = $marshall->one($data, []);
+
+ $this->assertInstanceOf('Cake\ORM\Entity', $result);
+ $this->assertSame($data['title'], $result->title);
+ $this->assertSame($data['body'], $result->body);
+ $this->assertNull($result->author_id, 'Missing fields should be null');
+ }
+
/**
* Test that marshalling an entity with '' for pk values results
* in no pk value being set.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment