From 25f4647ff9564d1b0694874cae560fa61cab9db0 Mon Sep 17 00:00:00 2001 From: Sergey Boltonosov Date: Mon, 1 Oct 2018 20:22:40 +0700 Subject: [PATCH] Added object type-casting handler (fixes #7) --- src/TypeCast/Handler/ObjectHandler.php | 44 ++++++++++++++ tests/TypeCast/Handler/ObjectHandlerTest.php | 60 ++++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 src/TypeCast/Handler/ObjectHandler.php create mode 100644 tests/TypeCast/Handler/ObjectHandlerTest.php 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); + } +}