Passed
Branch master (98ecdf)
by Michael
56:56
created

InMemoryApiFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 4
dl 0
loc 64
ccs 0
cts 39
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 15 2
A getKey() 0 4 1
A addConfiguration() 0 23 1
1
<?php
2
3
/*
4
 * This file is part of the OsLabSecurityApiBundle package.
5
 *
6
 * (c) OsLab <https://github.com/OsLab>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace OsLab\SecurityApiBundle\DependencyInjection\Security\UserProvider;
13
14
use Symfony\Component\DependencyInjection\ContainerBuilder;
15
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface;
16
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
17
use Symfony\Component\DependencyInjection\DefinitionDecorator;
18
use Symfony\Component\DependencyInjection\Reference;
19
20
/**
21
 * InMemoryApiFactory creates services for the memory api provider.
22
 *
23
 * @author Michael COULLERET <[email protected]>
24
 * @author Florent DESPIERRES <[email protected]>
25
 */
26
class InMemoryApiFactory implements UserProviderFactoryInterface
27
{
28
    /**
29
     * Creates the userProvider.
30
     *
31
     * @param ContainerBuilder $container Instance of container.
32
     * @param string           $id        The service id for concrete user provider.
33
     * @param array            $config    Configuration of current factory.
34
     */
35
    public function create(ContainerBuilder $container, $id, $config)
36
    {
37
        $definition = $container->setDefinition($id, new DefinitionDecorator('oslab_security_api.security.user.provider'));
38
39
        foreach ($config['users'] as $username => $user) {
40
            $userId = $id.'_'.$username;
41
42
            $container
43
                ->setDefinition($userId, new DefinitionDecorator('security.user.provider.in_memory.user'))
44
                ->setArguments(array($username, (string) $user['password'], $user['roles']))
45
            ;
46
47
            $definition->addMethodCall('createUser', array(new Reference($userId)));
48
        }
49
    }
50
51
    /**
52
     * Returns the key of current factory.
53
     *
54
     * @return string
55
     */
56
    public function getKey()
57
    {
58
        return 'memory_api';
59
    }
60
61
    /**
62
     * Adds configuration nodes to current user provider.
63
     *
64
     * @param NodeDefinition $node
65
     */
66
    public function addConfiguration(NodeDefinition $node)
67
    {
68
        $node
1 ignored issue
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Config...\Builder\NodeDefinition as the method fixXmlConfig() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
69
            ->fixXmlConfig('user')
70
            ->children()
71
                ->arrayNode('users')
72
                    ->useAttributeAsKey('name')
73
                    ->prototype('array')
74
                        ->children()
75
                            ->scalarNode('password')->defaultValue(uniqid('', true))->end()
76
                            ->arrayNode('roles')
77
                                ->beforeNormalization()->ifString()->then(function ($v) {
78
                                    return preg_split('/\s*,\s*/', $v);
79
                                })
80
                                ->end()
81
                                ->prototype('scalar')->end()
82
                            ->end()
83
                        ->end()
84
                    ->end()
85
                ->end()
86
            ->end()
87
        ;
88
    }
89
}
90