Completed
Push — master ( 3e963f...fbd0cf )
by Yann
02:04
created

DoctrineORMTokenRepository::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Yokai\SecurityTokenBundle\Repository;
4
5
use Doctrine\ORM\EntityManager;
6
use Doctrine\ORM\EntityRepository;
7
use Yokai\SecurityTokenBundle\Entity\Token;
8
use Yokai\SecurityTokenBundle\Exception\TokenExpiredException;
9
use Yokai\SecurityTokenBundle\Exception\TokenNotFoundException;
10
use Yokai\SecurityTokenBundle\Exception\TokenUsedException;
11
12
/**
13
 * @author Yann Eugoné <[email protected]>
14
 */
15
class DoctrineORMTokenRepository implements TokenRepositoryInterface
16
{
17
    /**
18
     * @var EntityManager
19
     */
20
    private $manager;
21
22
    /**
23
     * @var EntityRepository
24
     */
25
    private $repository;
26
27
    /**
28
     * @param EntityManager    $manager
29
     * @param EntityRepository $repository
30
     */
31
    public function __construct(EntityManager $manager, EntityRepository $repository)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $manager. 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...
32
    {
33
        $this->manager = $manager;
34
        $this->repository = $repository;
35
    }
36
37
    /**
38
     * @inheritdoc
39
     */
40
    public function get($value, $purpose)
41
    {
42
        $token = $this->repository->findOneBy(
43
            [
44
                'value' => $value,
45
                'purpose' => $purpose,
46
            ]
47
        );
48
49
        if (!$token instanceof Token) {
50
            throw TokenNotFoundException::create($value, $purpose);
51
        }
52
        if ($token->isExpired()) {
53
            throw TokenExpiredException::create($value, $purpose, $token->getExpiresAt());
54
        }
55
        if ($token->isUsed()) {
56
            throw TokenUsedException::create($value, $purpose, $token->getUsedAt());
0 ignored issues
show
Bug introduced by
It seems like $token->getUsedAt() can be null; however, create() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
57
        }
58
59
        return $token;
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function create(Token $token)
66
    {
67
        $this->manager->persist($token);
68
        $this->manager->flush($token);
69
    }
70
71
    /**
72
     * @inheritdoc
73
     */
74
    public function update(Token $token)
75
    {
76
        $this->manager->persist($token);
77
        $this->manager->flush($token);
78
    }
79
80
    /**
81
     * @inheritdoc
82
     */
83
    public function exists($value, $purpose)
84
    {
85
        $builder = $this->repository->createQueryBuilder('token');
86
        $builder
87
            ->select('COUNT(token.id)')
88
            ->where('token.value = :value')
89
            ->andWhere('token.purpose = :purpose')
90
            ->setParameters(
91
                [
92
                    'value' => $value,
93
                    'purpose' => $purpose,
94
                ]
95
            )
96
        ;
97
98
        return intval($builder->getQuery()->getSingleScalarResult()) > 0;
99
    }
100
}
101