Passed
Branch master (c65ffc)
by Dāvis
03:08
created

Oauth   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 172
Duplicated Lines 13.95 %

Importance

Changes 0
Metric Value
dl 24
loc 172
rs 10
c 0
b 0
f 0
wmc 18

8 Methods

Rating   Name   Duplication   Size   Complexity  
A buildClientConfiguration() 0 14 1
A getAllSupportedTypes() 0 3 1
B configureClient() 0 44 5
A __construct() 0 3 1
A getConfigurator() 9 9 2
B configure() 14 49 6
A setType() 0 5 1
A getType() 0 3 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Sludio\HelperBundle\DependencyInjection\Component;
4
5
use LogicException;
6
use Sludio\HelperBundle\Oauth\Configurator;
7
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
8
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
9
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
10
use Symfony\Component\Config\Definition\Processor;
11
use Symfony\Component\DependencyInjection\ContainerBuilder;
12
use Symfony\Component\DependencyInjection\Reference;
13
14
class Oauth implements Extensionable
15
{
16
    protected $checkClassExistence;
17
18
    protected $configurators = [];
19
20
    protected $type;
21
22
    /**
23
     * List of available Oauth providers
24
     * @var array
25
     */
26
    protected static $supportedProviderTypes = [
27
        'custom' => Configurator\CustomProviderConfigurator::class,
28
        'facebook' => Configurator\FacebookProviderConfigurator::class,
29
        'google' => Configurator\GoogleProviderConfigurator::class,
30
        'twitter' => Configurator\TwitterProviderConfigurator::class,
31
        'draugiem' => Configurator\DraugiemProviderConfigurator::class,
32
    ];
33
34
    public function __construct($checkClassExistence = true)
35
    {
36
        $this->checkClassExistence = $checkClassExistence;
37
    }
38
39
    public static function getAllSupportedTypes()
40
    {
41
        return array_keys(self::$supportedProviderTypes);
42
    }
43
44 View Code Duplication
    public function getConfigurator($type)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
45
    {
46
        if (!isset($this->configurators[$type])) {
47
            $class = self::$supportedProviderTypes[$type];
48
49
            $this->configurators[$type] = new $class();
50
        }
51
52
        return $this->configurators[$type];
53
    }
54
55
    public function buildClientConfiguration(NodeDefinition &$node)
56
    {
57
        $optionsNode = $node->children();
58
59
        // @formatter:off
60
        $optionsNode
61
            ->scalarNode('client_id')->isRequired()->cannotBeEmpty()->end()
62
            ->scalarNode('client_secret')->isRequired()->cannotBeEmpty()->end()
63
            ->booleanNode('use_state')->defaultValue(true)->end()
64
        ;
65
        // @formatter:on
66
67
        $this->getConfigurator($this->getType())->buildConfiguration($optionsNode);
68
        $optionsNode->end();
69
    }
70
71
    public function configureClient(ContainerBuilder $container, $clientServiceKey, array $options = [])
72
    {
73
        $providerClass = $options['provider_class'];
74
        if ($this->checkClassExistence && !class_exists($providerClass)) {
75
            throw new LogicException(sprintf('Class "%s" does not exist.', $providerClass));
76
        }
77
78
        $providerServiceKey = sprintf('sludio_helper.oauth.provider.%s', $clientServiceKey);
79
80
        $providerDefinition = $container->register($providerServiceKey, $providerClass);
81
        $providerDefinition->setPublic(false);
82
83
        $providerDefinition->setFactory([
84
            new Reference('sludio_helper.oauth.provider_factory'),
85
            'createProvider',
86
        ]);
87
88
        $mandatory = [
89
            $providerClass,
90
            $options['provider_options'],
91
        ];
92
93
        $optional = [];
94
95
        if (isset($options['provider_options']['params'])) {
96
            $optional[] = $options['provider_options']['params'];
97
        }
98
99
        $providerDefinition->setArguments(array_merge($mandatory, $optional));
100
101
        $clientServiceKey = sprintf('sludio_helper.oauth.client.%s', $clientServiceKey);
102
        $clientClass = $options['client_class'];
103
        $clientDefinition = $container->register($clientServiceKey, $clientClass);
104
        $clientDefinition->setArguments([
105
            new Reference($providerServiceKey),
106
            new Reference('request_stack'),
107
            new Reference('sludio_helper.logger'),
108
        ]);
109
110
        if (!$options['state']) {
111
            $clientDefinition->addMethodCall('setAsStateless');
112
        }
113
114
        return $clientServiceKey;
115
    }
116
117
    public function configure(ContainerBuilder &$container)
118
    {
119
        $clientConfigurations = $container->getParameter('sludio_helper.oauth.clients');
120
        $clientServiceKeys = [];
121
        foreach ($clientConfigurations as $key => $clientConfig) {
122
            $tree = new TreeBuilder();
123
            $processor = new Processor();
124
125
            if (!isset($clientConfig['type'])) {
126
                throw new InvalidConfigurationException(sprintf('Your "sludio_helper_oauth_client.clients.%s" config entry is missing the "type" key.', $key));
127
            }
128
129
            $this->type = $clientConfig['type'];
130
            unset($clientConfig['type']);
131 View Code Duplication
            if (!isset(self::$supportedProviderTypes[$this->type])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
                $supportedKeys = array_keys(self::$supportedProviderTypes);
133
                sort($supportedKeys);
134
                throw new InvalidConfigurationException(sprintf('The "sludio_helper_oauth_client.clients" config "type" key "%s" is not supported. We support: %s', $this->type, implode(', ', $supportedKeys)));
135
            }
136
137
            $node = $tree->root('sludio_helper_oauth_client/clients/'.$key);
138
            $this->buildClientConfiguration($node);
139
            $config = $processor->process($tree->buildTree(), [$clientConfig]);
140
141
            $configurator = $this->getConfigurator($this->type);
142
143
            $options = [
144
                'provider_class' => $configurator->getProviderClass($config),
145
                'client_class' => $configurator->getClientClass($config),
146
                'provider_options' => $configurator->getProviderOptions($config),
147
                'state' => $config['use_state'],
148
            ];
149
150
            $clientServiceKey = $this->configureClient($container, $key, $options);
151
152
            $service = [
153
                'key' => $clientServiceKey,
154
            ];
155 View Code Duplication
            if (isset($config['provider_options']) && isset($config['provider_options']['name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
156
                $service['name'] = $config['provider_options']['name'];
157
            } else {
158
                $service['name'] = ucfirst($key);
159
            }
160
161
            $clientServiceKeys[$key] = $service;
162
        }
163
164
        $container->getDefinition('sludio_helper.oauth.registry')->replaceArgument(1, $clientServiceKeys);
165
        $container->getDefinition('sludio_helper.registry')->replaceArgument(1, $clientServiceKeys);
166
    }
167
168
    /**
169
     * @return mixed
170
     */
171
    public function getType()
172
    {
173
        return $this->type;
174
    }
175
176
    /**
177
     * @param $type
178
     *
179
     * @return $this
180
     */
181
    public function setType($type)
182
    {
183
        $this->type = $type;
184
185
        return $this;
186
    }
187
}
188