1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace SlayerBirden\DataFlowServer\Db\Controller; |
5
|
|
|
|
6
|
|
|
use Doctrine\ORM\ORMException; |
7
|
|
|
use Doctrine\ORM\ORMInvalidArgumentException; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
12
|
|
|
use Psr\Log\LoggerInterface; |
13
|
|
|
use SlayerBirden\DataFlowServer\Db\Entities\DbConfiguration; |
14
|
|
|
use SlayerBirden\DataFlowServer\Doctrine\Persistence\EntityManagerRegistry; |
15
|
|
|
use SlayerBirden\DataFlowServer\Stdlib\Request\Parser; |
16
|
|
|
use SlayerBirden\DataFlowServer\Stdlib\ResponseFactory; |
17
|
|
|
use SlayerBirden\DataFlowServer\Validation\Exception\ValidationException; |
18
|
|
|
use Zend\Hydrator\HydratorInterface; |
19
|
|
|
|
20
|
|
|
final class AddConfigAction implements MiddlewareInterface |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var HydratorInterface |
24
|
|
|
*/ |
25
|
|
|
private $hydrator; |
26
|
|
|
/** |
27
|
|
|
* @var LoggerInterface |
28
|
|
|
*/ |
29
|
|
|
private $logger; |
30
|
|
|
/** |
31
|
|
|
* @var EntityManagerRegistry |
32
|
|
|
*/ |
33
|
|
|
private $managerRegistry; |
34
|
|
|
|
35
|
10 |
|
public function __construct( |
36
|
|
|
EntityManagerRegistry $managerRegistry, |
37
|
|
|
HydratorInterface $hydrator, |
38
|
|
|
LoggerInterface $logger |
39
|
|
|
) { |
40
|
10 |
|
$this->managerRegistry = $managerRegistry; |
41
|
10 |
|
$this->hydrator = $hydrator; |
42
|
10 |
|
$this->logger = $logger; |
43
|
10 |
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @inheritdoc |
47
|
|
|
*/ |
48
|
10 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
49
|
|
|
{ |
50
|
10 |
|
$data = Parser::getRequestBody($request); |
51
|
|
|
|
52
|
|
|
try { |
53
|
10 |
|
$config = new DbConfiguration(); |
54
|
10 |
|
$this->hydrator->hydrate($data, $config); |
55
|
10 |
|
$em = $this->managerRegistry->getManagerForClass(DbConfiguration::class); |
56
|
10 |
|
$em->persist($config); |
57
|
6 |
|
$em->flush(); |
58
|
6 |
|
$msg = 'Configuration has been successfully created!'; |
59
|
6 |
|
return (new ResponseFactory())($msg, 200, 'configuration', $this->hydrator->extract($config)); |
60
|
4 |
|
} catch (ORMInvalidArgumentException | ValidationException $exception) { |
61
|
4 |
|
return (new ResponseFactory())($exception->getMessage(), 400, 'configuration'); |
62
|
|
|
} catch (ORMException $exception) { |
63
|
|
|
$this->logger->error((string)$exception); |
64
|
|
|
return (new ResponseFactory())('Error during creation operation.', 400, 'configuration'); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|