Completed
Push — master ( 9a4560...93a2ef )
by Sullivan
02:10
created

ConfigBridge   C

Complexity

Total Complexity 51

Size/Duplication

Total Lines 277
Duplicated Lines 2.17 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 0
Metric Value
wmc 51
lcom 1
cbo 16
dl 6
loc 277
rs 6.0708
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
C __construct() 0 41 15
C create() 0 37 7
C getFinder() 0 31 7
A getFixers() 0 21 3
B getRules() 0 23 4
A getRisky() 0 4 1
A getPresetFixers() 0 9 2
B resolveAliases() 6 13 8
A isFixerAvailable() 0 9 2
A parseStyleCIConfig() 0 8 2

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ConfigBridge often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ConfigBridge, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace SLLH\StyleCIBridge;
4
5
use Composer\Semver\Semver;
6
use Doctrine\Common\Inflector\Inflector;
7
use PhpCsFixer\Config;
8
use PhpCsFixer\Console\Application;
9
use PhpCsFixer\Finder;
10
use PhpCsFixer\FixerFactory;
11
use SLLH\StyleCIBridge\StyleCI\Configuration;
12
use SLLH\StyleCIFixers\Fixers;
13
use Symfony\Component\Config\Definition\Processor;
14
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
15
use Symfony\Component\Console\Output\ConsoleOutput;
16
use Symfony\Component\Console\Output\OutputInterface;
17
use Symfony\Component\Yaml\Yaml;
18
use Symfony\CS\Fixer;
19
use Symfony\CS\Fixer\Contrib\HeaderCommentFixer;
20
use Symfony\CS\FixerInterface;
21
22
/**
23
 * @author Sullivan Senechal <[email protected]>
24
 */
25
final class ConfigBridge
26
{
27
    const CS_FIXER_MIN_VERSION = '1.6.1';
28
29
    const PRESET_NONE = 'none';
30
31
    /**
32
     * @var OutputInterface
33
     */
34
    private $output;
35
36
    /**
37
     * @var FixerFactory
38
     */
39
    private $fixerFactory = null;
40
41
    /**
42
     * @var string
43
     */
44
    private $styleCIConfigDir;
45
46
    /**
47
     * @var array|null
48
     */
49
    private $styleCIConfig = null;
50
51
    /**
52
     * @var string|array
53
     */
54
    private $finderDirs;
55
56
    /**
57
     * @param string|null       $styleCIConfigDir StyleCI config directory. Called script dir as default
58
     * @param string|array|null $finderDirs       A directory path or an array of directories for Finder. Called script dir as default
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
59
     */
60
    public function __construct($styleCIConfigDir = null, $finderDirs = null)
61
    {
62
        if (!Semver::satisfies(
63
            class_exists('Symfony\CS\Fixer') ? Fixer::VERSION : Application::VERSION, // PHP-CS-Fixer 1.x BC
64
            sprintf('>=%s', self::CS_FIXER_MIN_VERSION)
65
        )) {
66
            throw new \RuntimeException(sprintf(
67
                'PHP-CS-Fixer v%s is not supported, please upgrade to v%s or higher.',
68
                Fixer::VERSION,
69
                self::CS_FIXER_MIN_VERSION
70
            ));
71
        }
72
73
        // Guess config files path if not specified.
74
        // getcwd function is not enough. See: https://github.com/Soullivaneuh/php-cs-fixer-styleci-bridge/issues/46
75
        if (null === $styleCIConfigDir || null === $finderDirs) {
76
            $dbt = version_compare(PHP_VERSION, '5.4.0', '>=') ? debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2) : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 160 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
77
78
            // Static call
79
            if (isset($dbt[1]['class']) && 'SLLH\StyleCIBridge\ConfigBridge' === $dbt[1]['class'] && 'create' === $dbt[1]['function']) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 136 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
80
                $configsPath = dirname($dbt[1]['file']);
81
            } elseif (isset($dbt[0]['class']) && 'SLLH\StyleCIBridge\ConfigBridge' === $dbt[0]['class'] && '__construct' === $dbt[0]['function']) { // Manual instance
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 166 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
82
                $configsPath = dirname($dbt[0]['file']);
83
            } else { // If no case found, fallback to not reliable getcwd method.
84
                $configsPath = getcwd();
85
            }
86
87
            $this->styleCIConfigDir = $styleCIConfigDir ?: $configsPath;
88
            $this->finderDirs = $finderDirs ?: $configsPath;
89
        }
