Completed
Push — master ( 298ac7...0024da )
by Oleg
12:58
created

UpdateConfigAction   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 108
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 78%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 11
dl 0
loc 108
ccs 39
cts 50
cp 0.78
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
B process() 0 57 7
A getConfig() 0 9 2
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 Doctrine\ORM\ORMInvalidArgumentException;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Psr\Log\LoggerInterface;
14
use SlayerBirden\DataFlowServer\Db\Entities\DbConfiguration;
15
use SlayerBirden\DataFlowServer\Doctrine\Middleware\ResourceMiddlewareInterface;
16
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
17
use SlayerBirden\DataFlowServer\Notification\SuccessMessage;
18
use Zend\Diactoros\Response\JsonResponse;
19
use Zend\Hydrator\ExtractionInterface;
20
use Zend\Hydrator\HydrationInterface;
21
use Zend\Hydrator\HydratorInterface;
22
use Zend\InputFilter\InputFilterInterface;
23
24
class UpdateConfigAction implements MiddlewareInterface
25
{
26
    /**
27
     * @var EntityManagerInterface
28
     */
29
    private $entityManager;
30
    /**
31
     * @var ExtractionInterface
32
     */
33
    private $extraction;
34
    /**
35
     * @var LoggerInterface
36
     */
37
    private $logger;
38
    /**
39
     * @var HydrationInterface
40
     */
41
    private $hydrator;
42
    /**
43
     * @var InputFilterInterface
44
     */
45
    private $inputFilter;
46
47 2
    public function __construct(
48
        EntityManagerInterface $entityManager,
49
        HydrationInterface $hydrator,
50
        InputFilterInterface $inputFilter,
51
        LoggerInterface $logger,
52
        ExtractionInterface $extraction
53
    ) {
54 2
        $this->entityManager = $entityManager;
55 2
        $this->hydrator = $hydrator;
56 2
        $this->inputFilter = $inputFilter;
57 2
        $this->logger = $logger;
58 2
        $this->extraction = $extraction;
59 2
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64 2
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
65
    {
66 2
        $data = $request->getParsedBody();
67 2
        $dbConfig = $request->getAttribute(ResourceMiddlewareInterface::DATA_RESOURCE);
68 2
        if (!$dbConfig) {
69
            return new JsonResponse([
70
                'msg' => new DangerMessage('Could not find Configuration.'),
71
                'success' => false,
72
                'data' => [
73
                    'configuration' => null,
74
                ]
75
            ], 404);
76
        }
77
78 2
        $this->inputFilter->setData($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 66 can also be of type null or object; however, Zend\InputFilter\InputFilterInterface::setData() does only seem to accept array|object<Traversable>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
79
80 2
        $message = null;
81 2
        $validation = [];
82 2
        $updated = false;
83 2
        $status = 200;
84
85 2
        if ($this->inputFilter->isValid()) {
86
            try {
87 1
                $config = $this->getConfig($dbConfig, $data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 66 can also be of type null or object; however, SlayerBirden\DataFlowSer...nfigAction::getConfig() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
88 1
                $this->entityManager->persist($config);
89 1
                $this->entityManager->flush();
90 1
                $message = new SuccessMessage('Configuration has been updated!');
91 1
                $updated = true;
92
            } catch (ORMInvalidArgumentException $exception) {
93
                $message = new DangerMessage($exception->getMessage());
94
                $status = 400;
95
            } catch (ORMException $exception) {
96
                $this->logger->error((string)$exception);
97
                $message = new DangerMessage('Error while updating configuration.');
98
                $status = 400;
99
            }
100
        } else {
101 1
            $message = new DangerMessage('There were validation errors.');
102 1
            foreach ($this->inputFilter->getInvalidInput() as $key => $input) {
103 1
                $messages = $input->getMessages();
104 1
                $validation[] = [
105 1
                    'field' => $key,
106 1
                    'msg' => reset($messages)
107
                ];
108
            }
109 1
            $status = 400;
110
        }
111
112 2
        return new JsonResponse([
113 2
            'msg' => $message,
114 2
            'success' => $updated,
115
            'data' => [
116 1
                'configuration' => !empty($config) ? $this->extraction->extract($config) : null,
117 2
                'validation' => $validation,
118
            ]
119 2
        ], $status);
120
    }
121
122 1
    private function getConfig(DbConfiguration $oldConfig, array $data): DbConfiguration
123
    {
124 1
        if (isset($data['id'])) {
125
            unset($data['id']);
126
        }
127 1
        $this->hydrator->hydrate($data, $oldConfig);
128
129 1
        return $oldConfig;
130
    }
131
}
132