Failed Conditions
Push — master ( c4fa4a...5cc583 )
by Florent
02:12
created

JWKSource::load()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace Jose\Bundle\KeyManagement\DependencyInjection\Source;
15
16
use Jose\Bundle\JoseFramework\DependencyInjection\Source\SourceInterface;
17
use Jose\Bundle\KeyManagement\DependencyInjection\Source\JWKSource\JWKSourceInterface;
18
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
19
use Symfony\Component\Config\FileLocator;
20
use Symfony\Component\DependencyInjection\ContainerBuilder;
21
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
22
23
/**
24
 * Class JWKSource.
25
 */
26
final class JWKSource implements SourceInterface
27
{
28
    /**
29
     * @var null|JWKSourceInterface[]
30
     */
31
    private $jwkSources = null;
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function name(): string
37
    {
38
        return 'keys';
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function load(array $configs, ContainerBuilder $container)
45
    {
46
        $this->createService($configs[$this->name()], $container);
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    private function createService(array $config, ContainerBuilder $container)
53
    {
54
        $sources = $this->getJWKSources();
55
56
        foreach ($config as $name => $itemConfig) {
57
            foreach ($itemConfig as $sourceName => $sourceConfig) {
58
                if (array_key_exists($sourceName, $sources)) {
59
                    $source = $sources[$sourceName];
60
                    $source->create($container, 'key', $sourceName, $sourceConfig);
61
                } else {
62
                    throw new \LogicException(sprintf('The JWK definition "%s" is not configured.', $name));
63
                }
64
            }
65
        }
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function getNodeDefinition(ArrayNodeDefinition $node)
72
    {
73
        $sourceNodeBuilder = $node
0 ignored issues
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 performNoDeepMerging() 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...
74
            ->children()
75
                ->arrayNode('keys')
76
                    ->useAttributeAsKey('name')
77
                    ->prototype('array')
78
                        ->performNoDeepMerging()
79
                        ->children();
80
        foreach ($this->getJWKSources() as $name => $source) {
81
            $sourceNode = $sourceNodeBuilder->arrayNode($name)->canBeUnset();
82
            $source->addConfiguration($sourceNode);
83
        }
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function prepend(ContainerBuilder $container, array $config): ?array
90
    {
91
        return null;
92
    }
93
94
    /**
95
     * @return JWKSourceInterface[]
96
     */
97
    private function getJWKSources(): array
98
    {
99
        if (null !== $this->jwkSources) {
100
            return $this->jwkSources;
101
        }
102
103
        // load bundled adapter factories
104
        $tempContainer = new ContainerBuilder();
105
        $loader = new YamlFileLoader($tempContainer, new FileLocator(__DIR__.'/../../Resources/config'));
106
        $loader->load('jwk_sources.yml');
107
        $services = $tempContainer->findTaggedServiceIds('jose.jwk_source');
108
        $jwkSources = [];
109
        foreach (array_keys($services) as $id) {
110
            $factory = $tempContainer->get($id);
111
            $jwkSources[str_replace('-', '_', $factory->getKey())] = $factory;
112
        }
113
114
        $this->jwkSources = $jwkSources;
115
116
        return $jwkSources;
117
    }
118
}
119