1
|
|
|
<?php |
2
|
|
|
namespace rtens\domin; |
3
|
|
|
|
4
|
|
|
use rtens\domin\delivery\FieldRegistry; |
5
|
|
|
use rtens\domin\delivery\ParameterReader; |
6
|
|
|
use rtens\domin\execution\ExecutionResult; |
7
|
|
|
use rtens\domin\execution\FailedResult; |
8
|
|
|
use rtens\domin\execution\MissingParametersResult; |
9
|
|
|
use rtens\domin\execution\NoResult; |
10
|
|
|
use rtens\domin\execution\ValueResult; |
11
|
|
|
|
12
|
|
|
class Executor { |
13
|
|
|
|
14
|
|
|
/** @var ActionRegistry */ |
15
|
|
|
private $actions; |
16
|
|
|
|
17
|
|
|
/** @var FieldRegistry */ |
18
|
|
|
private $fields; |
19
|
|
|
|
20
|
|
|
/** @var ParameterReader */ |
21
|
|
|
private $paramReader; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param ActionRegistry $actions <- |
25
|
|
|
* @param FieldRegistry $fields <- |
26
|
|
|
* @param ParameterReader $reader <- |
27
|
|
|
*/ |
28
|
|
|
public function __construct(ActionRegistry $actions, FieldRegistry $fields, ParameterReader $reader) { |
29
|
|
|
$this->actions = $actions; |
30
|
|
|
$this->fields = $fields; |
31
|
|
|
$this->paramReader = $reader; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param $id |
36
|
|
|
* @return ExecutionResult |
37
|
|
|
*/ |
38
|
|
|
public function execute($id) { |
39
|
|
|
try { |
40
|
|
|
$action = $this->actions->getAction($id); |
41
|
|
|
|
42
|
|
|
list($params, $missing) = $this->readParameters($action); |
43
|
|
|
|
44
|
|
|
if (!empty($missing)) { |
45
|
|
|
return new MissingParametersResult($missing); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$returned = $action->execute($params); |
49
|
|
|
|
50
|
|
|
if (is_null($returned)) { |
51
|
|
|
return new NoResult(); |
52
|
|
|
} else if ($returned instanceof ExecutionResult) { |
53
|
|
|
return $returned; |
54
|
|
|
} else { |
55
|
|
|
return new ValueResult($returned); |
56
|
|
|
} |
57
|
|
|
} catch (\Exception $e) { |
58
|
|
|
return new FailedResult($e); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
private function readParameters(Action $action) { |
63
|
|
|
$failed = []; |
64
|
|
|
$params = []; |
65
|
|
|
foreach ($action->parameters() as $parameter) { |
66
|
|
|
try { |
67
|
|
|
$params[$parameter->getName()] = $this->inflate($parameter); |
68
|
|
|
} catch (\Exception $e) { |
69
|
|
|
$failed[$parameter->getName()] = $e; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return [$params, $failed]; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
private function inflate(Parameter $parameter) { |
77
|
|
|
if ($this->paramReader->has($parameter)) { |
78
|
|
|
$inflated = $this->fields->getField($parameter) |
79
|
|
|
->inflate($parameter, $this->paramReader->read($parameter)); |
80
|
|
|
|
81
|
|
|
if ($parameter->getType()->is($inflated)) { |
82
|
|
|
return $inflated; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
if ($parameter->isRequired()) { |
87
|
|
|
throw new \Exception("[{$parameter->getName()}] is required."); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
return null; |
91
|
|
|
} |
92
|
|
|
} |