From 67315aeb377148588066b86e4008766b28396a61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Pude=C5=82ek?= Date: Wed, 15 Apr 2020 00:20:58 +0200 Subject: [PATCH] method fired after mapping + tests --- src/JsonMapper.php | 16 ++++++++++ tests/EventTest.php | 47 ++++++++++++++++++++++++++++ tests/JsonMapperTest/EventObject.php | 13 ++++++++ 3 files changed, 76 insertions(+) create mode 100644 tests/EventTest.php create mode 100644 tests/JsonMapperTest/EventObject.php diff --git a/src/JsonMapper.php b/src/JsonMapper.php index dc1d081bb9..78753fcfe2 100644 --- a/src/JsonMapper.php +++ b/src/JsonMapper.php @@ -119,6 +119,13 @@ class JsonMapper */ protected $arInspectedClasses = array(); + /** + * Custom name of method fired after deserialize process + * + * @var string|null method name + */ + public $postMappingMethodName = null; + /** * Map data all data in $json into the given $object instance. * @@ -296,6 +303,15 @@ public function map($json, $object) $this->removeUndefinedAttributes($object, $providedProperties); } + if ($this->postMappingMethodName !== null + && $rc->hasMethod($this->postMappingMethodName) + ) { + $refDeserializePostMethod = $rc + ->getMethod($this->postMappingMethodName); + $refDeserializePostMethod->setAccessible(true); + $refDeserializePostMethod->invoke($object); + } + return $object; } diff --git a/tests/EventTest.php b/tests/EventTest.php new file mode 100644 index 0000000000..e9b510ed31 --- /dev/null +++ b/tests/EventTest.php @@ -0,0 +1,47 @@ + + * @license OSL-3.0 http://opensource.org/licenses/osl-3.0 + * @link https://github.com/cweiske/jsonmapper + */ + +use PHPUnit\Framework\TestCase; + +require_once 'JsonMapperTest/EventObject.php'; + +/** + * Unit tests for JsonMapper's object handling (events) + * + * @category Tools + * @package JsonMapper + * @author Christian Weiske + * @license OSL-3.0 http://opensource.org/licenses/osl-3.0 + * @link https://github.com/cweiske/jsonmapper + */ +class EventTest extends TestCase +{ + /** + * Test for deserialize post event + * + * @throws \JsonMapper_Exception + */ + public function testDeserializePostEvent() + { + $jm = new JsonMapper(); + $jm->postMappingMethodName = '_deserializePostEvent'; + /** @var JsonMapperTest_EventObject $sn */ + $sn = $jm->map( + json_decode('{"pStr":"one"}', false), + new JsonMapperTest_EventObject() + ); + $this->assertIsString($sn->pStr); + $this->assertEquals('two', $sn->pStr); + } +} +?> diff --git a/tests/JsonMapperTest/EventObject.php b/tests/JsonMapperTest/EventObject.php new file mode 100644 index 0000000000..f0515ec52b --- /dev/null +++ b/tests/JsonMapperTest/EventObject.php @@ -0,0 +1,13 @@ +pStr = 'two'; + } +} +?>