PhpCodeSniffer::canExecuteOnStage()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Fabrica\Tools\Plugin;
4
5
use Fabrica\Tools;
6
use Fabrica\Tools\Builder;
7
use Fabrica\Models\Infra\Ci\Build;
8
use Fabrica\Models\Infra\Ci\BuildError;
9
use Fabrica\Tools\Plugin;
10
use Fabrica\Tools\ZeroConfigPluginInterface;
11
12
/**
13
 * PHP Code Sniffer Plugin - Allows PHP Code Sniffer testing.
14
 *
15
 * @author Ricardo Sierra <[email protected]>
16
 */
17
class PhpCodeSniffer extends Plugin implements ZeroConfigPluginInterface
18
{
19
    /**
20
     * @var array
21
     */
22
    protected $suffixes;
23
24
    /**
25
     * @var string
26
     */
27
    protected $standard;
28
29
    /**
30
     * @var string
31
     */
32
    protected $tabWidth;
33
34
    /**
35
     * @var string
36
     */
37
    protected $encoding;
38
39
    /**
40
     * @var int
41
     */
42
    protected $allowedErrors;
43
44
    /**
45
     * @var int
46
     */
47
    protected $allowedWarnings;
48
49
    /**
50
     * @var int
51
     */
52
    protected $severity = null;
53
    /**
54
     * @var null|int
55
     */
56
    protected $errorSeverity = null;
57
58
    /**
59
     * @var null|int
60
     */
61
    protected $warningSeverity = null;
62
63
    /**
64
     * @return string
65
     */
66
    public static function pluginName()
67
    {
68
        return 'php_code_sniffer';
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function __construct(Builder $builder, Build $build, array $options = [])
75
    {
76
        parent::__construct($builder, $build, $options);
77
78
        $this->suffixes        = ['php'];
79
        $this->standard        = 'PSR2';
80
        $this->tabWidth        = '';
81
        $this->encoding        = '';
82
        $this->allowedWarnings = 0;
83
        $this->allowedErrors   = 0;
84
85
        $this->executable = $this->findBinary('phpcs');
86
87
        if (isset($options['zero_config']) && $options['zero_config']) {
88
            $this->allowedWarnings = -1;
89
            $this->allowedErrors   = -1;
90
        }
91
92
        if (!empty($options['allowed_errors']) && is_int($options['allowed_errors'])) {
93
            $this->allowedErrors = $options['allowed_errors'];
94
        }
95
96
        if (!empty($options['allowed_warnings']) && is_int($options['allowed_warnings'])) {
97
            $this->allowedWarnings = $options['allowed_warnings'];
98
        }
99
100
        if (isset($options['suffixes'])) {
101
            $this->suffixes = (array) $options['suffixes'];
102
        }
103
104
        if (!empty($options['tab_width'])) {
105
            $this->tabWidth = ' --tab-width=' . $options['tab_width'];
106
        }
107
108
        if (!empty($options['encoding'])) {
109
            $this->encoding = ' --encoding=' . $options['encoding'];
110
        }
111
112
        if (!empty($options['standard'])) {
113
            $this->standard = $options['standard'];
114
        }
115
116
        if (isset($options['severity']) && is_int($options['severity'])) {
117
            $this->severity = $options['severity'];
118
        }
119
120
        if (isset($options['error_severity']) && is_int($options['error_severity'])) {
121
            $this->errorSeverity = $options['error_severity'];
122
        }
123
124
        if (isset($options['warning_severity']) && is_int($options['warning_severity'])) {
125
            $this->warningSeverity = $options['warning_severity'];
126
        }
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public static function canExecuteOnStage($stage, Build $build)
133
    {
134
        if (Build::STAGE_TEST === $stage) {
135
            return true;
136
        }
137
138
        return false;
139
    }
140
141
    /**
142
     * Runs PHP Code Sniffer in a specified directory, to a specified standard.
143
     */
144
    public function execute()
145
    {
146
        list($ignore, $standard, $suffixes, $severity, $errorSeverity, $warningSeverity) = $this->getFlags();
147
148
        $phpcs = $this->executable;
149
150 View Code Duplication
        if ((!defined('DEBUG_MODE') || !DEBUG_MODE) 
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...
151
            && !(bool)$this->build->getExtra('debug')
152
        ) {
153
            $this->builder->logExecOutput(false);
154
        }
155
156
        $cmd = 'cd "%s" && ' . $phpcs . ' --report=json %s %s %s %s %s "%s" %s %s %s';
157
        $this->builder->executeCommand(
158
            $cmd,
159
            $this->builder->buildPath,
160
            $standard,
161
            $suffixes,
162
            $ignore,
163
            $this->tabWidth,
164
            $this->encoding,
165
            $this->directory,
166
            $severity,
167
            $errorSeverity,
168
            $warningSeverity
169
        );
170
171
        $output                  = $this->builder->getLastOutput();
172
        list($errors, $warnings) = $this->processReport($output);
173
174
        $this->builder->logExecOutput(true);
175
176
        $success = true;
177
        $this->build->storeMeta((self::pluginName() . '-warnings'), $warnings);
178
        $this->build->storeMeta((self::pluginName() . '-errors'), $errors);
179
180
        if (-1 != $this->allowedWarnings && $warnings > $this->allowedWarnings) {
181
            $success = false;
182
        }
183
184
        if (-1 != $this->allowedErrors && $errors > $this->allowedErrors) {
185
            $success = false;
186
        }
187
188
        return $success;
189
    }
190
191
    /**
192
     * Process options and produce an arguments string for PHPCS.
193
     *
194
     * @return array
195
     */
196
    protected function getFlags()
197
    {
198
        $ignore = '';
199
        if (count($this->ignore)) {
200
            $ignore = sprintf(' --ignore="%s"', implode(',', $this->ignore));
201
        }
202
203
        $standardPath = $this->normalizePath($this->standard);
204
        if (file_exists($standardPath)) {
205
            $standard = ' --standard=' . $standardPath;
206
        } else {
207
            $standard = ' --standard=' . $this->standard;
208
        }
209
210
        $suffixes = '';
211
        if (count($this->suffixes)) {
212
            $suffixes = ' --extensions=' . implode(',', $this->suffixes);
213
        }
214
215
        $severity = '';
216
        if (null !== $this->severity) {
217
            $severity = ' --severity=' . $this->severity;
218
        }
219
220
        $errorSeverity = '';
221
        if (null !== $this->errorSeverity) {
222
            $errorSeverity = ' --error-severity=' . $this->errorSeverity;
223
        }
224
225
        $warningSeverity = '';
226
        if (null !== $this->warningSeverity) {
227
            $warningSeverity = ' --warning-severity=' . $this->warningSeverity;
228
        }
229
230
        return [$ignore, $standard, $suffixes, $severity, $errorSeverity, $warningSeverity];
231
    }
232
233
    /**
234
     * Process the PHPCS output report.
235
     *
236
     * @param  $output
237
     * @return array
238
     * @throws \Exception
239
     */
240
    protected function processReport($output)
241
    {
242
        $data = json_decode(trim($output), true);
243
244
        if (!is_array($data)) {
245
            $this->builder->log($output);
246
            throw new \Exception('Could not process the report generated by PHP Code Sniffer.');
247
        }
248
249
        $errors   = $data['totals']['errors'];
250
        $warnings = $data['totals']['warnings'];
251
252
        foreach ($data['files'] as $fileName => $file) {
253
            $fileName = str_replace($this->builder->buildPath, '', $fileName);
254
255
            foreach ($file['messages'] as $message) {
256
                $this->build->reportError(
257
                    $this->builder,
258
                    self::pluginName(),
259
                    'PHPCS: ' . $message['message'],
260
                    'ERROR' == $message['type'] ? BuildError::SEVERITY_HIGH : BuildError::SEVERITY_LOW,
261
                    $fileName,
262
                    $message['line']
263
                );
264
            }
265
        }
266
267
        return [$errors, $warnings];
268
    }
269
}
270