1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Anfischer\Foundation\Job\Concerns; |
4
|
|
|
|
5
|
|
|
use ArrayAccess; |
6
|
|
|
use Illuminate\Container\Container; |
7
|
|
|
use Illuminate\Support\Collection; |
8
|
|
|
use Illuminate\Support\Optional; |
9
|
|
|
use ReflectionClass; |
10
|
|
|
use ReflectionException; |
11
|
|
|
use ReflectionParameter; |
12
|
|
|
use RuntimeException; |
13
|
|
|
|
14
|
|
|
trait MarshalsJobs |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Marshal a command from the given array accessible object. |
18
|
|
|
* |
19
|
|
|
* @param string $command |
20
|
|
|
* @param ArrayAccess|null $source |
21
|
|
|
* @param array $extras |
22
|
|
|
* |
23
|
|
|
* @return mixed |
24
|
|
|
* |
25
|
|
|
* @throws RuntimeException |
26
|
|
|
*/ |
27
|
26 |
|
protected function marshal($command, ArrayAccess $source = null, array $extras = []) |
28
|
|
|
{ |
29
|
26 |
|
$params = (new Collection($source))->merge($extras); |
30
|
|
|
|
31
|
26 |
|
if (\is_object($command)) { |
|
|
|
|
32
|
6 |
|
return $command; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
try { |
36
|
22 |
|
$reflection = new ReflectionClass($command); |
37
|
20 |
|
$constructorParameters = (new Optional($reflection->getConstructor()))->getParameters(); |
38
|
|
|
|
39
|
|
|
$injected = array_map(function ($parameter) use ($command, $params) { |
40
|
14 |
|
return $this->mapParameterValueForCommand($command, $params, $parameter); |
41
|
20 |
|
}, $constructorParameters ?? []); |
42
|
|
|
|
43
|
18 |
|
return $reflection->newInstanceArgs($injected); |
44
|
4 |
|
} catch (ReflectionException $e) { |
45
|
2 |
|
throw new RuntimeException( |
46
|
2 |
|
"Unable to reflect on class {$command}. Are you sure it exists and is available for autoload?" |
47
|
|
|
); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Maps a source/extra value to the commands constructor parameter. |
53
|
|
|
* |
54
|
|
|
* @param $command |
55
|
|
|
* @param ArrayAccess $source |
56
|
|
|
* @param ReflectionParameter $parameter |
57
|
|
|
* |
58
|
|
|
* @return \Illuminate\Foundation\Application|mixed |
59
|
|
|
* |
60
|
|
|
* @throws \Exception |
61
|
|
|
*/ |
62
|
14 |
|
protected function mapParameterValueForCommand($command, ArrayAccess $source, ReflectionParameter $parameter) |
63
|
|
|
{ |
64
|
14 |
|
if (isset($source[$parameter->name])) { |
65
|
8 |
|
return $source[$parameter->name]; |
66
|
|
|
} |
67
|
|
|
|
68
|
10 |
|
if ($parameter->isDefaultValueAvailable()) { |
69
|
6 |
|
return $parameter->getDefaultValue(); |
70
|
|
|
} |
71
|
|
|
|
72
|
4 |
|
if ($parameter->hasType() && ! $parameter->getType()->isBuiltin()) { |
73
|
2 |
|
return (new Container)->getInstance()->make($parameter->getClass()->getName()); |
74
|
|
|
} |
75
|
|
|
|
76
|
2 |
|
throw new RuntimeException("Unable to map parameter [{$parameter->name}] to command [{$command}]"); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|