Completed
Push — master ( 0024da...3d898f )
by Oleg
03:17
created

UpdateUserAction   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 100
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 87.5%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 12
dl 0
loc 100
ccs 42
cts 48
cp 0.875
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
B process() 0 46 7
A getUser() 0 12 2
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\Domain\Entities\User;
17
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
18
use SlayerBirden\DataFlowServer\Notification\SuccessMessage;
19
use SlayerBirden\DataFlowServer\Stdlib\Validation\ValidationResponseFactory;
20
use Zend\Diactoros\Response\JsonResponse;
21
use Zend\Hydrator\ExtractionInterface;
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
     * @var ExtractionInterface
45
     */
46
    private $extraction;
47
48 5
    public function __construct(
49
        EntityManagerInterface $entityManager,
50
        HydratorInterface $hydrator,
51
        InputFilterInterface $inputFilter,
52
        LoggerInterface $logger,
53
        ExtractionInterface $extraction
54
    ) {
55 5
        $this->entityManager = $entityManager;
56 5
        $this->hydrator = $hydrator;
57 5
        $this->inputFilter = $inputFilter;
58 5
        $this->logger = $logger;
59 5
        $this->extraction = $extraction;
60 5
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65 5
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
66
    {
67 5
        $data = $request->getParsedBody();
68 5
        $id = (int)$request->getAttribute('id');
69
70 5
        $this->inputFilter->setData($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 67 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...
71
72 5
        $message = null;
73 5
        $validation = [];
74 5
        $updated = false;
75 5
        $status = 200;
76
77 5
        if ($this->inputFilter->isValid()) {
78
            try {
79 4
                $user = $this->getUser($id, $data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 67 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...
80 3
                $this->entityManager->persist($user);
81 3
                $this->entityManager->flush();
82 2
                $message = new SuccessMessage('User has been updated!');
83 2
                $updated = true;
84 2
            } catch (NonExistingEntity $exception) {
85 1
                $message = new DangerMessage($exception->getMessage());
86 1
                $status = 404;
87 1
            } catch (ORMInvalidArgumentException $exception) {
88
                $message = new DangerMessage($exception->getMessage());
89
                $status = 400;
90 1
            } catch (UniqueConstraintViolationException $exception) {
91 1
                $message = new DangerMessage('Email address already taken.');
92 1
                $status = 400;
93
            } catch (ORMException $exception) {
94
                $this->logger->error((string)$exception);
95
                $message = new DangerMessage('Error saving user.');
96
                $status = 400;
97
            }
98
        } else {
99 1
            return (new ValidationResponseFactory())('user', $this->inputFilter);
100
        }
101
102 4
        return new JsonResponse([
103 4
            'msg' => $message,
104 4
            'success' => $updated,
105
            'data' => [
106 4
                'validation' => $validation,
107 3
                'user' => isset($user) ? $this->extraction->extract($user) : null,
108
            ]
109 4
        ], $status);
110
    }
111
112 4
    private function getUser(int $id, array $data): User
113
    {
114
        /** @var User $user */
115 4
        $user = $this->entityManager->find(User::class, $id);
116 4
        if (!$user) {
117 1
            throw new NonExistingEntity(sprintf('Could not find user by id %d.', $id));
118
        }
119 3
        unset($data['id']);
120 3
        $this->hydrator->hydrate($data, $user);
121
122 3
        return $user;
123
    }
124
}
125