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 (#23)
by Cees-Jan
02:06
created

ResourceGenerator::setUpFixers()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 35
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 31
nc 1
nop 0
dl 0
loc 35
ccs 0
cts 32
cp 0
crap 2
rs 8.8571
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace ApiClients\Tools\ResourceGenerator;
4
5
use Exception;
6
use PhpParser\PrettyPrinter;
7
use PhpParser\Node;
8
use Symfony\CS\Config\Config;
9
use Symfony\CS\ConfigAwareInterface;
10
use Symfony\CS\ConfigInterface;
11
use Symfony\CS\Fixer;
12
use Symfony\CS\FixerInterface;
13
14
class ResourceGenerator
15
{
16
    /**
17
     * @var callable
18
     */
19
    protected $out = 'ApiClients\Tools\ResourceGenerator\outln';
20
21
    /**
22
     * @var array
23
     */
24
    protected $configuration;
25
26
    /**
27
     * @var FileGeneratorInterface[]
28
     */
29
    protected $generators = [];
30
31
    /**
32
     * @var string
33
     */
34
    protected $pathSrc;
35
36
    /**
37
     * @var string
38
     */
39
    protected $pathTests;
40
41
    /**
42
     * @var Fixer
43
     */
44
    protected $fixer;
45
46
    /**
47
     * @var array
48
     */
49
    protected $fixers;
50
51
    public function __construct(array $configuration, callable $out = null)
52
    {
53
        $this->configuration = $configuration;
54
        $this->generators = $this->configuration['file_generators'];
55
56
        if (is_callable($out)) {
57
            $this->out = $out;
58
        }
59
60
        $this->setUpFixers();
61
    }
62
63
    protected function setUpFixers()
64
    {
65
        $this->fixer = new Fixer();
66
        $this->fixer->registerCustomFixers([
67
            new Fixer\Symfony\ExtraEmptyLinesFixer(),
68
            new Fixer\Symfony\SingleBlankLineBeforeNamespaceFixer(),
69
            new Fixer\PSR0\Psr0Fixer(),
70
            new Fixer\PSR1\EncodingFixer(),
71
            new Fixer\PSR1\ShortTagFixer(),
72
            new Fixer\PSR2\BracesFixer(),
73
            new Fixer\PSR2\ElseifFixer(),
74
            new Fixer\PSR2\EofEndingFixer(),
75
            new Fixer\PSR2\FunctionCallSpaceFixer(),
76
            new Fixer\PSR2\FunctionDeclarationFixer(),
77
            new Fixer\PSR2\IndentationFixer(),
78
            new Fixer\PSR2\LineAfterNamespaceFixer(),
79
            new Fixer\PSR2\LinefeedFixer(),
80
            new Fixer\PSR2\LowercaseConstantsFixer(),
81
            new Fixer\PSR2\LowercaseKeywordsFixer(),
82
            new Fixer\PSR2\MethodArgumentSpaceFixer(),
83
            new Fixer\PSR2\MultipleUseFixer(),
84
            new Fixer\PSR2\ParenthesisFixer(),
85
            new Fixer\PSR2\PhpClosingTagFixer(),
86
            new Fixer\PSR2\SingleLineAfterImportsFixer(),
87
            new Fixer\PSR2\TrailingSpacesFixer(),
88
            new Fixer\PSR2\VisibilityFixer(),
89
            new Fixer\Contrib\NewlineAfterOpenTagFixer(),
90
            new EmptyLineAboveDocblocksFixer(),
91
        ]);
92
        $config = Config::create()->
93
            fixers($this->fixer->getFixers())
94
        ;
95
        $this->fixer->addConfig($config);
96
        $this->fixers = $this->prepareFixers($config);
97
    }
98
99
    public function run()
100
    {
101
        foreach ($this->configuration['files'] as $definition) {
102
            $this->out('-----');
103
            $this->out('- Definition: ' . $definition['class']);
104
            $definition = $this->applyAnnotationsToDefinition($definition);
105
            $this->generateFromDefinition($definition);
106
            $this->out('-----');
107
        }
108
    }
109
110
    protected function applyAnnotationsToDefinition(array $definition): array
111
    {
112
        foreach ($definition['properties'] as $property => $properties) {
113
            if (!isset($properties['annotations'])) {
114
                continue;
115
            }
116
117
            foreach ($properties['annotations'] as $annotation => $input) {
118
                if (!isset($this->configuration['annotation_handlers'][$annotation])) {
119
                    continue;
120
                }
121
122
                if (!is_subclass_of(
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \ApiClients\Tools\Resour...HandlerInterface::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
123
                    $this->configuration['annotation_handlers'][$annotation],
124
                    AnnotationHandlerInterface::class
125
                )) {
126
                    continue;
127
                }
128
129
                $definition = forward_static_call_array(
130
                    [
131
                        $this->configuration['annotation_handlers'][$annotation],
132
                        'handle',
133
                    ],
134
                    [
135
                        $property,
136
                        $definition,
137
                        $input,
138
                    ]
139
                );
140
            }
141
        }
142
143
        return $definition;
144
    }
145
146
    /**
147
     * @param array $file
148
     * @throws Exception
149
     */
150
    protected function generateFromDefinition(array $file)
151
    {
152
        $config = $this->configuration + $file;
153
        unset($config['files']);
154
155
        foreach ($this->generators as $generatorClass) {
156
            /** @var FileGeneratorInterface $generator */
157
            $generator = new $generatorClass($config);
158
            $fileName = $generator->getFilename();
159
            $this->out('----');
160
            $this->out('-- Generator: ' . $generatorClass);
161
            $this->out('-- File: ' . $fileName);
162
            $this->out('---');
163
            $this->out('-- Generating');
164
            $node = $generator->generate();
165
            $this->out('-- Printing');
166
            $code = $this->printCode($node);
167
            $this->out('-- Saving file');
168
            $continue = $this->save($fileName, $code);
169
            if (!$continue) {
170
                continue;
171
            }
172
            $this->out('-- Applying code standards');
173
            $this->applyPsr2($fileName);
174
            $this->out('----');
175
        }
176
    }
177
178
    /**
179
     * @param Node $node
180
     * @return string
181
     */
182
    protected function printCode(Node $node): string
183
    {
184
        $prettyPrinter = new PrettyPrinter\Standard();
185
        return $prettyPrinter->prettyPrintFile([
186
            $node
187
        ]) . PHP_EOL;
188
    }
189
190
    /**
191
     * @param string $fileName
192
     * @param string $fileContents
193
     * @return bool
194
     * @throws Exception
195
     */
196
    protected function save(string $fileName, string $fileContents)
197
    {
198
        $fileName = $this->configuration['root'] . $fileName;
199
200
        if (file_exists($fileName)) {
201
            $this->out('-- Exists');
202
            return false;
203
        }
204
205
        $directory = dirname($fileName);
206
        if (!file_exists($directory)) {
207
            mkdir($directory, 0755, true);
208
        }
209
210
        if (!file_exists($directory)) {
211
            throw new Exception('Unable to create: ' . $directory);
212
        }
213
214
        file_put_contents($fileName, $fileContents);
215
216
        do {
217
            usleep(500);
218
        } while (!file_exists($fileName));
219
220
        return true;
221
    }
222
223
    /**
224
     * @param string $fileName
225
     */
226
    protected function applyPsr2($fileName)
227
    {
228
        $fileName = $this->configuration['root'] . $fileName;
229
230
        $file = new \SplFileInfo($fileName);
231
        $new = file_get_contents($file->getRealPath());
232
233
        foreach ($this->fixers as $fixer) {
234
            if (!$fixer->supports($file)) {
235
                continue;
236
            }
237
238
            $new = $fixer->fix($file, $new);
239
        }
240
241
        file_put_contents(
242
            $fileName,
243
            str_replace(
244
                '<?php',
245
                '<?php declare(strict_types=1);',
246
                $new
247
            )
248
        );
249
    }
250
251
    /**
252
     * @param ConfigInterface $config
253
     *
254
     * @return FixerInterface[]
255
     */
256
    private function prepareFixers(ConfigInterface $config): array
257
    {
258
        $fixers = $config->getFixers();
259
260
        foreach ($fixers as $fixer) {
261
            if ($fixer instanceof ConfigAwareInterface) {
0 ignored issues
show
Bug introduced by
The class Symfony\CS\ConfigAwareInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
262
                $fixer->setConfig($config);
263
            }
264
        }
265
266
        return $fixers;
267
    }
268
269
    private function out(string $message)
270
    {
271
        $out = $this->out;
272
        $out($message);
273
    }
274
}
275