|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the daikon-cqrs/message-bus project. |
|
4
|
|
|
* |
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
6
|
|
|
* file that was distributed with this source code. |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
declare(strict_types=1); |
|
10
|
|
|
|
|
11
|
|
|
namespace Daikon\MessageBus; |
|
12
|
|
|
|
|
13
|
|
|
trait FromArrayTrait |
|
14
|
|
|
{ |
|
15
|
|
|
public static function fromArray(array $arrayState): MessageInterface |
|
16
|
|
|
{ |
|
17
|
|
|
$classReflection = new \ReflectionClass(static::class); |
|
18
|
|
|
$classes = [ $classReflection ]; |
|
19
|
|
|
$parent = $classReflection; |
|
20
|
|
|
while ($parent = $parent->getParentClass()) { |
|
21
|
|
|
$classes[] = $parent; |
|
22
|
|
|
} |
|
23
|
|
|
$valueFactories = []; |
|
24
|
|
|
foreach ($classes as $curClass) { |
|
25
|
|
|
$classProps = $curClass->getProperties(); |
|
26
|
|
|
foreach ($classProps as $prop) { |
|
27
|
|
|
$propName = $prop->getName(); |
|
28
|
|
|
$docBlock = $prop->getDocComment(); |
|
29
|
|
|
if (!preg_match("/@MessageBus::deserialize\((.*)\)/", $docBlock, $matches)) { |
|
30
|
|
|
continue; |
|
31
|
|
|
} |
|
32
|
|
|
$factoryMethod = $matches[1]; |
|
33
|
|
|
if ($factoryMethod === '$ctor') { |
|
34
|
|
|
$valueFactories[$propName] = function ($value) use ($valueImplementor) { |
|
|
|
|
|
|
35
|
|
|
return new $valueImplementor($value); |
|
36
|
|
|
}; |
|
37
|
|
|
} else { |
|
38
|
|
|
$valueFactories[$propName] = $factoryMethod; |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
$ctorReflection = $classReflection->getMethod("__construct"); |
|
43
|
|
|
$ctorArgs = []; |
|
44
|
|
|
foreach ($ctorReflection->getParameters() as $argumentReflection) { |
|
45
|
|
|
$argName = $argumentReflection->getName(); |
|
46
|
|
|
if (isset($arrayState[$argName])) { |
|
47
|
|
|
if (isset($valueFactories[$argName])) { |
|
48
|
|
|
$ctorArgs[] = call_user_func($valueFactories[$argName], $arrayState[$argName]); |
|
49
|
|
|
} else { |
|
|
|
|
|
|
50
|
|
|
// missing factory annoation, throw exception or ignore? |
|
51
|
|
|
} |
|
52
|
|
|
} elseif ($argumentReflection->allowsNull()) { |
|
53
|
|
|
$ctorArgs[] = null; |
|
54
|
|
|
} else { |
|
55
|
|
|
throw new \Exception("Missing required value for array-key: $argName while constructing from array"); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
return new static(...$ctorArgs); |
|
|
|
|
|
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.