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:50
created

Plugin   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 261
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 29
c 4
b 0
f 0
lcom 1
cbo 12
dl 0
loc 261
rs 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
A setComposer() 0 4 1
A run() 0 9 1
A activate() 0 7 1
A init() 0 9 1
A getSubscribedEvents() 0 11 1
A onDependenciesChangedEvent() 0 11 4
A loadInstalledPaths() 0 17 3
B saveInstalledPaths() 0 32 4
B cleanInstalledPaths() 0 11 5
B updateInstalledPaths() 0 25 4
A getPHPCodingStandardPackages() 0 18 3
A isPHPCodeSnifferInstalled() 0 11 1
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
15
use Composer\EventDispatcher\EventSubscriberInterface;
16
use Composer\IO\IOInterface;
17
use Composer\Package\AliasPackage;
18
use Composer\Package\PackageInterface;
19
use Composer\Plugin\PluginInterface;
20
use Composer\Script\Event;
21
use Composer\Script\ScriptEvents;
22
use Symfony\Component\Finder\Finder;
23
use Symfony\Component\Process\Exception\LogicException;
24
use Symfony\Component\Process\Exception\ProcessFailedException;
25
use Symfony\Component\Process\Exception\RuntimeException;
26
use Symfony\Component\Process\ProcessBuilder;
27
28
/**
29
 * PHP_CodeSniffer standard installation manager.
30
 *
31
 * @author Franck Nijhof <[email protected]>
32
 */
