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 (#57)
by Ross
16:56
created

CodeHelper::postProcessGeneratedCode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 1
crap 1
1
<?php declare(strict_types=1);
2
3
namespace EdmondsCommerce\DoctrineStaticMeta\CodeGeneration;
4
5
use Doctrine\Common\Util\Inflector;
6
use EdmondsCommerce\DoctrineStaticMeta\MappingHelper;
7
use gossi\codegen\generator\CodeFileGenerator;
8
use gossi\codegen\model\GenerateableInterface;
9
10
/**
11
 * Class CodeHelper
12
 *
13
 * @package EdmondsCommerce\DoctrineStaticMeta\CodeGeneration
14
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
15
 * @SuppressWarnings(PHPMD.StaticAccess)
16
 */
17
class CodeHelper
18
{
19
20
    /**
21
     * @var NamespaceHelper
22
     */
23
    private $namespaceHelper;
24
25 121
    public function __construct(NamespaceHelper $namespaceHelper)
26
    {
27 121
        $this->namespaceHelper = $namespaceHelper;
28 121
    }
29
30 3
    public function propertyIsh(string $name): string
31
    {
32 3
        return lcfirst($this->classy($name));
33
    }
34
35 31
    public function classy(string $name): string
36
    {
37 31
        return Inflector::classify($name);
38
    }
39
40 30
    public function consty(string $name): string
41
    {
42 30
        if (0 === \preg_match('%[^A-Z_]%', $name)) {
43 1
            return $name;
44
        }
45
46 30
        return strtoupper(Inflector::tableize($name));
47
    }
48
49
    /**
50
     * Fix niggles with code that is generated by gossi/php-code-generator
51
     *
52
     * @param string $generated
53
     *
54
     * @return string
55
     */
56 82
    public function postProcessGeneratedCode(string $generated): string
57
    {
58
59 82
        $generated = $this->fixSuppressWarningsTags($generated);
60 82
        $generated = $this->breakImplementsOntoLines($generated);
61 82
        $generated = $this->makeConstsPublic($generated);
62 82
        $generated = $this->constArraysOnMultipleLines($generated);
63 82
        $generated = $this->phpcsIgnoreUseSection($generated);
64 82
        $generated = $this->declareStrictFirstLine($generated);
65
66 82
        return $generated;
67
    }
68
69 82
    public function declareStrictFirstLine(string $generated): string
70
    {
71 82
        return preg_replace('%php\s+declare%', 'php declare', $generated);
72
    }
73
74 83
    public function fixSuppressWarningsTags(string $generated): string
75
    {
76 83
        return str_replace('SuppressWarnings (', 'SuppressWarnings(', $generated);
77
    }
78
79 83
    public function makeConstsPublic(string $generated): string
80
    {
81 83
        return preg_replace('%^([ ]+?)const%', '$1public const', $generated);
82
    }
83
84 83
    public function breakImplementsOntoLines(string $generated): string
85
    {
86 83
        return preg_replace_callback(
87 83
            '%class (.+?) implements (.+?){%s',
88
            function ($matches) {
89 79
                return 'class '.$matches[1].' implements '
90 79
                       ."\n    "
91 79
                       .trim(
92 79
                           implode(
93 79
                               ",\n    ",
94 79
                               explode(
95 79
                                   ', ',
96 79
                                   $matches[2]
97
                               )
98
                           )
99 79
                       )."\n{";
100 83
            },
101 83
            $generated
102
        );
103
    }
104
105 83
    public function constArraysOnMultipleLines(string $generated): string
106
    {
107 83
        return preg_replace_callback(
108 83
            "%(.*?)const ([A-Z_0-9]+?) = \[([^\]]+?)\];%",
109
            function ($matches) {
110 1
                return $matches[1].'const '.$matches[2]." = [\n        "
111 1
                       .trim(
112 1
                           implode(
113 1
                               ",\n        ",
114 1
                               explode(
115 1
                                   ', ',
116 1
                                   $matches[3]
117
                               )
118
                           )
119 1
                       )."\n    ];";
120 83
            },
121 83
            $generated
122
        );
123
    }
124
125
    /**
126
     * Use section can become long and fail line length limits. I don't care about line length here
127
     *
128
     * @param string $generated
129
     *
130
     * @return string
131
     */
132 83
    public function phpcsIgnoreUseSection(string $generated): string
133
    {
134 83
        return preg_replace(
135 83
            '%namespace (.+?);(.+?)(class|trait|interface) %si',
136 83
            "namespace \$1;\n// phpcs:disable\$2// phpcs:enable\n\$3 ",
137 83
            $generated
138
        );
139
    }
140
141
    /**
142
     * Take a potentially non existent path and resolve the relativeness into a normal path
143
     *
144
     * @param string $relativePath
145
     *
146
     * @return string
147
     * @throws \RuntimeException
148
     */
149 57
    public function resolvePath(string $relativePath): string
150
    {
151 57
        $path     = [];
152 57
        $absolute = ($relativePath[0] === '/');
153 57
        foreach (explode('/', $relativePath) as $part) {
154
            // ignore parts that have no value
155 57
            if (empty($part) || $part === '.') {
156 57
                continue;
157
            }
158
159 57
            if ($part !== '..') {
160 57
                $path[] = $part;
161 57
                continue;
162
            }
163 32
            if (count($path) > 0) {
164
                // going back up? sure
165 32
                array_pop($path);
166 32
                continue;
167
            }
168
            throw new \RuntimeException('Relative path resolves above root path.');
169
        }
170
171 57
        $return = implode('/', $path);
172 57
        if ($absolute) {
173 57
            $return = "/$return";
174
        }
175
176 57
        return $return;
177
    }
178
179
    /**
180
     * @param string $filePath
181
     *
182
     * @throws \RuntimeException
183
     */
184 28
    public function tidyNamespacesInFile(string $filePath): void
185
    {
186 28
        $contents = file_get_contents($filePath);
187 28
        $contents = preg_replace_callback(
188
        /**
189
         * @param $matches
190
         *
191
         * @return string
192
         */
193 28
            '%(namespace|use) (.+?);%',
194
            function ($matches): string {
195 28
                return $matches[1].' '.$this->namespaceHelper->tidy($matches[2]).';';
196 28
            },
197 28
            $contents
198
        );
199 28
        file_put_contents($filePath, $contents);
200 28
    }
201
202
203
    /**
204
     * We use the string type hint as our default in templates
205
     *
206
     * This method will then replace those with the updated type
207
     *
208
     * @param string $filePath
209
     * @param string $type
210
     * @param string $dbalType
211
     * @param bool   $isNullable
212
     */
213 28
    public function replaceTypeHintsInFile(
214
        string $filePath,
215
        string $type,
216
        string $dbalType,
217
        bool $isNullable
218
    ): void {
219 28
        $contents = \file_get_contents($filePath);
220
221
        $search = [
222 28
            ': string;',
223
            '(string $',
224
            ': string {',
225
            '@var string',
226
            '@return string',
227
            '@param string',
228
229
        ];
230
231
        $replaceNormal   = [
232 28
            ": $type;",
233 28
            "($type $",
234 28
            ": $type {",
235 28
            "@var $type",
236 28
            "@return $type",
237 28
            "@param $type",
238
        ];
239
        $replaceNullable = [
240 28
            ": ?$type;",
241 28
            "(?$type $",
242 28
            ": ?$type {",
243 28
            "@var $type|null",
244 28
            "@return $type|null",
245 28
            "@param $type|null",
246
        ];
247
        $replaceRemove   = [
248 28
            ';',
249
            '($',
250
            ' {',
251
            '',
252
            '',
253
            '',
254
        ];
255
256 28
        $replace = $replaceNormal;
257
258 28
        if (\in_array($dbalType, MappingHelper::MIXED_TYPES, true)) {
259 14
            $replace = $replaceRemove;
260 28
        } elseif ($isNullable) {
261 27
            $replace = $replaceNullable;
262
        }
263
264 28
        $contents = \str_replace(
265 28
            $search,
266 28
            $replace,
267 28
            $contents
268
        );
269
270 28
        \file_put_contents($filePath, $contents);
271 28
    }
272
273 82
    public function generate(GenerateableInterface $generateable, $filePath)
274
    {
275 82
        $generator = new CodeFileGenerator(
276
            [
277 82
                'generateDocblock'   => false,
278
                'declareStrictTypes' => true,
279
            ]
280
        );
281
282 82
        $generated = $generator->generate($generateable);
283 82
        $generated = $this->postProcessGeneratedCode($generated);
284 82
        \file_put_contents($filePath, $generated);
285 82
    }
286
287 21
    public function getGetterMethodNameForBoolean(string $fieldName): string
288
    {
289 21
        if (0 === stripos($fieldName, 'is')) {
290 4
            return lcfirst($fieldName);
291
        }
292
293 17
        if (0 === stripos($fieldName, 'has')) {
294 1
            return lcfirst($fieldName);
295
        }
296
297 16
        return 'is'.ucfirst($fieldName);
298
    }
299
}
300