diff --git a/src/TypeCast/Handler/ObjectHandler.php b/src/TypeCast/Handler/ObjectHandler.php new file mode 100644 index 0000000..1da77ee --- /dev/null +++ b/src/TypeCast/Handler/ObjectHandler.php @@ -0,0 +1,44 @@ +metaCast = $metaCast; + } + + /** + * Create object using __set_state. + * + * @param mixed $value + * @return object|mixed + */ + protected function createWithSetState($value) + { + $value = $this->metaCast->cast($this->class, $value); + + return parent::createWithSetState($value); + } +} diff --git a/tests/TypeCast/Handler/ObjectHandlerTest.php b/tests/TypeCast/Handler/ObjectHandlerTest.php new file mode 100644 index 0000000..267bdf1 --- /dev/null +++ b/tests/TypeCast/Handler/ObjectHandlerTest.php @@ -0,0 +1,60 @@ +getObjectClass(); + $data = ['x' => 'x_value', 'y' => 'y_value']; + $casted = ['x' => 'casted_x_value', 'y' => 'casted_y_value']; + + $metaCast = $this->createMock(MetaCast::class); + $metaCast->expects($this->once())->method('cast')->with($class, $data)->willReturn($casted); + + $handler = new ObjectHandler($metaCast); + $handler = $handler->forType($class); + + $result = $handler->cast($data); + + $this->assertInstanceOf($class, $result); + $this->assertSame($casted['x'], $result->x); + $this->assertSame($casted['y'], $result->y); + } + + /** + * Get target class for casting + * + * @return string + */ + protected function getObjectClass() + { + $object = new class() { + public $x; + public $y; + + public static function __set_state(array $data) + { + $foobar = new self(); + + if (isset($data['x'])) $foobar->x = $data['x']; + if (isset($data['y'])) $foobar->y = $data['y']; + + return $foobar; + } + }; + + return get_class($object); + } +}