|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace hiapi\Core\commands; |
|
5
|
|
|
|
|
6
|
|
|
use hiapi\commands\BulkCommand; |
|
7
|
|
|
use hiapi\Core\Endpoint\Endpoint; |
|
8
|
|
|
use hiapi\endpoints\Module\InOutControl\VO\Collection; |
|
9
|
|
|
use hiapi\exceptions\ConfigurationException; |
|
10
|
|
|
use hiapi\exceptions\HiapiException; |
|
11
|
|
|
use Psr\Container\ContainerInterface; |
|
12
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
13
|
|
|
use yii\base\Model; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Creates command by given data: name and request. |
|
17
|
|
|
* - takes data from POST or (if it is empty) from GET request, |
|
18
|
|
|
* - trims all the values and tries to load them to the command. |
|
19
|
|
|
*/ |
|
20
|
|
|
class CommandFactory |
|
21
|
|
|
{ |
|
22
|
|
|
private ContainerInterface $di; |
|
|
|
|
|
|
23
|
|
|
|
|
24
|
|
|
public function __construct(ContainerInterface $di) |
|
25
|
|
|
{ |
|
26
|
|
|
$this->di = $di; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function createByEndpoint(Endpoint $endpoint, ServerRequestInterface $request): Model |
|
30
|
|
|
{ |
|
31
|
|
|
$data = $this->extractData($request); |
|
32
|
|
|
$command = $this->createCommand($endpoint); |
|
33
|
|
|
$successLoad = $command->load($data, ''); |
|
34
|
|
|
if (!$successLoad && !empty($data)) { |
|
35
|
|
|
throw new HiapiException('Failed to load command data'); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
return $command; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
private function createCommand(Endpoint $endpoint): Model |
|
42
|
|
|
{ |
|
43
|
|
|
$inputType = $endpoint->inputType; |
|
44
|
|
|
if ($inputType instanceof Collection) { |
|
45
|
|
|
$command = BulkCommand::of($inputType->getEntriesClass(), $this); |
|
46
|
|
|
} else { |
|
47
|
|
|
$command = $this->createByClass($inputType); |
|
48
|
|
|
} |
|
49
|
|
|
if (!$command instanceof Model) { |
|
50
|
|
|
throw new ConfigurationException('This middleware can load only commands of Model class'); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
return $command; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function createByClass(string $className): Model |
|
57
|
|
|
{ |
|
58
|
|
|
return $this->di->get($className); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
private function extractData(ServerRequestInterface $request): array |
|
62
|
|
|
{ |
|
63
|
|
|
$data = array_merge($request->getParsedBody(), $request->getQueryParams()); |
|
64
|
|
|
array_walk_recursive($data, static function (&$value) { |
|
65
|
|
|
if (\is_string($value)) { |
|
66
|
|
|
$value = trim($value); |
|
67
|
|
|
} |
|
68
|
|
|
}); |
|
69
|
|
|
|
|
70
|
|
|
return $data; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|