GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#5)
by Ben
01:52
created

Plugin::getPHPCodingStandardPackages()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
rs 9.4285
cc 3
eloc 10
nc 2
nop 0
1
<?php
2
3
/**
4
 * This file is part of the Dealerdirect PHP_CodeSniffer Standards
5
 * Composer Installer Plugin package.
6
 *
7
 * @copyright 2016 Dealerdirect B.V.
8
 * @license MIT
9
 */
10
11
namespace Dealerdirect\Composer\Plugin\Installers\PHPCodeSniffer;
12
13
use Composer\Composer;
14
use Composer\EventDispatcher\EventSubscriberInterface;
15
use Composer\IO\IOInterface;
16
use Composer\Package\AliasPackage;
17
use Composer\Package\PackageInterface;
18
use Composer\Plugin\PluginInterface;
19
use Composer\Script\Event;
20
use Composer\Script\ScriptEvents;
21
use Symfony\Component\Finder\Finder;
22
use Symfony\Component\Process\Exception\LogicException;
23
use Symfony\Component\Process\Exception\ProcessFailedException;
24
use Symfony\Component\Process\Exception\RuntimeException;
25
use Symfony\Component\Process\ProcessBuilder;
26
27
/**
28
 * PHP_CodeSniffer standard installation manager.
29
 *
30
 * @author Franck Nijhof <[email protected]>
31
 */
32
class Plugin implements PluginInterface, EventSubscriberInterface
33
{
34
    const MESSAGE_RUNNING_INSTALLER = 'Running PHPCodeSniffer Composer Installer';
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
35
    const MESSAGE_NOTHING_TO_INSTALL = 'Nothing to install or update';
36
    const MESSAGE_NOT_INSTALLED = 'PHPCodeSniffer is not installed';
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
37
38
    const PACKAGE_NAME = 'squizlabs/php_codesniffer';
39
    const PACKAGE_TYPE = 'phpcodesniffer-standard';
40
41
    const PHPCS_CONFIG_KEY = 'installed_paths';
42
43
    /**
44
     * @var Composer
45
     */
46
    private $composer;
47
48
    /**
49
     * @var IOInterface
50
     */
51
    private $io;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $io. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
52
53
    /**
54
     * @var array
55
     */
56
    private $installedPaths;
57
58
    /**
59
     * @var ProcessBuilder
60
     */
61
    private $processBuilder;
62
63
    public static function run(Event $event)
64
    {
65
        $io = $event->getIO();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $io. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
66
        $composer = $event->getComposer();
67
68
        $instance = new static();
69
70
        $instance->io = $io;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
71
        $instance->composer = $composer;
72
        $instance->init();
73
        $instance->onDependenciesChangedEvent();
74
    }
75
76
    /**
77
     * {@inheritDoc}
78
     *
79
     * @throws \RuntimeException
80
     * @throws LogicException
81
     * @throws RuntimeException
82
     * @throws ProcessFailedException
83
     */
84
    public function activate(Composer $composer, IOInterface $io)
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $io. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
85
    {
86
        $this->composer = $composer;
87
        $this->io = $io;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
88
89
        $this->init();
90
    }
91
92
    private function init()
93
    {
94
        $this->installedPaths = [];
95
96
        $this->processBuilder = new ProcessBuilder();
97
        $this->processBuilder->setPrefix($this->composer->getConfig()->get('bin-dir') . DIRECTORY_SEPARATOR . 'phpcs');
98
99
        $this->loadInstalledPaths();
100
    }
101
102
    /**
103
     * {@inheritDoc}
104
     */
105
    public static function getSubscribedEvents()
106
    {
107
        return [
108
            ScriptEvents::POST_INSTALL_CMD => [
109
                ['onDependenciesChangedEvent', 0],
110
            ],
111
            ScriptEvents::POST_UPDATE_CMD => [
112
                ['onDependenciesChangedEvent', 0],
113
            ],
114
        ];
115
    }
116
117
    /**
118
     * Entry point for post install and post update events.
119
     *
120
     * @throws RuntimeException
121
     * @throws LogicException
122
     * @throws ProcessFailedException
123
     */
124
    public function onDependenciesChangedEvent()
125
    {
126
        $io = $this->io;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $io. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
127
        $isVerbose = $io->isVerbose();
128
129
        if ($isVerbose) {
130
            $io->write(sprintf('<info>%s</info>', self::MESSAGE_RUNNING_INSTALLER));
131
        }
132
133
        if ($this->isPHPCodeSnifferInstalled() === true) {
134
            $installPathCleaned = $this->cleanInstalledPaths();
135
            $installPathUpdated = $this->updateInstalledPaths();
136
137
            if ($installPathCleaned === true || $installPathUpdated === true) {
138
                $this->saveInstalledPaths();
139
            } elseif ($isVerbose) {
140
                $io->write(sprintf('<info>%s</info>', self::MESSAGE_NOTHING_TO_INSTALL));
141
            }
142
        } elseif ($isVerbose) {
143
            $io->write(sprintf('<info>%s</info>', self::MESSAGE_NOT_INSTALLED));
144
        }
145
    }
146
147
    /**
148
     * Load all paths from PHP_CodeSniffer into an array.
149
     *
150
     * @throws RuntimeException
151
     * @throws LogicException
152
     * @throws ProcessFailedException
153
     */
154
    private function loadInstalledPaths()
155
    {
156
        if ($this->isPHPCodeSnifferInstalled() === true) {
157
            $output = $this->processBuilder
158
                ->setArguments(['--config-show', self::PHPCS_CONFIG_KEY])
159
                ->getProcess()
160
                ->mustRun()
161
                ->getOutput();
162
163
            $phpcsInstalledPaths = str_replace(self::PHPCS_CONFIG_KEY . ': ', '', $output);
164
            $phpcsInstalledPaths = trim($phpcsInstalledPaths);
165
166
            if ($phpcsInstalledPaths !== '') {
167
                $this->installedPaths = explode(',', $phpcsInstalledPaths);
168
            }
169
        }
170
    }
171
172
    /**
173
     * Save all coding standard paths back into PHP_CodeSniffer
174
     *
175
     * @throws RuntimeException
176
     * @throws LogicException
177
     * @throws ProcessFailedException
178
     */
179
    private function saveInstalledPaths()
180
    {
181
        // Check if we found installed paths to set.
182
        if (count($this->installedPaths) !== 0) {
183
            $paths = implode(',', $this->installedPaths);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 9 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
184
            $arguments = ['--config-set', self::PHPCS_CONFIG_KEY, $paths];
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
185
            $configMessage = sprintf(
186
                'PHP CodeSniffer Config <info>%s</info> <comment>set to</comment> <info>%s</info>',
187
                self::PHPCS_CONFIG_KEY,
188
                $paths
189
            );
190
        } else {
191
            // Delete the installed paths if none were found.
192
            $arguments = ['--config-delete', self::PHPCS_CONFIG_KEY];
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
193
            $configMessage = sprintf(
194
                'PHP CodeSniffer Config <info>%s</info> <comment>delete</comment>',
195
                self::PHPCS_CONFIG_KEY
196
            );
197
        }
198
199
        $this->io->write($configMessage);
200
201
        $configResult = $this->processBuilder
202
            ->setArguments($arguments)
203
            ->getProcess()
204
            ->mustRun()
205
            ->getOutput()
206
        ;
207
        if ($this->io->isVerbose() && !empty($configResult)) {
208
            $this->io->write(sprintf('<info>%s</info>', $configResult));
209
        }
210
    }
211
212
    /**
213
     * Iterate trough all known paths and check if they are still valid.
214
     *
215
     * If path does not exists, is not an directory or isn't readable, the path
216
     * is removed from the list.
217
     *
218
     * @return bool True if changes where made, false otherwise
219
     */
220
    private function cleanInstalledPaths()
0 ignored issues
show
Coding Style introduced by
function cleanInstalledPaths() 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...
221
    {
222
        $changes = false;
223
        foreach ($this->installedPaths as $key => $path) {
224
            if (file_exists($path) === false || is_dir($path) === false || is_readable($path) === false) {
225
                unset($this->installedPaths[$key]);
226
                $changes = true;
227
            }
228
        }
229
        return $changes;
230
    }
231
232
    /**
233
     * Check all installed packages against the installed paths from
234
     * PHP_CodeSniffer and add the missing ones.
235
     *
236
     * @return bool True if changes where made, false otherwise
237
     */
238
    private function updateInstalledPaths()
0 ignored issues
show
Coding Style introduced by
function updateInstalledPaths() 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
        $changes = false;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 16 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
241
        $codingStandardPackages = $this->getPHPCodingStandardPackages();
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $codingStandardPackages exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
242
243
        foreach ($codingStandardPackages as $package) {
244
            $packageInstallPath = $this->composer->getInstallationManager()->getInstallPath($package);
245
            $finder = new Finder();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 13 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
246
            $finder->files()
247
              ->ignoreVCS(true)
248
              ->in($packageInstallPath)
249
              ->depth('> 1')
250
              ->depth('< 4')
251
              ->name('ruleset.xml');
252
            foreach ($finder as $ruleset) {
253
                $standardsPath = dirname(dirname($ruleset));
254
                if (in_array($standardsPath, $this->installedPaths, true) === false) {
255
                    $this->installedPaths[] = $standardsPath;
256
                    $changes = true;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 16 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
257
                }
258
            }
259
        }
260
261
        return $changes;
262
    }
