Completed
Push — master ( 2ef37c...52cad6 )
by Oleg
02:13
created

GetConfigAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 3
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 1
rs 9.6666
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Db\Controller;
5
6
use Doctrine\ORM\EntityManagerInterface;
7
use Doctrine\ORM\ORMException;
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\Notification\DangerMessage;
15
use Zend\Diactoros\Response\JsonResponse;
16
use Zend\Hydrator\ExtractionInterface;
17
18
class GetConfigAction implements MiddlewareInterface
19
{
20
    /**
21
     * @var EntityManagerInterface
22
     */
23
    private $entityManager;
24
    /**
25
     * @var LoggerInterface
26
     */
27
    private $logger;
28
    /**
29
     * @var ExtractionInterface
30
     */
31
    private $extraction;
32
33 2
    public function __construct(
34
        EntityManagerInterface $entityManager,
35
        LoggerInterface $logger,
36
        ExtractionInterface $extraction
37
    ) {
38 2
        $this->entityManager = $entityManager;
39 2
        $this->logger = $logger;
40 2
        $this->extraction = $extraction;
41 2
    }
42
43
    /**
44
     * @inheritdoc
45
     */
46 2
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
47
    {
48 2
        $id = $request->getAttribute('id');
49 2
        $success = false;
50 2
        $msg = '';
51 2
        $status = 200;
52
53
        try {
54 2
            $config = $this->entityManager
55 2
                ->getRepository(DbConfiguration::class)
56 2
                ->find($id);
57 1
            if ($config !== null) {
58
                $success = true;
59
            } else {
60 1
                $msg = new DangerMessage('Could not find configuration.');
61 1
                $status = 404;
62
            }
63
        } catch (ORMException $exception) {
64
            $this->logger->error((string)$exception);
65
            $msg = new DangerMessage('Could not find configuration. An error occurred.');
66
            $status = 400;
67
        }
68
69 1
        return new JsonResponse([
70 1
            'data' => [
71
                'configuration' => !empty($config) ? $this->extraction->extract($config) : null,
72
            ],
73 1
            'success' => $success,
74 1
            'msg' => $msg,
75 1
        ], $status);
76
    }
77
}
78