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

AddConfigAction   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 107
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 80.85%

Importance

Changes 0
Metric Value
dl 0
loc 107
ccs 38
cts 47
cp 0.8085
rs 10
c 0
b 0
f 0
wmc 8
lcom 1
cbo 13

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
B process() 0 54 6
A getConfiguration() 0 7 1
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\Domain\Entities\User;
16
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
17
use SlayerBirden\DataFlowServer\Notification\SuccessMessage;
18
use Zend\Diactoros\Response\JsonResponse;
19
use Zend\Hydrator\ClassMethods;
20
use Zend\Hydrator\ExtractionInterface;
21
use Zend\Hydrator\HydratorInterface;
22
use Zend\InputFilter\InputFilterInterface;
23
24
class AddConfigAction implements MiddlewareInterface
25
{
26
    /**
27
     * @var EntityManagerInterface
28
     */
29
    private $entityManager;
30
    /**
31
     * @var ClassMethods
32
     */
33
    private $hydrator;
34
    /**
35
     * @var InputFilterInterface
36
     */
37
    private $inputFilter;
38
    /**
39
     * @var LoggerInterface
40
     */
41
    private $logger;
42
    /**
43
     * @var ExtractionInterface
44
     */
45
    private $extractor;
46
47 3
    public function __construct(
48
        EntityManagerInterface $entityManager,
49
        HydratorInterface $hydrator,
50
        InputFilterInterface $inputFilter,
51
        LoggerInterface $logger,
52
        ExtractionInterface $extractor
53
    ) {
54 3
        $this->entityManager = $entityManager;
55 3
        $this->hydrator = $hydrator;
0 ignored issues
show
Documentation Bug introduced by
$hydrator is of type object<Zend\Hydrator\HydratorInterface>, but the property $hydrator was declared to be of type object<Zend\Hydrator\ClassMethods>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
56 3
        $this->inputFilter = $inputFilter;
57 3
        $this->logger = $logger;
58 3
        $this->extractor = $extractor;
59 3
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
65
    {
66 3
        $data = $request->getParsedBody();
67
68
        // todo get owner
69
        #### get current user
70 3
        $user = $this->entityManager
71 3
            ->getRepository(User::class)
72 3
            ->find(1);
73 3
        $data['owner'] = $user;
74
        ###
75
76 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 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...
77
78 3
        $message = null;
79 3
        $validation = [];
80 3
        $created = false;
81 3
        $status = 200;
82
83 3
        if ($this->inputFilter->isValid()) {
84
            try {
85 2
                $config = $this->getConfiguration($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 66 can also be of type object; however, SlayerBirden\DataFlowSer...ion::getConfiguration() 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...
86 2
                $this->entityManager->persist($config);
87 2
                $this->entityManager->flush();
88 2
                $message = new SuccessMessage('Configuration has been successfully created!');
89 2
                $created = true;
90
            } catch (ORMInvalidArgumentException $exception) {
91
                $message = new DangerMessage($exception->getMessage());
92
                $status = 400;
93
            } catch (ORMException $exception) {
94
                $this->logger->error((string)$exception);
95
                $message = new DangerMessage('Error during creation operation.');
96
                $status = 400;
97
            }
98
        } else {
99 1
            foreach ($this->inputFilter->getInvalidInput() as $key => $input) {
100 1
                $message = new DangerMessage('There were validation errors.');
101
                $validation[] = [
102 1
                    'field' => $key,
103 1
                    'msg' => reset($input->getMessages())
0 ignored issues
show
Bug introduced by
$input->getMessages() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
104
                ];
105
            }
106
            $status = 400;
107
        }
108
109 2
        return new JsonResponse([
110 2
            'msg' => $message,
111 2
            'success' => $created,
112
            'data' => [
113 2
                'validation' => $validation,
114 2
                'configuration' => !empty($config) ? $this->extractor->extract($config) : null,
115
            ]
116 2
        ], $status);
117
    }
118
119
    /**
120
     * @param array $data
121
     * @return DbConfiguration
122
     */
123 2
    private function getConfiguration(array $data): DbConfiguration
124
    {
125 2
        $config = new DbConfiguration();
126 2
        $this->hydrator->hydrate($data, $config);
127
128 2
        return $config;
129
    }
130
}
131