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\Middleware\ResourceMiddlewareInterface; |
15
|
|
|
use SlayerBirden\DataFlowServer\Doctrine\Persistence\EntityManagerRegistry; |
16
|
|
|
use SlayerBirden\DataFlowServer\Stdlib\Request\Parser; |
17
|
|
|
use SlayerBirden\DataFlowServer\Stdlib\ResponseFactory; |
18
|
|
|
use SlayerBirden\DataFlowServer\Validation\Exception\ValidationException; |
19
|
|
|
use Zend\Hydrator\HydratorInterface; |
20
|
|
|
|
21
|
|
|
final class UpdateConfigAction implements MiddlewareInterface |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var LoggerInterface |
25
|
|
|
*/ |
26
|
|
|
private $logger; |
27
|
|
|
/** |
28
|
|
|
* @var HydratorInterface |
29
|
|
|
*/ |
30
|
|
|
private $hydrator; |
31
|
|
|
/** |
32
|
|
|
* @var EntityManagerRegistry |
33
|
|
|
*/ |
34
|
|
|
private $managerRegistry; |
35
|
|
|
|
36
|
4 |
|
public function __construct( |
37
|
|
|
EntityManagerRegistry $managerRegistry, |
38
|
|
|
HydratorInterface $hydrator, |
39
|
|
|
LoggerInterface $logger |
40
|
|
|
) { |
41
|
4 |
|
$this->managerRegistry = $managerRegistry; |
42
|
4 |
|
$this->hydrator = $hydrator; |
43
|
4 |
|
$this->logger = $logger; |
44
|
4 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @inheritdoc |
48
|
|
|
*/ |
49
|
4 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
50
|
|
|
{ |
51
|
4 |
|
$data = Parser::getRequestBody($request); |
52
|
4 |
|
$dbConfig = $request->getAttribute(ResourceMiddlewareInterface::DATA_RESOURCE); |
53
|
|
|
try { |
54
|
4 |
|
$this->hydrator->hydrate($data, $dbConfig); |
55
|
4 |
|
$em = $this->managerRegistry->getManagerForClass(DbConfiguration::class); |
56
|
4 |
|
$em->persist($dbConfig); |
57
|
4 |
|
$em->flush(); |
58
|
4 |
|
$msg = 'Configuration has been updated!'; |
59
|
4 |
|
return (new ResponseFactory())($msg, 200, 'configuration', $this->hydrator->extract($dbConfig)); |
60
|
|
|
} catch (ORMInvalidArgumentException | ValidationException $exception) { |
61
|
|
|
return (new ResponseFactory())($exception->getMessage(), 400, 'configuration'); |
62
|
|
|
} catch (ORMException $exception) { |
63
|
|
|
$this->logger->error((string)$exception); |
64
|
|
|
return (new ResponseFactory())('Error while updating configuration.', 400, 'configuration'); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|