33
class Plugin implements PluginInterface, EventSubscriberInterface
34
{
35
36
    const PACKAGE_TYPE = 'phpcodesniffer-standard';
37
38
    const PHPCS_CONFIG_KEY = 'installed_paths';
39
40
    /**
41
     * @var Composer
42
     */
43
    private $composer;
44
45
    /**
46
     * @var IOInterface
47
     */
48
    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...
49
50
    /**
51
     * @var array
52
     */
53
    private $installedPaths;
54
55
    /**
56
     * @var ProcessBuilder
57
     */
58
    private $processBuilder;
59
60
    public function setComposer($composer)
61
    {
62
        $this->composer = $composer;
63
    }
64
65
    public static function run(Event $event)
66
    {
67
        $instance = new static();
68
69
        $composer = $event->getComposer();
70
        $instance->setComposer($composer);
71
        $instance->init();
72
        $instance->onDependenciesChangedEvent();
73
    }
74
75
    /**
76
     * {@inheritDoc}
77
     *
78
     * @throws \RuntimeException
79
     * @throws LogicException
80
     * @throws RuntimeException
81
     * @throws ProcessFailedException
82
     */
83
    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...
84
    {
85
        $this->composer = $composer;
86
        $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...
87
88
        $this->init();
89
    }
90
91
    public function init()
92
    {
93
        $this->installedPaths = [];
94
95
        $this->processBuilder = new ProcessBuilder();
96
        $this->processBuilder->setPrefix($this->composer->getConfig()->get('bin-dir') . DIRECTORY_SEPARATOR . 'phpcs');
97
98
        $this->loadInstalledPaths();
99
    }
100
101
    /**
102
     * {@inheritDoc}
103
     */
104
    public static function getSubscribedEvents()
105
    {
106
        return [
107
            ScriptEvents::POST_INSTALL_CMD => [
108
                ['onDependenciesChangedEvent', 0],
109
            ],
110
            ScriptEvents::POST_UPDATE_CMD => [
111
                ['onDependenciesChangedEvent', 0],
112
            ],
113
        ];
114
    }
115
116
    /**
117
     * Entry point for post install and post update events.
118
     *
119
     * @throws RuntimeException
120
     * @throws LogicException
121
     * @throws ProcessFailedException
122
     */
123
    public function onDependenciesChangedEvent()
124
    {
125
        if ($this->isPHPCodeSnifferInstalled() === true) {
126
            $installPathCleaned = $this->cleanInstalledPaths();
127
            $installPathUpdated = $this->updateInstalledPaths();
128
129
            if ($installPathCleaned === true || $installPathUpdated === true) {
130
                $this->saveInstalledPaths();
131
            }
132
        }
133
    }
134
135
    /**
136
     * Load all paths from PHP_CodeSniffer into an array.
137
     *
138
     * @throws RuntimeException
139
     * @throws LogicException
140
     * @throws ProcessFailedException
141
     */
142
    private function loadInstalledPaths()
143
    {
144
        if ($this->isPHPCodeSnifferInstalled() === true) {
145
            $output = $this->processBuilder
146
                ->setArguments(['--config-show', self::PHPCS_CONFIG_KEY])
147
                ->getProcess()
148
                ->mustRun()
149
                ->getOutput();
150
151
            $phpcsInstalledPaths = str_replace(self::PHPCS_CONFIG_KEY . ': ', '', $output);
152
            $phpcsInstalledPaths = trim($phpcsInstalledPaths);
153
154
            if ($phpcsInstalledPaths !== '') {
155
                $this->installedPaths = explode(',', $phpcsInstalledPaths);
156
            }
157
        }
158
    }
159
160
    /**
161
     * Save all coding standard paths back into PHP_CodeSniffer
162
     *
163
     * @throws RuntimeException
164
     * @throws LogicException
165
     * @throws ProcessFailedException
166
     */
167
    private function saveInstalledPaths()
168
    {
169
        // Check if we found installed paths to set.
170
        if (count($this->installedPaths) !== 0) {
171
            $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...
172
            $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...
173
            $configMessage = sprintf(
174
                'PHP CodeSniffer Config <info>%s</info> <comment>set to</comment> <info>%s</info>',
175
                self::PHPCS_CONFIG_KEY,
176
                $paths
177
            );
178
        } else {
179
            // Delete the installed paths if none were found.
180
            $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...
181
            $configMessage = sprintf(
182
                'PHP CodeSniffer Config <info>%s</info> <comment>delete</comment>',
183
                self::PHPCS_CONFIG_KEY
184
            );
185
        }
186
187
        $this->io->write($configMessage);
188
189
        $configResult = $this->processBuilder
190
            ->setArguments($arguments)
191
            ->getProcess()
192
            ->mustRun()
193
            ->getOutput()
194
        ;
195
        if ($this->io->isVerbose() && !empty($configResult)) {
196
            $this->io->write(sprintf('<info>%s</info>', $configResult));
197
        }
198
    }
199
200
    /**
201
     * Iterate trough all known paths and check if they are still valid.
202
     *
203
     * If path does not exists, is not an directory or isn't readable, the path
204
     * is removed from the list.
205
     *
206
     * @return bool True if changes where made, false otherwise
207
     */
208
    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...
209
    {
210
        $changes = false;
211
        foreach ($this->installedPaths as $key => $path) {
212
            if (file_exists($path) === false || is_dir($path) === false || is_readable($path) === false) {
213
                unset($this->installedPaths[$key]);
214
                $changes = true;
215
            }
216
        }
217
        return $changes;
218
    }
219
220
    /**
221
     * Check all installed packages against the installed paths from
222
     * PHP_CodeSniffer and add the missing ones.
223
     *
224
     * @return bool True if changes where made, false otherwise
225
     */
226
    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...
227
    {
228
        $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...
229
        $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...
230
231
        foreach ($codingStandardPackages as $package) {
232
            $packageInstallPath = $this->composer->getInstallationManager()->getInstallPath($package);
233
            $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...
234
            $finder->files()
235
              ->ignoreVCS(true)
236
              ->in($packageInstallPath)
237
              ->depth('> 1')
238
              ->depth('< 4')
239
              ->name('ruleset.xml');
240
            foreach ($finder as $ruleset) {
241
                $standardsPath = dirname(dirname($ruleset));
242
                if (in_array($standardsPath, $this->installedPaths, true) === false) {
243
                    $this->installedPaths[] = $standardsPath;
244
                    $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...
245
                }
246
            }
247
        }
248
249
        return $changes;
250
    }
251
252
    /**
253
     * Iterates through Composers' local repository looking for valid Coding
254
     * Standard packages.
255
     *
256
     * @return array Composer packages containing coding standard(s)
257
     */
258
    private function getPHPCodingStandardPackages()
259
    {
260
        $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...
261
            $this->composer->getRepositoryManager()->getLocalRepository()->getPackages(),
262
            function (PackageInterface $package) {
263
                if ($package instanceof AliasPackage) {
264
                    return false;
265
                }
266
                return $package->getType() === Plugin::PACKAGE_TYPE;
267
            }
268
        );
269
270
        if ($this->composer->getPackage()->getType() === self::PACKAGE_TYPE) {
271
            $codingStandardPackages[] = $this->composer->getPackage();
272
        }
273
274
        return $codingStandardPackages;
275
    }
276
277
    /**
278
     * Simple check if PHP_CodeSniffer is installed.
279
     *
280
     * @return bool PHP_CodeSniffer is installed
281
     */
282
    private function isPHPCodeSnifferInstalled()
283
    {
284
        // Check if PHP_CodeSniffer is actually installed
285
        return (count(
286
            $this
287
                ->composer
288
                ->getRepositoryManager()
289
                ->getLocalRepository()
290
                    ->findPackages('squizlabs/php_codesniffer')
291
        ) !== 0);
292
    }
293
}
294