Completed
Push — master ( d99c9e...a21e34 )
by Oleg
05:49
created

UpdateConfigAction::process()   B

Complexity

Conditions 7
Paths 15

Size

Total Lines 52
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 7.3318

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 52
ccs 30
cts 37
cp 0.8108
rs 7.2396
cc 7
eloc 40
nc 15
nop 2
crap 7.3318

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 Interop\Http\ServerMiddleware\DelegateInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\ServerRequestInterface;
12
use Interop\Http\ServerMiddleware\MiddlewareInterface;
13
use Psr\Log\LoggerInterface;
14
use SlayerBirden\DataFlowServer\Db\Entities\DbConfiguration;
15
use SlayerBirden\DataFlowServer\Doctrine\Exception\NonExistingEntity;
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\HydratorInterface;
21
use Zend\InputFilter\InputFilterInterface;
22
23
class UpdateConfigAction implements MiddlewareInterface
24
{
25
    /**
26
     * @var EntityManagerInterface
27
     */
28
    private $entityManager;
29
    /**
30
     * @var ExtractionInterface
31
     */
32
    private $extraction;
33
    /**
34
     * @var LoggerInterface
35
     */
36
    private $logger;
37
    /**
38
     * @var HydratorInterface
39
     */
40
    private $hydrator;
41
    /**
42
     * @var InputFilterInterface
43
     */
44
    private $inputFilter;
45
46 3
    public function __construct(
47
        EntityManagerInterface $entityManager,
48
        HydratorInterface $hydrator,
49
        InputFilterInterface $inputFilter,
50
        LoggerInterface $logger,
51
        ExtractionInterface $extraction
52
    ) {
53 3
        $this->entityManager = $entityManager;
54 3
        $this->hydrator = $hydrator;
55 3
        $this->inputFilter = $inputFilter;
56 3
        $this->logger = $logger;
57 3
        $this->extraction = $extraction;
58 3
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63 3
    public function process(ServerRequestInterface $request, DelegateInterface $handler): ResponseInterface
64
    {
65
        // todo check current user
66 3
        $data = $request->getParsedBody();
67 3
        $id = (int)$request->getAttribute('id');
68
69 3
        $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...
70
71 3
        $message = null;
72 3
        $validation = [];
73 3
        $updated = false;
74 3
        $status = 200;
75
76 3
        if ($this->inputFilter->isValid()) {
77
            try {
78 2
                $config = $this->getConfig($id, $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...
79 1
                $this->entityManager->persist($config);
80 1
                $this->entityManager->flush();
81 1
                $message = new SuccessMessage('Configuration has been updated!');
82 1
                $updated = true;
83 1
            } catch (NonExistingEntity $exception) {
84 1
                $message = new DangerMessage($exception->getMessage());
85 1
                $status = 404;
86
            } catch (ORMInvalidArgumentException $exception) {
87
                $message = new DangerMessage($exception->getMessage());
88
                $status = 400;
89
            } catch (ORMException $exception) {
90
                $this->logger->error((string)$exception);
91
                $message = new DangerMessage('Error while updating configuration.');
92
                $status = 400;
93
            }
94
        } else {
95 1
            foreach ($this->inputFilter->getInvalidInput() as $key => $input) {
96 1
                $message = new DangerMessage('There were validation errors.');
97 1
                $messages = $input->getMessages();
98 1
                $validation[] = [
99 1
                    'field' => $key,
100 1
                    'msg' => reset($messages)
101
                ];
102
            }
103 1
            $status = 400;
104
        }
105
106 3
        return new JsonResponse([
107 3
            'msg' => $message,
108 3
            'success' => $updated,
109
            'data' => [
110 1
                'configuration' => !empty($config) ? $this->extraction->extract($config) : null,
111 3
                'validation' => $validation,
112
            ]
113 3
        ], $status);
114
    }
115
116 2
    private function getConfig(int $id, array $data): DbConfiguration
117
    {
118
        /** @var DbConfiguration $config */
119 2
        $config = $this->entityManager->find(DbConfiguration::class, $id);
120 2
        if (!$config) {
121 1
            throw new NonExistingEntity(sprintf('Could not find config by id %d.', $id));
122
        }
123 1
        if (isset($data['id'])) {
124
            unset($data['id']);
125
        }
126
        // todo set current user as owner
127 1
        $this->hydrator->hydrate($data, $config);
128
129 1
        return $config;
130
    }
131
}
132