Completed
Pull Request — master (#74)
by Sullivan
02:12
created

ConfigBridge::resolveAliases()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 13
Code Lines 7

Duplication

Lines 6
Ratio 46.15 %

Importance

Changes 0
Metric Value
dl 6
loc 13
rs 7.7777
c 0
b 0
f 0
cc 8
eloc 7
nc 5
nop 1
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, 'finder')) {
138
            return $config
139
                ->finder($bridge->getFinder());
140
        }
141
142
        return $config
143
            ->setFinder($bridge->getFinder())
144
        ;
145
    }
146
147
    /**
148
     * @return Finder|\Symfony\CS\Finder|\Symfony\CS\Finder\DefaultFinder
149
     */
150
    public function getFinder()
151
    {
152
        // PHP-CS-Fixer 1.x BC
153
        if (class_exists('\Symfony\CS\Finder')) { // PHP-CS-Fixer >=1.12,<2.0
154
            $finder = \Symfony\CS\Finder::create()->in($this->finderDirs);
155
        } elseif (class_exists('\Symfony\CS\Finder\DefaultFinder')) { // PHP-CS-Fixer 1.x
156
            $finder = \Symfony\CS\Finder\DefaultFinder::create()->in($this->finderDirs);
157
        } else { // PHP-CS-Fixer 2.x
158
            $finder = Finder::create()->in($this->finderDirs);
159
        }
160
161
        if (isset($this->styleCIConfig['finder'])) {
162
            $finderConfig = $this->styleCIConfig['finder'];
163
            foreach ($finderConfig as $key => $values) {
164
                $finderMethod = Inflector::camelize($key);
165
                foreach ($values as $value) {
166
                    if (method_exists($finder, $finderMethod)) {
167
                        $finder->$finderMethod($value);
168
                    } else {
169
                        $this->output->writeln(sprintf(
170
                            '<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...
171
                            str_replace('_', '-', $key),
172
                            Fixer::VERSION
173
                        ));
174
                    }
175
                }
176
            }
177
        }
178
179
        return $finder;
180
    }
181
182
    /**
183
     * @return string[]
184
     */
185
    public function getFixers()
186
    {
187
        $presetFixers = $this->resolveAliases($this->getPresetFixers());
188
        $enabledFixers = $this->resolveAliases($this->styleCIConfig['enabled']);
189
        $disabledFixers = $this->resolveAliases($this->styleCIConfig['disabled']);
190
191
        $fixers = array_merge(
192
            $enabledFixers,
193
            array_map(function ($disabledFixer) {
194
                return '-'.$disabledFixer;
195
            }, $disabledFixers),
196
            array_diff($presetFixers, $disabledFixers) // Remove disabled fixers from preset
197
        );
198
199
        // PHP-CS-Fixer 1.x BC
200
        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...
201
            array_push($fixers, 'header_comment');
202
        }
203
204
        return $fixers;
205
    }
206
207
    /**
208
     * Returns fixers converted to rules for PHP-CS-Fixer 2.x.
209
     *
210
     * @return array
211
     */
212
    public function getRules()
213
    {
214
        $fixers = $this->getFixers();
215
216
        $rules = array();
217
        foreach ($fixers as $fixer) {
218
            if ('-' === $fixer[0]) {
219
                $name = substr($fixer, 1);
220
                $enabled = false;
221
            } else {
222
                $name = $fixer;
223
                $enabled = true;
224
            }
225
226
            if ($this->isFixerAvailable($name)) {
227
                $rules[$name] = $enabled;
228
            } else {
229
                $this->output->writeln(sprintf('<warning>Fixer "%s" does not exist, skipping.</warning>', $name));
230
            }
231
        }
232
233
        return $rules;
234
    }
235
236
    /**
237
     * @return bool
238
     */
239
    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...
240
    {
241
        return $this->styleCIConfig['risky'];
242
    }
243
244
    /**
245
     * @return string[]
246
     */
247
    private function getPresetFixers()
248
    {
249
        if (static::PRESET_NONE === $this->styleCIConfig['preset']) {
250
            return array();
251
        }
252
        $validPresets = Fixers::getPresets();
253
254
        return $validPresets[$this->styleCIConfig['preset']];
255
    }
256
257
    /**
258
     * Adds both aliases and real fixers if set. PHP-CS-Fixer would not take care if not existing.
259
     * Better compatibility between PHP-CS-Fixer 1.x and 2.x.
260
     *
261
     * @param string[] $fixers
262
     *
263
     * @return string[]
264
     */
265
    private function resolveAliases(array $fixers)
266
    {
267
        foreach (Fixers::$aliases as $alias => $name) {
268 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...
269
                array_push($fixers, $name);
270
            }
271 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...
272
                array_push($fixers, $alias);
273
            }
274
        }
275
276
        return $fixers;
277
    }
278
279
    /**
280
     * @param string $name
281
     *
282
     * @return bool
283
     */
284
    private function isFixerAvailable($name)
285
    {
286
        // PHP-CS-Fixer 1.x BC
287
        if (null === $this->fixerFactory) {
288
            return true;
289
        }
290
291
        return $this->fixerFactory->hasRule($name);
292
    }
293
294
    private function parseStyleCIConfig()
295
    {
296
        if (null === $this->styleCIConfig) {
297
            $config = Yaml::parse(file_get_contents(sprintf('%s/.styleci.yml', $this->styleCIConfigDir)));
298
            $processor = new Processor();
299
            $this->styleCIConfig = $processor->processConfiguration(new Configuration(), array('styleci' => $config));
300
        }
301
    }
302
}
303