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

CreatePasswordAction   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 85.19%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 9
dl 0
loc 80
ccs 23
cts 27
cp 0.8519
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A process() 0 22 3
A createPassword() 0 17 1
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authentication\Controller;
5
6
use Doctrine\ORM\EntityManager;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
use Psr\Log\LoggerInterface;
12
use SlayerBirden\DataFlowServer\Authentication\Entities\Password;
13
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
14
use SlayerBirden\DataFlowServer\Notification\SuccessMessage;
15
use SlayerBirden\DataFlowServer\Stdlib\Validation\ValidationResponseFactory;
16
use Zend\Diactoros\Response\JsonResponse;
17
use Zend\Hydrator\HydratorInterface;
18
use Zend\InputFilter\InputFilterInterface;
19
20
class CreatePasswordAction implements MiddlewareInterface
21
{
22
    /**
23
     * @var EntityManager
24
     */
25
    private $entityManager;
26
    /**
27
     * @var InputFilterInterface
28
     */
29
    private $inputFilter;
30
    /**
31
     * @var LoggerInterface
32
     */
33
    private $logger;
34
    /**
35
     * @var HydratorInterface
36
     */
37
    private $hydrator;
38
39 3
    public function __construct(
40
        EntityManager $entityManager,
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
41
        InputFilterInterface $inputFilter,
42
        LoggerInterface $logger,
43
        HydratorInterface $hydrator
44
    ) {
45 3
        $this->entityManager = $entityManager;
46 3
        $this->inputFilter = $inputFilter;
47 3
        $this->logger = $logger;
48 3
        $this->hydrator = $hydrator;
49 3
    }
50
51
    /**
52
     * @inheritdoc
53
     */
54 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
55
    {
56 3
        $data = $request->getParsedBody();
57 3
        $this->inputFilter->setData($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 56 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...
58
59 3
        if ($this->inputFilter->isValid()) {
60
            try {
61 1
                return $this->createPassword($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 56 can also be of type null or object; however, SlayerBirden\DataFlowSer...ction::createPassword() 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...
62
            } catch (\Exception $exception) {
63
                return new JsonResponse([
64
                    'msg' => new DangerMessage('There was an error while creating password.'),
65
                    'success' => true,
66
                    'data' => [
67
                        'validation' => [],
68
                        'password' => null,
69
                    ]
70
                ], 500);
71
            }
72
        } else {
73 2
            return (new ValidationResponseFactory())('password', $this->inputFilter);
74
        }
75
    }
76
77
    /**
78
     * @param array $data
79
     * @return ResponseInterface
80
     * @throws \Exception
81
     */
82 1
    private function createPassword(array $data): ResponseInterface
83
    {
84 1
        $data['created_at'] = (new \DateTime())->format(\DateTime::RFC3339);
85 1
        $data['due'] = (new \DateTime())->add(new \DateInterval('P1Y'))->format(\DateTime::RFC3339);
86 1
        $data['active'] = $data['active'] ?? true;
87 1
        $password = $this->hydrator->hydrate($data, new Password());
88 1
        $this->entityManager->persist($password);
89 1
        $this->entityManager->flush();
90 1
        return new JsonResponse([
91 1
            'msg' => new SuccessMessage('Password has been successfully created!'),
92
            'success' => true,
93
            'data' => [
94
                'validation' => [],
95 1
                'password' => $this->hydrator->extract($password),
96
            ]
97 1
        ], 200);
98
    }
99
}
100