Completed
Push — master ( 178a08...5c0b6f )
by Oleg
05:22
created

UpdateUserAction::getUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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