UserRepository::supportsClass()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * This file is part of Webcook security bundle.
5
 *
6
 * See LICENSE file in the root of the bundle. Webcook 
7
 */
8
9
namespace Webcook\Cms\SecurityBundle\Entity;
10
11
use Symfony\Component\Security\Core\User\UserInterface;
12
use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
13
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
14
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
15
use Doctrine\ORM\EntityRepository;
16
use Doctrine\ORM\NoResultException;
17
18
/**
19
 * User entity repository.
20
 */
21
class UserRepository extends EntityRepository implements UserLoaderInterface
22
{
23
    /**
24
     * {@inheritdoc}
25
     *
26
     * @param [type] $username [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
27
     *
28
     * @return [type] [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
29
     */
30 1
    public function loadUserByUsername($username)
31
    {
32
        $q = $this
33 1
            ->createQueryBuilder('u')
34 1
            ->where('(u.username = :username OR u.email = :email) AND u.isActive = :active')
35 1
            ->setParameter('username', $username)
36 1
            ->setParameter('email', $username)
37 1
            ->setParameter('active', true)
38 1
            ->getQuery();
39
40
        try {
41 1
            $user = $q->getSingleResult();
42 1
        } catch (NoResultException $e) {
43 1
            $message = sprintf(
44 1
                'Unable to find an active admin object identified by "%s".',
45
                $username
46
            );
47 1
            throw new UsernameNotFoundException($message, 0, $e);
48
        }
49
50 1
        return $user;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     *
56
     * @param UserInterface $user [description]
57
     *
58
     * @return [type] [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
59
     */
60 1
    public function refreshUser(UserInterface $user)
61
    {
62 1
        $class = get_class($user);
63 1
        if (!$this->supportsClass($class)) {
64
            throw new UnsupportedUserException(
65
                sprintf(
66
                    'Instances of "%s" are not supported.',
67
                    $class
68
                )
69
            );
70
        }
71
        return $this
72 1
            ->createQueryBuilder('u')
73 1
            ->where('u.id = :id AND u.isActive = :active')
74 1
            ->setParameter('id', $user->getId())
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Security\Core\User\UserInterface as the method getId() does only exist in the following implementations of said interface: Liip\FunctionalTestBundle\Tests\App\Entity\User, Webcook\Cms\SecurityBundle\Entity\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
75 1
            ->setParameter('active', true)
76 1
            ->getQuery()
77 1
            ->getSingleResult();
78
79
        //return $this->find($user->getId());
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     *
85
     * @param  string $class [description]
86
     * @return [type] [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
87
     */
88 1
    public function supportsClass($class)
89
    {
90 1
        return $this->getEntityName() === $class
91 1
            || is_subclass_of($class, $this->getEntityName());
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if $this->getEntityName() can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
92
    }
93
}
94