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

ConfigBridge::parseStyleCIConfig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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