Browse Source

Merge pull request #3081 from cakephp/3.0-entity-fixes

Preventing invalid property names from being get/set into Entity
Mark Story 12 years ago
parent
commit
5e38016d44
3 changed files with 50 additions and 6 deletions
  1. 11 2
      src/Datasource/EntityTrait.php
  2. 7 4
      src/ORM/Entity.php
  3. 32 0
      tests/TestCase/ORM/EntityTest.php

+ 11 - 2
src/Datasource/EntityTrait.php

@@ -199,7 +199,8 @@ trait EntityTrait {
  * @return \Cake\Datasource\EntityInterface this object
  */
 	public function set($property, $value = null, $options = []) {
-		if (is_string($property)) {
+		$isString = is_string($property);
+		if ($isString && $property !== '') {
 			$guard = false;
 			$property = [$property => $value];
 		} else {
@@ -207,6 +208,9 @@ trait EntityTrait {
 			$options = (array)$value;
 		}
 
+		if (!is_array($property)) {
+			throw new \InvalidArgumentException('Cannot set an empty property');
+		}
 		$options += ['setter' => true, 'guard' => $guard];
 
 		foreach ($property as $p => $value) {
@@ -235,10 +239,15 @@ trait EntityTrait {
  *
  * @param string $property the name of the property to retrieve
  * @return mixed
+ * @throws \InvalidArgumentException if an empty property name is passed
  */
 	public function &get($property) {
-		$method = 'get' . Inflector::camelize($property);
+		if (!strlen((string)$property)) {
+			throw new \InvalidArgumentException('Cannot get an empty property');
+		}
+
 		$value = null;
+		$method = 'get' . Inflector::camelize($property);
 
 		if (isset($this->_properties[$property])) {
 			$value =& $this->_properties[$property];

+ 7 - 4
src/ORM/Entity.php

@@ -54,10 +54,13 @@ class Entity implements EntityInterface {
 			'source' => null
 		];
 		$this->_className = get_class($this);
-		$this->set($properties, [
-			'setter' => $options['useSetters'],
-			'guard' => $options['guard']
-		]);
+
+		if (!empty($properties)) {
+			$this->set($properties, [
+				'setter' => $options['useSetters'],
+				'guard' => $options['guard']
+			]);
+		}
 
 		if ($options['markClean']) {
 			$this->clean();

+ 32 - 0
tests/TestCase/ORM/EntityTest.php

@@ -1037,4 +1037,36 @@ class EntityTest extends TestCase {
 		$this->assertEquals('foos', $entity->source());
 	}
 
+/**
+ * Provides empty values
+ *
+ * @return void
+ */
+	public function emptyNamesProvider() {
+		return [[''], [null], [false]];
+	}
+/**
+ * Tests that trying to get an empty propery name throws exception
+ *
+ * @dataProvider emptyNamesProvider
+ * @expectedException \InvalidArgumentException
+ * @return void
+ */
+	public function testEmptyProperties($property) {
+		$entity = new Entity();
+		$entity->get($property);
+	}
+
+/**
+ * Tests that setitng an empty property name does nothing
+ *
+ * @expectedException \InvalidArgumentException
+ * @dataProvider emptyNamesProvider
+ * @return void
+ */
+	public function testSetEmptyPropertyName($property) {
+		$entity = new Entity();
+		$entity->set($property, 'bar');
+	}
+
 }