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
Push — master ( 84e592...894b2c )
by joseph
127:56 queued 125:09
created

AbstractEntityFixtureLoader   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 287
Duplicated Lines 0 %

Test Coverage

Coverage 45.31%

Importance

Changes 0
Metric Value
eloc 76
dl 0
loc 287
ccs 58
cts 128
cp 0.4531
rs 10
c 0
b 0
f 0
wmc 28

16 Methods

Rating   Name   Duplication   Size   Complexity  
A setCustomData() 0 5 1
A getContainer() 0 3 1
A getReference() 0 8 2
A generateCustomFixtures() 0 8 2
A generateCustomFixture() 0 3 1
A addReference() 0 6 2
A validateNumberGenerated() 0 7 3
A load() 0 13 2
A setReferenceRepository() 0 4 1
A __construct() 0 18 2
A updateGenerated() 0 6 2
A setUsingReferences() 0 5 1
A assertReferencePrefixOverridden() 0 4 2
A loadBulk() 0 14 3
A getEntityFqn() 0 7 2
A setModifier() 0 3 1
1
<?php declare(strict_types=1);
2
3
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Testing\Fixtures;
4
5
use Doctrine\Common\DataFixtures\AbstractFixture;
6
use Doctrine\Common\Persistence\ObjectManager;
7
use Doctrine\ORM\EntityManagerInterface;
8
use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\NamespaceHelper;
9
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\EntityInterface;
10
use EdmondsCommerce\DoctrineStaticMeta\Entity\Savers\EntitySaverFactory;
11
use EdmondsCommerce\DoctrineStaticMeta\Entity\Savers\EntitySaverInterface;
12
use EdmondsCommerce\DoctrineStaticMeta\Entity\Testing\EntityGenerator\TestEntityGenerator;
13
use EdmondsCommerce\DoctrineStaticMeta\Entity\Testing\EntityGenerator\TestEntityGeneratorFactory;
14
use Psr\Container\ContainerInterface;
15
16
/**
17
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
18
 */
