1 | <?php |
||
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 | |||
73 |