263
264
    /**
265
     * Iterates through Composers' local repository looking for valid Coding
266
     * Standard packages.
267
     *
268
     * @return array Composer packages containing coding standard(s)
269
     */
270
    private function getPHPCodingStandardPackages()
271
    {
272
        $codingStandardPackages = array_filter(
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $codingStandardPackages exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
273
            $this->composer->getRepositoryManager()->getLocalRepository()->getPackages(),
274
            function (PackageInterface $package) {
275
                if ($package instanceof AliasPackage) {
276
                    return false;
277
                }
278
                return $package->getType() === Plugin::PACKAGE_TYPE;
279
            }
280
        );
281
282
        if ($this->composer->getPackage()->getType() === self::PACKAGE_TYPE) {
283
            $codingStandardPackages[] = $this->composer->getPackage();
284
        }
285
286
        return $codingStandardPackages;
287
    }
288
289
    /**
290
     * Simple check if PHP_CodeSniffer is installed.
291
     *
292
     * @return bool Whether PHP_CodeSniffer is installed
293
     */
294
    private function isPHPCodeSnifferInstalled()
295
    {
296
        $packages = $this
297
            ->composer
298
            ->getRepositoryManager()
299
            ->getLocalRepository()
300
            ->findPackages(self::PACKAGE_NAME)
301
        ;
302
303
        $packageCount = count($packages);
304
305
        return ($packageCount !== 0);
306
    }
307
}
308