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

GenerateTemporaryTokenAction::createToken()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3.3332

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 12
cts 18
cp 0.6667
rs 9.392
c 0
b 0
f 0
cc 3
nc 5
nop 2
crap 3.3332
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authentication\Controller;
5
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\ORMException;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Psr\Log\LoggerInterface;
13
use SlayerBirden\DataFlowServer\Authentication\Exception\PermissionDeniedException;
14
use SlayerBirden\DataFlowServer\Authentication\TokenManagerInterface;
15
use SlayerBirden\DataFlowServer\Doctrine\Middleware\ResourceMiddlewareInterface;
16
use SlayerBirden\DataFlowServer\Domain\Entities\ClaimedResourceInterface;
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 GenerateTemporaryTokenAction implements MiddlewareInterface
26
{
27
    /**
28
     * @var EntityManager
29
     */
30
    private $entityManager;
31
    /**
32
     * @var TokenManagerInterface
33
     */
34
    private $tokenManager;
35
    /**
36
     * @var LoggerInterface
37
     */
38
    private $logger;
39
    /**
40
     * @var HydratorInterface
41
     */
42
    private $hydrator;
43
    /**
44
     * @var InputFilterInterface
45
     */
46
    private $inputFilter;
47
48 8
    public function __construct(
49
        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...
50
        InputFilterInterface $inputFilter,
51
        TokenManagerInterface $tokenManager,
52
        LoggerInterface $logger,
53
        HydratorInterface $hydrator
54
    ) {
55 8
        $this->entityManager = $entityManager;
56 8
        $this->tokenManager = $tokenManager;
57 8
        $this->logger = $logger;
58 8
        $this->hydrator = $hydrator;
59 8
        $this->inputFilter = $inputFilter;
60 8
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65 8
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
66
    {
67 8
        $data = $request->getParsedBody();
68 8
        $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...
69
70 8
        $user = $request->getAttribute(ResourceMiddlewareInterface::DATA_RESOURCE);
71
72 8
        if ($this->inputFilter->isValid()) {
73 7
            return $this->createToken($user, $data['resources']);
74
        } else {
75 1
            return (new ValidationResponseFactory())('token', $this->inputFilter);
76
        }
77
    }
78
79 7
    private function createToken(User $user, array $resources): ResponseInterface
80
    {
81
        try {
82 7
            $token = $this->tokenManager->getTmpToken($user, $resources);
83 5
            return new JsonResponse([
84 5
                'data' => [
85 5
                    'token' => $this->hydrator->extract($token),
86
                    'validation' => [],
87
                ],
88
                'success' => true,
89 5
                'msg' => new SuccessMessage('Token created'),
90 5
            ], 200);
91 2
        } catch (PermissionDeniedException $exception) {
92 2
            return new JsonResponse([
93 2
                'data' => [
94
                    'token' => null,
95
                    'validation' => [],
96
                ],
97
                'success' => false,
98 2
                'msg' => new DangerMessage($exception->getMessage()),
99 2
            ], 400);
100
        } catch (\Exception $exception) {
101
            $this->logger->error((string)$exception);
102
            return new JsonResponse([
103
                'data' => [
104
                    'token' => null,
105
                    'validation' => [],
106
                ],
107
                'success' => false,
108
                'msg' => new DangerMessage('There was an error while obtaining tmp token.'),
109
            ], 500);
110
        }
111
    }
112
}
113