90
91
        $this->output = new ConsoleOutput();
92
        $this->output->getFormatter()->setStyle('warning', new OutputFormatterStyle('black', 'yellow'));
93
        // PHP-CS-Fixer 1.x BC
94
        if (class_exists('PhpCsFixer\FixerFactory')) { // PHP-CS-Fixer 2.x only
95
            $this->fixerFactory = FixerFactory::create();
96
            $this->fixerFactory->registerBuiltInFixers();
97
        }
98
99
        $this->parseStyleCIConfig();
100
    }
101
102
    /**
103
     * @param string       $styleCIConfigDir
0 ignored issues
show
Documentation introduced by
Should the type for parameter $styleCIConfigDir not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
104
     * @param string|array $finderDirs       A directory path or an array of directories for Finder
0 ignored issues
show
Documentation introduced by
Should the type for parameter $finderDirs not be string|array|null? Also, consider making the array more specific, something like array<String>, or String[].

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive. In addition it looks for parameters that have the generic type array and suggests a stricter type like array<String>.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
105
     *
106
     * @return Config|\Symfony\CS\Config|\Symfony\CS\Config\Config
107
     */
108
    public static function create($styleCIConfigDir = null, $finderDirs = null)
109
    {
110
        $bridge = new static($styleCIConfigDir, $finderDirs);
111
112
        if (class_exists('\Symfony\CS\Config')) { // PHP-CS-Fixer >=1.12,<2.0
113
            $config = \Symfony\CS\Config::create();
114
        } elseif (class_exists('\Symfony\CS\Config\Config')) { // PHP-CS-Fixer 1.x
115
            $config = \Symfony\CS\Config\Config::create();
116
        } else { // PHP-CS-Fixer 2.x
117
            $config = Config::create();
118
        }
119
120
        // PHP-CS-Fixer 1.x BC
121
        if (method_exists($config, 'level')) {
122
            $config->level(FixerInterface::NONE_LEVEL);
123
        }
124
125
        if (method_exists($config, 'setRules')) {
126
            $config->setRules($bridge->getRules());
127
        } else { // PHP-CS-Fixer 1.x BC
128
            $config->fixers($bridge->getFixers());
129
        }
130
131
        // PHP-CS-Fixer 1.x BC
132
        if (method_exists($config, 'setRiskyAllowed')) {
133
            $config->setRiskyAllowed($bridge->getRisky());
134
        }
135
136
        // PHP-CS-Fixer 1.x BC
137
        if (method_exists($config, 'setFinder')) {
138
            $config->setFinder($bridge->getFinder());
139
        } else {
140
            $config->finder($bridge->getFinder());
141
        }
142
143
        return $config;
144
    }
145
146
    /**
147
     * @return Finder|\Symfony\CS\Finder|\Symfony\CS\Finder\DefaultFinder
148
     */
149
    public function getFinder()
150
    {
151
        // PHP-CS-Fixer 1.x BC
152
        if (class_exists('\Symfony\CS\Finder')) { // PHP-CS-Fixer >=1.12,<2.0
153
            $finder = \Symfony\CS\Finder::create()->in($this->finderDirs);
154
        } elseif (class_exists('\Symfony\CS\Finder\DefaultFinder')) { // PHP-CS-Fixer 1.x
155
            $finder = \Symfony\CS\Finder\DefaultFinder::create()->in($this->finderDirs);
156
        } else { // PHP-CS-Fixer 2.x
157
            $finder = Finder::create()->in($this->finderDirs);
158
        }
159
160
        if (isset($this->styleCIConfig['finder'])) {
161
            $finderConfig = $this->styleCIConfig['finder'];
162
            foreach ($finderConfig as $key => $values) {
163
                $finderMethod = Inflector::camelize($key);
164
                foreach ($values as $value) {
165
                    if (method_exists($finder, $finderMethod)) {
166
                        $finder->$finderMethod($value);
167
                    } else {
168
                        $this->output->writeln(sprintf(
169
                            '<warning>Can not apply "%s" finder option with PHP-CS-Fixer v%s. You fixer config may be erroneous. Consider upgrading to fix it.</warning>',
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 170 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
170
                            str_replace('_', '-', $key),
171
                            Fixer::VERSION
172
                        ));
173
                    }
174
                }
175
            }
176
        }
177
178
        return $finder;
179
    }
