Skip to content

Commit

Permalink
Merge pull request #6 from makasim/hook-class-take-priority-over-argu…
Browse files Browse the repository at this point in the history
…ment-class

Hook class should take priority over argument one.
  • Loading branch information
makasim authored Oct 20, 2017
2 parents a278680 + 7a914c4 commit 2384062
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 6 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "0.2-dev"
"dev-master": "0.3-dev"
}
}
}
8 changes: 3 additions & 5 deletions src/functions/values.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,9 @@ function get_object_changed_values($object)
*/
function build_object_ref($classOrClosure = null, array &$values, $context = null, $contextKey = null)
{
if (false == $classOrClosure) {
foreach (get_registered_hooks('build_object', 'get_object_class') as $callback) {
if ($classOrClosure = call_user_func($callback, $values, $context, $contextKey)) {
break;
}
foreach (get_registered_hooks('build_object', 'get_object_class') as $callback) {
if ($dynamicClassOrClosure = call_user_func($callback, $values, $context, $contextKey)) {
$classOrClosure = $dynamicClassOrClosure;
}
}

Expand Down
6 changes: 6 additions & 0 deletions tests/Model/OtherSubObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php
namespace Makasim\Values\Tests\Model;

class OtherSubObject extends Object
{
}
24 changes: 24 additions & 0 deletions tests/ObjectsTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use function Makasim\Values\register_object_hooks;
use function Makasim\Values\set_values;
use Makasim\Values\Tests\Model\Object;
use Makasim\Values\Tests\Model\OtherSubObject;
use Makasim\Values\Tests\Model\SubObject;
use PHPUnit\Framework\TestCase;

Expand Down Expand Up @@ -667,4 +668,27 @@ public function testShouldBuildObjectFromClassProvidedByHook()

$this->assertInstanceOf(SubObject::class, $subObj);
}

public function testClassProvidedByHookShouldTakePriorityOverClassAsArgument()
{
$values = [
'aKey' => [
'aSubName' => ['aSubKey' => 'aFooVal'],
],
];

$argumentClass = SubObject::class;
$hookClass = OtherSubObject::class;

$obj = new Object();
set_values($obj, $values);

register_hook('build_object', 'get_object_class', function($object, $key, $values) use ($hookClass) {
return $hookClass;
});

$subObj = get_object($obj, 'aKey', $argumentClass);

$this->assertInstanceOf($hookClass, $subObj);
}
}

0 comments on commit 2384062

Please sign in to comment.