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 joseph
16:59
created

UsesPHPMetaDataTrait::runInitMethods()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 9
cts 9
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 10
nop 0
crap 5
1
<?php declare(strict_types=1);
2
3
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Traits;
4
5
use Doctrine\Common\Util\Debug;
6
use Doctrine\Common\Util\Inflector;
7
use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder;
8
use Doctrine\ORM\Mapping\ClassMetadata as DoctrineClassMetaData;
9
use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\Generator\AbstractGenerator;
10
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\UsesPHPMetaDataInterface;
11
use EdmondsCommerce\DoctrineStaticMeta\Exception\DoctrineStaticMetaException;
12
use EdmondsCommerce\DoctrineStaticMeta\MappingHelper;
13
14
trait UsesPHPMetaDataTrait
15
{
16
17
    /**
18
     * @var \ReflectionClass
19
     */
20
    private static $reflectionClass;
21
22
    /**
23
     * @var string
24
     */
25
    private static $singular;
26
27
    /**
28
     * @var string
29
     */
30
    private static $plural;
31
32
    /**
33
     * @var array
34
     */
35
    private static $setters;
36
37
    /**
38
     * @var array
39
     */
40
    private static $getters;
41
42
43
    /**
44
     * UsesPHPMetaDataTrait constructor.
45
     *
46
     * @throws \ReflectionException
47
     */
48 1
    public function __construct()
49
    {
50 1
        $this->runInitMethods();
51 1
    }
52
53
    /**
54
     * Find and run all init methods
55
     * - defined in relationship traits and generally to init ArrayCollection properties
56
     *
57
     * @throws \ReflectionException
58
     */
59 38
    protected function runInitMethods(): void
60
    {
61 38
        if (!static::$reflectionClass instanceof \ReflectionClass) {
0 ignored issues
show
Bug introduced by
Since $reflectionClass is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $reflectionClass to at least protected.
Loading history...
introduced by
static::reflectionClass is always a sub-type of ReflectionClass. If static::reflectionClass can have other possible types, add them to src/Entity/Traits/UsesPHPMetaDataTrait.php:18.
Loading history...
62 19
            static::$reflectionClass = new \ReflectionClass(static::class);
63
        }
64 38
        $methods = static::$reflectionClass->getMethods(\ReflectionMethod::IS_PRIVATE);
65 38
        foreach ($methods as $method) {
66 38
            if ($method instanceof \ReflectionMethod) {
67 38
                $method = $method->getName();
68
            }
69 38
            if (0 === strpos($method, UsesPHPMetaDataInterface::METHOD_PREFIX_INIT)) {
70 38
                $this->$method();
71
            }
72
        }
73 38
    }
74
75
    /**
76
     * Loads the class and property meta data in the class
77
     *
78
     * This is the method called by Doctrine to load the meta data
79
     *
80
     * @param DoctrineClassMetaData $metadata
81
     *
82
     * @throws DoctrineStaticMetaException
83
     * @SuppressWarnings(PHPMD.StaticAccess)
84
     */
85 37
    public static function loadMetadata(DoctrineClassMetaData $metadata): void
86
    {
87
        try {
88 37
            $builder                 = new ClassMetadataBuilder($metadata);
89 37
            static::$reflectionClass = $metadata->getReflectionClass();
0 ignored issues
show
Bug introduced by
Since $reflectionClass is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $reflectionClass to at least protected.
Loading history...
90 37
            static::loadPropertyDoctrineMetaData($builder);
91 37
            static::loadClassDoctrineMetaData($builder);
92 37
            static::setChangeTrackingPolicy($builder);
93
        } catch (\Exception $e) {
94
            throw new DoctrineStaticMetaException(
95
                'Exception in '.__METHOD__.': '.$e->getMessage(),
96
                $e->getCode(),
97
                $e
98
            );
99
        }
100 37
    }
101
102
    /**
103
     * Setthing the change policy to be deferred explicit for the moment. Should consider if this needs to be
104
     * configurable in the future
105
     *
106
     * @see http://doctrine-orm.readthedocs.io/en/latest/reference/change-tracking-policies.html
107
     *
108
     * @param ClassMetadataBuilder $builder
109
     */
110 37
    public static function setChangeTrackingPolicy(ClassMetadataBuilder $builder)
111
    {
112 37
        $builder->setChangeTrackingPolicyDeferredExplicit();
113 37
    }
114
115
    /**
116
     * This method will reflect on the entity class and pull out all the methods that begin with
117
     * UsesPHPMetaDataInterface::METHOD_PREFIX_GET_PROPERTY_DOCTRINE_META
118
     *
119
     * Once it has an array of methods, it calls them all, passing in the $builder
120
     *
121
     * @param ClassMetadataBuilder $builder
122
     *
123
     * @throws DoctrineStaticMetaException
124
     * @SuppressWarnings(PHPMD.StaticAccess)
125
     */
126 37
    protected static function loadPropertyDoctrineMetaData(ClassMetadataBuilder $builder): void
127
    {
128 37
        $methodName = '__no_method__';
129
        try {
130 37
            $staticMethods = static::getStaticMethods();
131
            //now loop through and call them
132 37
            foreach ($staticMethods as $method) {
133 37
                $methodName = $method->getName();
134 37
                if (0 === stripos(
135 37
                        $methodName,
136 37
                        UsesPHPMetaDataInterface::METHOD_PREFIX_GET_PROPERTY_DOCTRINE_META
137
                    )
138
                ) {
139 37
                    static::$methodName($builder);
140
                }
141
            }
142
        } catch (\Exception $e) {
143
            throw new DoctrineStaticMetaException(
144
                'Exception in '.__METHOD__.'for '
145
                .static::$reflectionClass->getName()."::$methodName\n\n"
0 ignored issues
show
Bug introduced by
Since $reflectionClass is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $reflectionClass to at least protected.
Loading history...
146
                .$e->getMessage()
147
            );
148
        }
149 37
    }
150
151
    /**
152
     * Get class level meta data, eg table name, custom repository
153
     *
154
     * @param ClassMetadataBuilder $builder
155
     *
156
     * @SuppressWarnings(PHPMD.StaticAccess)
157
     */
158 37
    protected static function loadClassDoctrineMetaData(ClassMetadataBuilder $builder): void
159
    {
160 37
        $tableName = MappingHelper::getTableNameForEntityFqn(static::class);
161 37
        $builder->setTable($tableName);
162 37
        static::setCustomRepositoryClass($builder);
163 37
    }
164
165
    /**
166
     * In the class itself, we need to specify the repository class name
167
     *
168
     * @param ClassMetadataBuilder $builder
169
     *
170
     * @return mixed
171
     */
172
    abstract protected static function setCustomRepositoryClass(ClassMetadataBuilder $builder);
173
174
    /**
175
     * Get an array of all static methods implemented by the current class
176
     *
177
     * Merges trait methods
178
     * Filters out this trait
179
     *
180
     * @return array|\ReflectionMethod[]
181
     * @throws \ReflectionException
182
     */
183 39
    protected static function getStaticMethods(): array
184
    {
185 39
        $currentClass = static::class;
186
        // get class level static methods
187 39
        if (!static::$reflectionClass instanceof \ReflectionClass
0 ignored issues
show
introduced by
static::reflectionClass is always a sub-type of ReflectionClass. If static::reflectionClass can have other possible types, add them to src/Entity/Traits/UsesPHPMetaDataTrait.php:18.
Loading history...
Bug introduced by
Since $reflectionClass is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $reflectionClass to at least protected.
Loading history...
188 39
            || static::$reflectionClass->getName() !== $currentClass
189
        ) {
190
            static::$reflectionClass = new \ReflectionClass($currentClass);
191
        }
192 39
        $staticMethods = static::$reflectionClass->getMethods(
193 39
            \ReflectionMethod::IS_STATIC
194
        );
195
        // get static methods from traits
196 39
        $traits = self::$reflectionClass->getTraits();
197 39
        foreach ($traits as $trait) {
198 39
            if ($trait->getShortName() === 'UsesPHPMetaData') {
199
                continue;
200
            }
201 39
            $traitStaticMethods = $trait->getMethods(
202 39
                \ReflectionMethod::IS_STATIC
203
            );
204 39
            array_merge(
205 39
                $staticMethods,
206 39
                $traitStaticMethods
207
            );
208
        }
209
210 39
        return $staticMethods;
211
    }
212
213
214
    /**
215
     * Get the property name the Entity is mapped by when plural
216
     *
217
     * Override it in your entity class if you are using an Entity class name that doesn't pluralize nicely
218
     *
219
     * @return string
220
     * @throws DoctrineStaticMetaException
221
     * @SuppressWarnings(PHPMD.StaticAccess)
222
     */
223 6
    public static function getPlural(): string
224
    {
225
        try {
226 6
            if (null === static::$plural) {
0 ignored issues
show
Bug introduced by
Since $plural is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $plural to at least protected.
Loading history...
introduced by
The condition null === static::plural is always false. If null === static::plural can have other possible types, add them to src/Entity/Traits/UsesPHPMetaDataTrait.php:28
Loading history...
227 6
                $singular       = static::getSingular();
228 6
                static::$plural = Inflector::pluralize($singular);
229
            }
230
231 6
            return static::$plural;
232
        } catch (\Exception $e) {
233
            throw new DoctrineStaticMetaException('Exception in '.__METHOD__.': '.$e->getMessage(), $e->getCode(), $e);
234
        }
235
    }
236
237
    /**
238
     * Get the property the name the Entity is mapped by when singular
239
     *
240
     * @return string
241
     * @throws DoctrineStaticMetaException
242
     * @SuppressWarnings(PHPMD.StaticAccess)
243
     */
244 7
    public static function getSingular(): string
245
    {
246
        try {
247 7
            if (null === static::$singular) {
0 ignored issues
show
Bug introduced by
Since $singular is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $singular to at least protected.
Loading history...
introduced by
The condition null === static::singular is always false. If null === static::singular can have other possible types, add them to src/Entity/Traits/UsesPHPMetaDataTrait.php:23
Loading history...
248 6
                if (null === self::$reflectionClass) {
249 5
                    self::$reflectionClass = new \ReflectionClass(static::class);
250
                }
251
252 6
                $shortName         = self::$reflectionClass->getShortName();
253 6
                $singularShortName = Inflector::singularize($shortName);
254
255 6
                $namespaceName   = self::$reflectionClass->getNamespaceName();
256 6
                $namespaceParts  = \explode(AbstractGenerator::ENTITIES_FOLDER_NAME, $namespaceName);
257 6
                $entityNamespace = \array_pop($namespaceParts);
258
259 6
                $namespacedShortName = \preg_replace(
260 6
                    '/\\\\/',
261 6
                    '',
262 6
                    $entityNamespace.$singularShortName
263
                );
264
265 6
                static::$singular = \lcfirst($namespacedShortName);
266
            }
267
268 7
            return static::$singular;
269
        } catch (\Exception $e) {
270
            throw new DoctrineStaticMetaException('Exception in '.__METHOD__.': '.$e->getMessage(), $e->getCode(), $e);
271
        }
272
    }
273
274
    /**
275
     * Get an array of setters by name
276
     *
277
     * @return array|string[]
278
     */
279 2
    public function getSetters(): array
280
    {
281 2
        if (null !== static::$setters) {
0 ignored issues
show
Bug introduced by
Since $setters is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $setters to at least protected.
Loading history...
introduced by
The condition null !== static::setters is always true. If null !== static::setters can have other possible types, add them to src/Entity/Traits/UsesPHPMetaDataTrait.php:33
Loading history...
282 1
            return static::$setters;
283
        }
284
        $skip            = [
285 2
            'setChangeTrackingPolicy' => true,
286
        ];
287 2
        static::$setters = [];
288 2
        foreach (self::$reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
289 2
            $methodName = $method->getName();
290 2
            if (isset($skip[$methodName])) {
291 2
                continue;
292
            }
293 2
            if (0 === \strpos($methodName, 'set')) {
294 2
                static::$setters[] = $methodName;
295 2
                continue;
296
            }
297 2
            if (0 === \strpos($methodName, 'add')) {
298 1
                static::$setters[] = $methodName;
299 2
                continue;
300
            }
301
        }
302
303 2
        return static::$setters;
304
    }
305
306
    /**
307
     * Get an array of getters by name
308
     * [];
309
     * @return array|string[]
310
     */
311 1
    public function getGetters(): array
312
    {
313 1
        if (null !== static::$getters) {
0 ignored issues
show
Bug introduced by
Since $getters is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $getters to at least protected.
Loading history...
introduced by
The condition null !== static::getters is always true. If null !== static::getters can have other possible types, add them to src/Entity/Traits/UsesPHPMetaDataTrait.php:38
Loading history...
314
            return static::$getters;
315
        }
316
        $skip = [
317 1
            'getPlural'    => true,
318
            'getSingular'  => true,
319
            'getSetters'   => true,
320
            'getGetters'   => true,
321
            'getIdField'   => true,
322
            'getShortName' => true,
323
        ];
324
325 1
        static::$getters = [];
326 1
        foreach (self::$reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
327 1
            $methodName = $method->getName();
328 1
            if (isset($skip[$methodName])) {
329 1
                continue;
330
            }
331 1
            if (0 === \strpos($methodName, 'get')) {
332 1
                static::$getters[] = $methodName;
333 1
                continue;
334
            }
335
        }
336
337 1
        return static::$getters;
338
    }
339
340
    /**
341
     * Which field is being used for ID - will normally be `id` as implemented by
342
     * \EdmondsCommerce\DoctrineStaticMeta\Fields\Traits\IdField
343
     *
344
     * @return string
345
     * @SuppressWarnings(PHPMD.StaticAccess)
346
     */
347 2
    public static function getIdField(): string
348
    {
349 2
        return 'id';
350
    }
351
352
    /**
353
     * Get the short name (without fully qualified namespace) of the current Entity
354
     *
355
     * @return string
356
     */
357 1
    public function getShortName(): string
358
    {
359 1
        return static::$reflectionClass->getShortName();
0 ignored issues
show
Bug introduced by
Since $reflectionClass is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $reflectionClass to at least protected.
Loading history...
360
    }
361
362
    /**
363
     * @return string
364
     * @SuppressWarnings(PHPMD.StaticAccess)
365
     */
366 1
    public function __toString(): string
367
    {
368 1
        return (string)print_r(Debug::export($this, 2), true);
369
    }
370
}
371