1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace Simplex\Quickstart\Shared\Controller; |
4
|
|
|
|
5
|
|
|
use JMS\Serializer\Exception\Exception as SerializerException; |
6
|
|
|
use League\Tactician\CommandBus; |
7
|
|
|
use Lukasoppermann\Httpstatus\Httpstatuscodes; |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
9
|
|
|
use Simplex\BaseController; |
10
|
|
|
use Simplex\Quickstart\Shared\Exception\BadRequestException; |
11
|
|
|
use Symfony\Component\Validator\Validator\ValidatorInterface; |
12
|
|
|
|
13
|
|
|
abstract class AppController extends BaseController |
14
|
|
|
{ |
15
|
|
|
/** @var CommandBus */ |
16
|
|
|
private $commandBus; |
17
|
|
|
|
18
|
|
|
/** @var ValidatorInterface */ |
19
|
|
|
private $validator; |
20
|
|
|
|
21
|
6 |
|
public function setCommandBus(CommandBus $commandBus): void |
22
|
|
|
{ |
23
|
6 |
|
$this->commandBus = $commandBus; |
24
|
6 |
|
} |
25
|
|
|
|
26
|
6 |
|
public function setValidator(ValidatorInterface $validator): void |
27
|
|
|
{ |
28
|
6 |
|
$this->validator = $validator; |
29
|
6 |
|
} |
30
|
|
|
|
31
|
|
|
/** @return mixed */ |
32
|
4 |
|
public function map(Request $request, string $commandClass) |
33
|
|
|
{ |
34
|
4 |
|
$command = $this->deserializeRequest($request, $commandClass); |
35
|
|
|
|
36
|
4 |
|
$this->validateRequest($command); |
37
|
|
|
|
38
|
1 |
|
return $command; |
39
|
|
|
} |
40
|
|
|
|
41
|
1 |
|
public function handleCommand($command): void |
42
|
|
|
{ |
43
|
1 |
|
$this->commandBus->handle($command); |
44
|
1 |
|
} |
45
|
|
|
|
46
|
|
|
/** @return mixed */ |
47
|
4 |
|
private function deserializeRequest(Request $request, string $commandClass) |
48
|
|
|
{ |
49
|
|
|
try { |
50
|
4 |
|
$command = $this->serializer->deserialize((string) $request->getBody(), $commandClass, parent::JSON_FORMAT); |
51
|
|
|
} catch (SerializerException $exception) { |
52
|
|
|
throw new BadRequestException("Invalid request body", Httpstatuscodes::HTTP_BAD_REQUEST, $exception); |
53
|
|
|
} |
54
|
|
|
|
55
|
4 |
|
return $command; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** @param mixed $command */ |
59
|
4 |
|
private function validateRequest($command): void |
60
|
|
|
{ |
61
|
4 |
|
$violations = $this->validator->validate($command); |
62
|
|
|
|
63
|
4 |
|
if ($violations->count() > 0) { |
64
|
|
|
|
65
|
3 |
|
$exception = new BadRequestException("Validation failure", Httpstatuscodes::HTTP_BAD_REQUEST); |
66
|
3 |
|
$exception->setViolations($violations); |
67
|
|
|
|
68
|
3 |
|
throw $exception; |
69
|
|
|
} |
70
|
1 |
|
} |
71
|
|
|
} |
72
|
|
|
|