180
181
    /**
182
     * @return string[]
183
     */
184
    public function getFixers()
185
    {
186
        $presetFixers = $this->resolveAliases($this->getPresetFixers());
187
        $enabledFixers = $this->resolveAliases($this->styleCIConfig['enabled']);
188
        $disabledFixers = $this->resolveAliases($this->styleCIConfig['disabled']);
189
190
        $fixers = array_merge(
191
            $enabledFixers,
192
            array_map(function ($disabledFixer) {
193
                return '-'.$disabledFixer;
194
            }, $disabledFixers),
195
            array_diff($presetFixers, $disabledFixers) // Remove disabled fixers from preset
196
        );
197
198
        // PHP-CS-Fixer 1.x BC
199
        if (method_exists('Symfony\CS\Fixer\Contrib\HeaderCommentFixer', 'getHeader') && HeaderCommentFixer::getHeader()) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
200
            array_push($fixers, 'header_comment');
201
        }
202
203
        return $fixers;
204
    }
205
206
    /**
207
     * Returns fixers converted to rules for PHP-CS-Fixer 2.x.
208
     *
209
     * @return array
210
     */
211
    public function getRules()
212
    {
213
        $fixers = $this->getFixers();
214
215
        $rules = array();
216
        foreach ($fixers as $fixer) {
217
            if ('-' === $fixer[0]) {
218
                $name = substr($fixer, 1);
219
                $enabled = false;
220
            } else {
221
                $name = $fixer;
222
                $enabled = true;
223
            }
224
225
            if ($this->isFixerAvailable($name)) {
226
                $rules[$name] = $enabled;
227
            } else {
228
                $this->output->writeln(sprintf('<warning>Fixer "%s" does not exist, skipping.</warning>', $name));
229
            }
230
        }
231
232
        return $rules;
233
    }
234
235
    /**
236
     * @return bool
237
     */
238
    public function getRisky()
0 ignored issues
show
Coding Style introduced by
function getRisky() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
239
    {
240
        return $this->styleCIConfig['risky'];
241
    }
242
243
    /**
244
     * @return string[]
245
     */
246
    private function getPresetFixers()
247
    {
248
        if (static::PRESET_NONE === $this->styleCIConfig['preset']) {
249
            return array();
250
        }
251
        $validPresets = Fixers::getPresets();
252
253
        return $validPresets[$this->styleCIConfig['preset']];
254
    }
255
256
    /**
257
     * Adds both aliases and real fixers if set. PHP-CS-Fixer would not take care if not existing.
258
     * Better compatibility between PHP-CS-Fixer 1.x and 2.x.
259
     *
260
     * @param string[] $fixers
261
     *
262
     * @return string[]
263
     */
264
    private function resolveAliases(array $fixers)
265
    {
266
        foreach (Fixers::$aliases as $alias => $name) {
267 View Code Duplication
            if (in_array($alias, $fixers, true) && !in_array($name, $fixers, true) && $this->isFixerAvailable($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...
268
                array_push($fixers, $name);
269
            }
270 View Code Duplication
            if (in_array($name, $fixers, true) && !in_array($alias, $fixers, true) && $this->isFixerAvailable($alias)) {
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...
271
                array_push($fixers, $alias);
272
            }
273
        }
274
275
        return $fixers;
276
    }
277
278
    /**
279
     * @param string $name
280
     *
281
     * @return bool
282
     */
283
    private function isFixerAvailable($name)
284
    {
285
        // PHP-CS-Fixer 1.x BC
286
        if (null === $this->fixerFactory) {
287
            return true;
288
        }
289
290
        return $this->fixerFactory->hasRule($name);
291
    }
292
293
    private function parseStyleCIConfig()
294
    {
295
        if (null === $this->styleCIConfig) {
296
            $config = Yaml::parse(file_get_contents(sprintf('%s/.styleci.yml', $this->styleCIConfigDir)));
297
            $processor = new Processor();
298
            $this->styleCIConfig = $processor->processConfiguration(new Configuration(), array('styleci' => $config));
299
        }
300
    }
301
}
302