19
abstract class AbstractEntityFixtureLoader extends AbstractFixture
20
{
21
    /**
22
     * If you override the loadBulk method, please ensure you update this number to reflect the number of Entities you
23
     * are actually generating
24
     */
25
    public const BULK_AMOUNT_TO_GENERATE = 100;
26
27
    public const REFERENCE_PREFIX = 'OVERRIDE ME';
28
29
    /**
30
     * @var TestEntityGenerator
31
     */
32
    protected $testEntityGenerator;
33
    /**
34
     * @var EntitySaverInterface
35
     */
36
    protected $saver;
37
38
    /**
39
     * @var null|FixtureEntitiesModifierInterface
40
     */
41
    protected $modifier;
42
43
    /**
44
     * @var string
45
     */
46
    protected $entityFqn;
47
    /**
48
     * @var NamespaceHelper
49
     */
50
    protected $namespaceHelper;
51
52
    /**
53
     * @var TestEntityGeneratorFactory
54
     */
55
    private $testEntityGeneratorFactory;
56
    /**
57
     * @var ContainerInterface
58
     */
59
    private $container;
60
61
    private $usingReferences = false;
62
    /**
63
     * @var EntityManagerInterface
64
     */
65
    private $entityManager;
66
    /**
67
     * @var bool
68
     */
69
    protected $generateCustomFixtures = false;
70
    /**
71
     * @var int
72
     */
73
    protected $numberToGenerate;
74
    /**
75
     * @var array
76
     */
77
    protected $customData;
78
79 5
    public function __construct(
80
        TestEntityGeneratorFactory $testEntityGeneratorFactory,
81
        EntitySaverFactory $saverFactory,
82
        NamespaceHelper $namespaceHelper,
83
        EntityManagerInterface $entityManager,
84
        ContainerInterface $container,
85
        ?FixtureEntitiesModifierInterface $modifier = null
86
    ) {
87 5
        $this->namespaceHelper = $namespaceHelper;
88 5
        $this->entityFqn       = $this->getEntityFqn();
89 5
        $this->saver           = $saverFactory->getSaverForEntityFqn($this->entityFqn);
90 5
        if (null !== $modifier) {
91 1
            $this->setModifier($modifier);
92
        }
93 5
        $this->testEntityGeneratorFactory = $testEntityGeneratorFactory;
94 5
        $this->container                  = $container;
95 5
        $this->assertReferencePrefixOverridden();
96 5
        $this->entityManager = $entityManager;
97 5
    }
98
99
    /**
100
     * Get the fully qualified name of the Entity we are testing,
101
     * assumes EntityNameTest as the entity class short name
102
     *
103
     * @return string
104
     */
105 5
    protected function getEntityFqn(): string
106
    {
107 5
        if (null === $this->entityFqn) {
108 5
            $this->entityFqn = $this->namespaceHelper->getEntityFqnFromFixtureFqn(static::class);
109
        }
110
111 5
        return $this->entityFqn;
112
    }
113
114
    /**
115
     * Use this method to inject your own modifier that will receive the array of generated entities and can then
116
     * update them as you see fit
117
     *
118
     * @param FixtureEntitiesModifierInterface $modifier
119
     */
120 1
    public function setModifier(FixtureEntitiesModifierInterface $modifier): void
121
    {
122 1
        $this->modifier = $modifier;
123 1
    }
124
125 5
    private function assertReferencePrefixOverridden(): void
126
    {
127 5
        if (static::REFERENCE_PREFIX === self::REFERENCE_PREFIX) {
0 ignored issues
show
introduced by
The condition static::REFERENCE_PREFIX... self::REFERENCE_PREFIX is always true.
Loading history...
128
            throw new \LogicException('You must override the REFERENCE_PREFIX constant in your Fixture');
129
        }
130 5
    }
131
132
    /**
133
     * Load data fixtures with the passed EntityManager
134
     *
135
     * @param ObjectManager $manager
136
     *
137
     * @throws \Doctrine\ORM\Mapping\MappingException
138
     * @throws \EdmondsCommerce\DoctrineStaticMeta\Exception\DoctrineStaticMetaException
139
     * @throws \ErrorException
140
     * @throws \ReflectionException
141
     */
142 4
    public function load(ObjectManager $manager)
143
    {
144 4
        if (!$manager instanceof EntityManagerInterface) {
145
            throw new \RuntimeException(
146
                'Expecting $manager to be EntityManagerInterface but got ' . \get_class($manager)
147
            );
148
        }
149 4
        $this->testEntityGenerator = $this->testEntityGeneratorFactory->createForEntityFqn($this->entityFqn, $manager);
150 4
        $this->testEntityGenerator->assertSameEntityManagerInstance($manager);
151 4
        $entities = $this->loadBulk();
152 4
        $this->validateNumberGenerated($entities);
153 4
        $this->updateGenerated($entities);
154 4
        $this->saver->saveAll($entities);
155 4
    }
156
157
    /**
158
     * This method can be used to generate ad hoc fixture with specified data. To use it pass in an array of arrays,
159
     * with each child array keyed with the properties that you want to set, e.g.
160
     * [
161
     *      [
162
     *          'propertyOne' => true,
163
     *          'propertyTwo' => DifferentEntity,
164
     *          ...
165
     *      ],
166
     *      ...
167
     * ]
168
     *
169
     * The entity will be created as normal, with Faker data used to populate each field and then the data in the array
170
     * will be used to override the properties
171
     *
172
     * @param array $customData
173
     */
174
    public function setCustomData(array $customData): void
175
    {
176
        $this->numberToGenerate       = count($customData);
177
        $this->customData             = $customData;
178
        $this->generateCustomFixtures = true;
179
    }
180
181
    /**
182
     * This method will be used to check that the number of entities generated matches the number expected. If you are
183
     * generating custom fixtures then this will check the number generated matches the number of custom array items
184
     * passed in, otherwise it will check the constant defined in the class
185
     *
186
     * @param array $entities
187
     */
188 4
    protected function validateNumberGenerated(array $entities): void
189
    {
190 4
        $expected = $this->generateCustomFixtures === true ? $this->numberToGenerate : static::BULK_AMOUNT_TO_GENERATE;
191 4
        if (count($entities) !== $expected) {
192
            throw new \RuntimeException(
193
                'generated ' . count($entities) .
194
                ' but the constant ' . get_class($this) . '::BULK_AMOUNT_TO_GENERATE is ' . $expected
195
            );
196
        }
197 4
    }
198
199
    /**
200
     * @return array|EntityInterface[]
201
     * @throws \Doctrine\ORM\Mapping\MappingException
202
     * @throws \ErrorException
203
     * @throws \ReflectionException
204
     */
205 4
    protected function loadBulk(): array
206
    {
207 4
        if ($this->generateCustomFixtures === true) {
208
            return $this->generateCustomFixtures();
209
        }
210 4
        $entities = $this->testEntityGenerator->generateEntities(
211 4
            static::BULK_AMOUNT_TO_GENERATE
212
        );
213 4
        $num      = 0;
214 4
        foreach ($entities as $generated) {
215 4
            $this->addReference(static::REFERENCE_PREFIX . $num++, $generated);
216
        }
217
218 4
        return $entities;
219
    }
220
221
    /**
222
     * This loops over the custom array and passes the data to to a function used to create and update the entity
223
     *
224
     * @return array
225
     */
226
    protected function generateCustomFixtures(): array
227
    {
228
        $customFixtures = [];
229
        for ($numberToGenerate = 0; $numberToGenerate < $this->numberToGenerate; $numberToGenerate++) {
230
            $customFixtures[] = $this->generateCustomFixture($this->customData[$numberToGenerate], $numberToGenerate);
231
        }
232
233
        return $customFixtures;
234
    }
235
236
    /**
237
     * This is used to create the custom entity. It can be overwritten if you want to use customise it further, e.g.
238
     * using the same vaule for each entity. The method is passed the array of custom data and the number, zero indexed,
239
     * of the entity being generated
240
     *
241
     * @param array $customData
242
     * @param int   $fixtureNumber
243
     * @SuppressWarnings(PHPMD.UnusedFormalParameter) - We don't need the fixture number in this method, but it may be
244
     *                                                useful if the method is overwritten
245
     *
246
     * @return EntityInterface
247
     */
248
    protected function generateCustomFixture(array $customData, int $fixtureNumber): EntityInterface
0 ignored issues
show
Unused Code introduced by
The parameter $fixtureNumber is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

248
    protected function generateCustomFixture(array $customData, /** @scrutinizer ignore-unused */ int $fixtureNumber): EntityInterface

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
249
    {
250
        return $this->testEntityGenerator->create($customData);
251
    }
252
253 4
    public function addReference($name, $object)
254
    {
255 4
        if (false === $this->usingReferences) {
256
            return;
257
        }
258 4
        parent::addReference($name, $object);
259 4
    }
260
261 4
    protected function updateGenerated(array &$entities)
262
    {
263 4
        if (null === $this->modifier) {
264 3
            return;
265
        }
266 1
        $this->modifier->modifyEntities($entities);
267 1
    }
268
269 4
    public function setReferenceRepository(\Doctrine\Common\DataFixtures\ReferenceRepository $referenceRepository)
270
    {
271 4
        $this->setUsingReferences(true);
272 4
        parent::setReferenceRepository($referenceRepository); // TODO: Change the autogenerated stub
273 4
    }
274
275
    /**
276
     * @param bool $usingReferences
277
     *
278
     * @return AbstractEntityFixtureLoader
279
     */
280 4
    public function setUsingReferences(bool $usingReferences): AbstractEntityFixtureLoader
281
    {
282 4
        $this->usingReferences = $usingReferences;
283
284 4
        return $this;
285
    }
286
287
    public function getReference($name): EntityInterface
288
    {
289
        $reference = parent::getReference($name);
290
        $this->entityManager->initializeObject($reference);
291
        if ($reference instanceof EntityInterface) {
292
            return $reference;
293
        }
294
        throw new \RuntimeException('Failed initialising refernce into Entity');
295
    }
296
297
    /**
298
     * Generally we should avoid using the container as a service locator, however for test assets it is acceptable if
299
     * really necessary
300
     *
301
     * @return ContainerInterface
302
     */
303
    protected function getContainer(): ContainerInterface
304
    {
305
        return $this->container;
306
    }
307
}
308