Skip to content

Commit

Permalink
method fired after mapping + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mrcnpdlk committed Apr 14, 2020
1 parent 88946e8 commit 67315ae
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/JsonMapper.php
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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;
}

Expand Down
47 changes: 47 additions & 0 deletions tests/EventTest.php
@@ -0,0 +1,47 @@
<?php
/**
* Part of JsonMapper
*
* PHP version 5
*
* @category Tools
* @package JsonMapper
* @author Christian Weiske <cweiske@cweiske.de>
* @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 <cweiske@cweiske.de>
* @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);
}
}
?>
13 changes: 13 additions & 0 deletions tests/JsonMapperTest/EventObject.php
@@ -0,0 +1,13 @@
<?php
class JsonMapperTest_EventObject
{
/**
* @var string
*/
public $pStr;

private function _deserializePostEvent(){
$this->pStr = 'two';
}
}
?>

0 comments on commit 67315ae

Please sign in to comment.