Browse files

Add and test ObjectAccessor.

  • Loading branch information...
1 parent 23c7e5f commit 8d6ac1d75528b3e4bc7f6e8dc1d1ccc3b6fecfb9 @lukemorton lukemorton committed May 17, 2012
Showing with 97 additions and 0 deletions.
  1. +47 −0 classes/TheCure/ObjectAccessor.php
  2. +50 −0 test/unit/classes/TheCure/Specs/ObjectAccessor.php
View
47 classes/TheCure/ObjectAccessor.php
@@ -0,0 +1,47 @@
+<?php
+/**
+ * An accessor class for data transfer objects
+ *
+ * @example
+ *
+ * $accessor = new ObjectAccessor;
+ * $model = new Models\User;
+ * $accessor->set($model, new Object(array(...)));
+ * $object = $accessor->get($model);
+ *
+ * // For convinience plain arrays are also supported
+ * $accessor->set($model, array(...));
+ *
+ * @package TheCure
+ * @category ObjectAccessor
+ * @copyright Gignite, 2012
+ * @license MIT
+ */
+namespace TheCure;
+
+use TheCure\Models\Model;
+use TheCure\Object;
+
+class ObjectAccessor {
+
+ public function get(Model $model)
+ {
+ return $model->__object();
+ }
+
+ protected function set_object(Model $model, Object $object)
+ {
+ $model->__object($object);
+ }
+
+ public function set(Model $model, $object)
+ {
+ if (is_array($object))
+ {
+ $object = new Object($object);
+ }
+
+ $this->set_object($model, $object);
+ }
+
+}
View
50 test/unit/classes/TheCure/Specs/ObjectAccessor.php
@@ -0,0 +1,50 @@
+<?php
+namespace TheCure\Specs;
+/**
+ * Test the accessor object for setting and getting the
+ * data transfer object to and from a model.
+ *
+ * @package TheCure
+ * @category ObjectAccessor
+ * @category Spec
+ * @category Test
+ * @copyright Gignite, 2012
+ * @license MIT
+ *
+ * @group specs
+ * @group objectaccessor
+ */
+use TheCure\ObjectAccessor;
+use TheCure\Object;
+use TheCure\Models\User\Magic as User;
+
+class ObjectAccessorTest extends \PHPUnit_Framework_TestCase {
+
+ public function testItShouldSetObject()
+ {
+ $model = new User;
+ $accessor = new ObjectAccessor;
+ $accessor->set($model, new Object(array('name' => 'Luke')));
+ $this->assertSame('Luke', $model->name());
+ }
+
+ public function testItShouldGetObject()
+ {
+ $model = new User;
+ $model->__object(new Object(array('name' => 'Luke')));
+ $accessor = new ObjectAccessor;
+ $object = $accessor->get($model);
+ $this->assertInstanceOf('TheCure\Object', $object);
+ $this->assertSame('Luke', $object->name);
+ }
+
+ public function testItShouldConvertArrayToObjectWhenSetting()
+ {
+ $model = new User;
+ $accessor = new ObjectAccessor;
+ $accessor->set($model, array('name' => 'Luke'));
+ $this->assertInstanceOf('TheCure\Object', $model->__object());
+ }
+
+}
+

0 comments on commit 8d6ac1d

Please sign in to comment.