|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Simplex\Quickstart\Shared\Controller; |
|
4
|
|
|
|
|
5
|
|
|
use Lukasoppermann\Httpstatus\Httpstatuscodes; |
|
6
|
|
|
use JMS\Serializer\Exception\Exception as SerializerException; |
|
7
|
|
|
use League\Tactician\CommandBus; |
|
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
|
|
|
public function setCommandBus(CommandBus $commandBus): void |
|
22
|
|
|
{ |
|
23
|
|
|
$this->commandBus = $commandBus; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function setValidator(ValidatorInterface $validator): void |
|
27
|
|
|
{ |
|
28
|
|
|
$this->validator = $validator; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** @return mixed */ |
|
32
|
|
|
public function map(Request $request, string $commandClass) |
|
33
|
|
|
{ |
|
34
|
|
|
$command = $this->deserializeRequest($request, $commandClass); |
|
35
|
|
|
|
|
36
|
|
|
$this->validateRequest($command); |
|
37
|
|
|
|
|
38
|
|
|
return $command; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function handleCommand($command): void |
|
42
|
|
|
{ |
|
43
|
|
|
$this->commandBus->handle($command); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** @return mixed */ |
|
47
|
|
|
private function deserializeRequest(Request $request, string $commandClass) |
|
48
|
|
|
{ |
|
49
|
|
|
try { |
|
50
|
|
|
$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
|
|
|
return $command; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
private function validateRequest($command): void |
|
59
|
|
|
{ |
|
60
|
|
|
$violations = $this->validator->validate($command); |
|
61
|
|
|
|
|
62
|
|
|
if ($violations->count() > 0) { |
|
63
|
|
|
|
|
64
|
|
|
$exception = new BadRequestException("Validation failure", Httpstatuscodes::HTTP_BAD_REQUEST); |
|
65
|
|
|
$exception->setViolations($violations); |
|
66
|
|
|
|
|
67
|
|
|
throw $exception; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|