Completed
Pull Request — master (#31)
by Christophe
03:29 queued 15s
created

XabbuhPandaExtension::loadClouds()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 53
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 6.0131

Importance

Changes 0
Metric Value
dl 0
loc 53
ccs 26
cts 28
cp 0.9286
rs 8.7155
c 0
b 0
f 0
cc 6
eloc 30
nc 9
nop 4
crap 6.0131

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the XabbuhPandaBundle package.
5
 *
6
 * (c) Christian Flothmann <[email protected]>
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 Xabbuh\PandaBundle\DependencyInjection;
13
14
use Symfony\Component\Config\FileLocator;
15
use Symfony\Component\DependencyInjection\Alias;
16
use Symfony\Component\DependencyInjection\ContainerBuilder;
17
use Symfony\Component\DependencyInjection\ChildDefinition;
18
use Symfony\Component\DependencyInjection\Definition;
19
use Symfony\Component\DependencyInjection\DefinitionDecorator;
20
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
21
use Symfony\Component\DependencyInjection\Reference;
22
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
23
use Xabbuh\PandaClient\Api\CloudInterface;
24
25
/**
26
 * XabbuhPandaExtension.
27
 *
28
 * @author Christian Flothmann <[email protected]>
29
 */
30
class XabbuhPandaExtension extends Extension
31
{
32
    /**
33
     * {@inheritDoc}
34
     */
35 3
    public function load(array $configs, ContainerBuilder $container)
36
    {
37 3
        $configuration = new Configuration();
38 3
        $config = $this->processConfiguration($configuration, $configs);
39
40 3
        $container->setParameter(
41 3
            'xabbuh_panda.video_uploader.multiple_files',
42 3
            $config['video_uploader']['multiple_files']
43
        );
44 3
        $container->setParameter(
45 3
            'xabbuh_panda.video_uploader.cancel_button',
46 3
            $config['video_uploader']['cancel_button']
47
        );
48 3
        $container->setParameter(
49 3
            'xabbuh_panda.video_uploader.progress_bar',
50 3
            $config['video_uploader']['progress_bar']
51
        );
52
53 3
        $container->setParameter('xabbuh_panda.account.default', $config['default_account']);
54 3
        $container->setParameter('xabbuh_panda.cloud.default', $config['default_cloud']);
55
56
        // and load the service definitions
57 3
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
58 3
        $loader->load('account_manager.xml');
59 3
        $loader->load('cloud_manager.xml');
60 3
        $loader->load('cloud_factory.xml');
61 3
        $loader->load('controller.xml');
62 3
        $loader->load('transformers.xml');
63 3
        $loader->load('video_uploader_extension.xml');
64
65 3
        $knownAccounts = $this->loadAccounts($config['accounts'], $container);
66 3
        $knownClouds = $this->loadClouds($config['clouds'], $container, $knownAccounts, $config['default_account']);
67
68 3
        if (isset($knownClouds[$config['default_cloud']])) {
69
            $container->setAlias(CloudInterface::class, new Alias($knownClouds[$config['default_cloud']], false));
70 3
        } elseif (!empty($config['clouds'])) {
71
            // Weird case where the config has some clouds, but the default one is not part of it.
72
            // The autowired service will still be the default one from the CloudManager.
73 1
            $autowiredCloud = new Definition(CloudInterface::class);
74 1
            $autowiredCloud->setPublic(false);
75 1
            $autowiredCloud->setFactory(array(new Reference('xabbuh_panda.cloud_manager'), 'getCloud'));
76
77 1
            $container->setDefinition(CloudInterface::class, $autowiredCloud);
78
        }
79
80 3
        $baseHttpClientDefinition = $container->getDefinition('xabbuh_panda.http_client');
81
82 3
        foreach (array('client' => 0, 'request_factory' => 1, 'stream_factory' => 2) as $key => $argumentIndex) {
83 3
            if (null !== $config['httplug'][$key]) {
84 3
                $baseHttpClientDefinition->replaceArgument($argumentIndex, new Reference($config['httplug'][$key]));
85
            }
86
        }
87 3
    }
88
89 3
    private function loadAccounts(array $accounts, ContainerBuilder $container)
90
    {
91 3
        $accountManagerDefinition = $container->getDefinition('xabbuh_panda.account_manager');
92
93 3
        $knownAccounts = array();
94
95 3
        foreach ($accounts as $name => $accountConfig) {
96
            // register each account as a service
97
            $accountDefinition = new Definition(
98
                'Xabbuh\PandaClient\Api\Account',
99
                array(
100
                    $accountConfig['access_key'],
101
                    $accountConfig['secret_key'],
102
                    $accountConfig['api_host']
103
                )
104
            );
105
            $id = 'xabbuh_panda.'.strtr($name, ' -', '_').'_account';
106
            $container->setDefinition($id, $accountDefinition);
107
108
            // and pass it to the manager's registerAccount() method
109
            $accountManagerDefinition->addMethodCall(
110
                'registerAccount',
111
                array($name, new Reference($id))
112
            );
113
            $knownAccounts[$name] = $id;
114
        }
115
116 3
        return $knownAccounts;
117
    }
118
119 3
    private function loadClouds(array $clouds, ContainerBuilder $container, array $knownAccounts, $defaultAccount)
120
    {
121 3
        $cloudManagerDefinition = $container->getDefinition('xabbuh_panda.cloud_manager');
122
123 3
        $knownClouds = array();
124
125 3
        foreach ($clouds as $name => $cloudConfig) {
126 1
            $accountName = isset($cloudConfig['account']) ? $cloudConfig['account'] : $defaultAccount;
127
128 1
            if (isset($knownAccounts[$accountName])) {
129
                // Get a reference to the account service directly, to avoid instantiating the AccountManager (and all other
130
                // accounts due to the AccountManager not supporting lazy-loading)
131
                $accountDefinition = new Reference($knownAccounts[$accountName]);
132
            } else {
133
                // Account for the fact that the AccountManager may have additional accounts registered by other bundles
134 1
                $accountDefinition = new Definition('Xabbuh\PandaClient\Api\Account');
135 1
                $accountDefinition->setFactory(array(new Reference('xabbuh_panda.account_manager'), 'getAccount'));
136
137 1
                $accountDefinition->addArgument(isset($cloudConfig['account']) ? $cloudConfig['account'] : null);
138
            }
139
140 1
            if (class_exists('Symfony\Component\DependencyInjection\ChildDefinition')) {
141 1
                $httpClientDefinition = new ChildDefinition('xabbuh_panda.http_client');
142
            } else {
143
                $httpClientDefinition = new DefinitionDecorator('xabbuh_panda.http_client');
144
            }
145
146 1
            $httpClientDefinition->setPublic(false);
147 1
            $httpClientDefinition->addMethodCall('setAccount', array($accountDefinition));
148 1
            $httpClientDefinition->addMethodCall('setCloudId', array($cloudConfig['id']));
149
150 1
            $httpClientId = 'xabbuh_panda.http_client.'.strtr($name, ' -', '_');
151
152 1
            $container->setDefinition($httpClientId, $httpClientDefinition);
153
154
            // register each cloud as a service
155 1
            $cloudDefinition = new Definition('Xabbuh\PandaClient\Api\Cloud');
156 1
            $cloudDefinition->addMethodCall('setHttpClient', array(new Reference($httpClientId)));
157 1
            $cloudDefinition->addMethodCall('setTransformers', array(new Reference('xabbuh_panda.transformer')));
158
159 1
            $id = 'xabbuh_panda.'.strtr($name, ' -', '_').'_cloud';
160 1
            $container->setDefinition($id, $cloudDefinition);
161
162
            // and pass it to the manager's registerAccount() method
163 1
            $cloudManagerDefinition->addMethodCall(
164 1
                'registerCloud',
165 1
                array($name, new Reference($id))
166
            );
167 1
            $knownClouds[$name] = $id;
168
        }
169
170 3
        return $knownClouds;
171
    }
172
173
    /**
174
     * {@inheritDoc}
175
     */
176 3
    public function getNamespace()
177
    {
178 3
        return 'http://xabbuh.de/schema/dic/xabbuh/panda';
179
    }
180
181
    /**
182
     * {@inheritDoc}
183
     */
184
    public function getXsdValidationBasePath()
185
    {
186
        return __DIR__.'/../Resources/config/schema';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return __DIR__ . '/../Resources/config/schema'; (string) is incompatible with the return type of the parent method Symfony\Component\Depend...etXsdValidationBasePath of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
187
    }
188
}
189