Completed
Push — master ( 51e9c2...0afc07 )
by Oleg
06:21
created

AddUserAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 11
nc 1
nop 5
dl 0
loc 13
ccs 7
cts 7
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\ClassMethods;
20
use Zend\Hydrator\ExtractionInterface;
21
use Zend\Hydrator\HydratorInterface;
22
use Zend\InputFilter\InputFilterInterface;
23
24
class AddUserAction implements MiddlewareInterface
25
{
26
    /**
27
     * @var EntityManagerInterface
28
     */
29
    private $entityManager;
30
    /**
31
     * @var HydratorInterface
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 $extraction;
46
47 3
    public function __construct(
48
        EntityManagerInterface $entityManager,
49
        HydratorInterface $hydrator,
50
        InputFilterInterface $inputFilter,
51
        LoggerInterface $logger,
52
        ExtractionInterface $extraction
53
    ) {
54 3
        $this->entityManager = $entityManager;
55 3
        $this->hydrator = $hydrator;
56 3
        $this->inputFilter = $inputFilter;
57 3
        $this->logger = $logger;
58 3
        $this->extraction = $extraction;
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 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...
69
70 3
        $message = null;
71 3
        $validation = [];
72 3
        $created = false;
73 3
        $status = 200;
74
75 3
        if ($this->inputFilter->isValid()) {
76
            try {
77 2
                $user = $this->getUser($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...ddUserAction::getUser() 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...
78 2
                $this->entityManager->persist($user);
79 2
                $this->entityManager->flush();
80 1
                $message = new SuccessMessage('User has been successfully created!');
81 1
                $created = true;
82 1
            } catch (ORMInvalidArgumentException $exception) {
83
                $message = new DangerMessage($exception->getMessage());
84
                $status = 400;
85 1
            } catch (UniqueConstraintViolationException $exception) {
86 1
                $message = new DangerMessage('Provided email already exists.');
87 1
                $status = 400;
88 1
                $user = null;
89
            } catch (ORMException $exception) {
90
                $this->logger->error((string)$exception);
91
                $message = new DangerMessage('Error during creation operation.');
92
                $status = 400;
93
            }
94
        } else {
95 1
            foreach ($this->inputFilter->getInvalidInput() as $key => $input) {
96 1
                $messages = $input->getMessages();
97 1
                $validation[] = [
98 1
                    'field' => $key,
99 1
                    'msg' => reset($messages)
100
                ];
101
            }
102 1
            $status = 400;
103
        }
104
105 3
        return new JsonResponse([
106 3
            'msg' => $message,
107 3
            'success' => $created,
108
            'data' => [
109 3
                'validation' => $validation,
110 1
                'user' => isset($user) ? $this->extraction->extract($user) : null,
111
            ]
112 3
        ], $status);
113
    }
114
115
    /**
116
     * @param array $data
117
     * @return User
118
     */
119 2
    private function getUser(array $data): User
120
    {
121 2
        $user = new User();
122 2
        $this->hydrator->hydrate($data, $user);
123
124 2
        return $user;
125
    }
126
}
127