Completed
Push — master ( 707446...d99c9e )
by Oleg
04:16
created

AddUserAction::getUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Domain\Controller;
5
6
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
7
use Doctrine\ORM\EntityManagerInterface;
8
use Doctrine\ORM\ORMException;
9
use Doctrine\ORM\ORMInvalidArgumentException;
10
use Psr\Http\Server\MiddlewareInterface;
11
use SlayerBirden\DataFlowServer\Domain\Entities\User;
12
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
13
use SlayerBirden\DataFlowServer\Notification\SuccessMessage;
14
use Psr\Http\Server\RequestHandlerInterface;
15
use Psr\Http\Message\ResponseInterface;
16
use Psr\Http\Message\ServerRequestInterface;
17
use Psr\Log\LoggerInterface;
18
use Zend\Diactoros\Response\JsonResponse;
19
use Zend\Hydrator\ExtractionInterface;
20
use Zend\Hydrator\HydratorInterface;
21
use Zend\InputFilter\InputFilterInterface;
22
23
class AddUserAction implements MiddlewareInterface
24
{
25
    /**
26
     * @var EntityManagerInterface
27
     */
28
    private $entityManager;
29
    /**
30
     * @var HydratorInterface
31
     */
32
    private $hydrator;
33
    /**
34
     * @var InputFilterInterface
35
     */
36
    private $inputFilter;
37
    /**
38
     * @var LoggerInterface
39
     */
40
    private $logger;
41
    /**
42
     * @var ExtractionInterface
43
     */
44
    private $extraction;
45
46 4
    public function __construct(
47
        EntityManagerInterface $entityManager,
48
        HydratorInterface $hydrator,
49
        InputFilterInterface $inputFilter,
50
        LoggerInterface $logger,
51
        ExtractionInterface $extraction
52
    ) {
53 4
        $this->entityManager = $entityManager;
54 4
        $this->hydrator = $hydrator;
55 4
        $this->inputFilter = $inputFilter;
56 4
        $this->logger = $logger;
57 4
        $this->extraction = $extraction;
58 4
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63 4
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
64
    {
65 4
        $data = $request->getParsedBody();
66
67 4
        $this->inputFilter->setData($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 65 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...
68
69 4
        $message = null;
70 4
        $validation = [];
71 4
        $created = false;
72 4
        $status = 200;
73
74 4
        if ($this->inputFilter->isValid()) {
75
            try {
76 2
                $entity = $this->getEntity($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 65 can also be of type null or object; however, SlayerBirden\DataFlowSer...UserAction::getEntity() 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...
77 2
                $this->entityManager->persist($entity);
78 2
                $this->entityManager->flush();
79 1
                $message = new SuccessMessage('User has been successfully created!');
80 1
                $created = true;
81 1
            } catch (ORMInvalidArgumentException $exception) {
82
                $message = new DangerMessage($exception->getMessage());
83
                $status = 400;
84 1
            } catch (UniqueConstraintViolationException $exception) {
85 1
                $message = new DangerMessage('Provided email already exists.');
86 1
                $status = 400;
87
            } catch (ORMException $exception) {
88
                $this->logger->error((string)$exception);
89
                $message = new DangerMessage('Error during creation operation.');
90
                $status = 400;
91
            }
92
        } else {
93 2
            foreach ($this->inputFilter->getInvalidInput() as $key => $input) {
94 2
                $messages = $input->getMessages();
95 2
                $validation[] = [
96 2
                    'field' => $key,
97 2
                    'msg' => reset($messages)
98
                ];
99
            }
100 2
            $status = 400;
101
        }
102
103 4
        return new JsonResponse([
104 4
            'msg' => $message,
105 4
            'success' => $created,
106
            'data' => [
107 4
                'validation' => $validation,
108 2
                'user' => isset($entity) ? $this->extraction->extract($entity) : null,
109
            ]
110 4
        ], $status);
111
    }
112
113
    /**
114
     * @param array $data
115
     * @return User
116
     */
117 2
    private function getEntity(array $data): User
118
    {
119 2
        $entity = new User();
120 2
        $this->hydrator->hydrate($data, $entity);
121
122 2
        return $entity;
123
    }
124
}
125