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 (#214)
by joseph
21:10
created

FixturesHelperTest::itUsesTheCacheTheSecondTime()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 33
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 25
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 33
rs 9.52
1
<?php declare(strict_types=1);
2
3
namespace EdmondsCommerce\DoctrineStaticMeta\Tests\Large\G\Entity\Testing\Fixtures;
4
5
use Doctrine\Common\Cache\FilesystemCache;
6
use Doctrine\Common\Collections\ArrayCollection;
7
use EdmondsCommerce\DoctrineStaticMeta\Entity\DataTransferObjects\DtoFactory;
8
use EdmondsCommerce\DoctrineStaticMeta\Entity\Factory\EntityFactoryInterface;
9
use EdmondsCommerce\DoctrineStaticMeta\Entity\Fields\Factories\UuidFactory;
10
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\DataTransferObjectInterface;
11
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\EntityInterface;
12
use EdmondsCommerce\DoctrineStaticMeta\Entity\Savers\EntitySaverFactory;
13
use EdmondsCommerce\DoctrineStaticMeta\Entity\Testing\Fixtures\AbstractEntityFixtureLoader;
14
use EdmondsCommerce\DoctrineStaticMeta\Entity\Testing\Fixtures\FixtureEntitiesModifierInterface;
15
use EdmondsCommerce\DoctrineStaticMeta\Entity\Testing\Fixtures\FixturesHelper;
16
use EdmondsCommerce\DoctrineStaticMeta\Exception\DoctrineStaticMetaException;
17
use EdmondsCommerce\DoctrineStaticMeta\Schema\Database;
18
use EdmondsCommerce\DoctrineStaticMeta\Schema\Schema;
19
use EdmondsCommerce\DoctrineStaticMeta\Tests\Assets\AbstractLargeTest;
20
use EdmondsCommerce\DoctrineStaticMeta\Tests\Assets\AbstractTest;
21
use EdmondsCommerce\DoctrineStaticMeta\Tests\Assets\TestCodeGenerator;
22
use Ramsey\Uuid\UuidInterface;
23
use ReflectionException;
24
25
/**
26
 * @covers \EdmondsCommerce\DoctrineStaticMeta\Entity\Testing\Fixtures\AbstractEntityFixtureLoader
27
 * @covers \EdmondsCommerce\DoctrineStaticMeta\Entity\Testing\Fixtures\FixturesHelper
28
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
29
 * @SuppressWarnings(PHPMD.StaticAccess)
30
 */
31
class FixturesHelperTest extends AbstractLargeTest
32
{
33
    public const WORK_DIR = AbstractTest::VAR_PATH .
34
                            self::TEST_TYPE_LARGE .
35
                            '/FixturesTest';
36
37
    private const ENTITY_WITHOUT_MODIFIER = self::TEST_ENTITIES_ROOT_NAMESPACE .
38
                                            TestCodeGenerator::TEST_ENTITY_PERSON;
39
40
    private const ENTITY_WITH_MODIFIER = self::TEST_ENTITIES_ROOT_NAMESPACE .
41
                                         TestCodeGenerator::TEST_ENTITY_PERSON;
42
43
    protected static $buildOnce = true;
44
    /**
45
     * @var FixturesHelper
46
     */
47
    private $helper;
48
49
    public function setup(): void
50
    {
51
        parent::setUp();
52
        if (false === self::$built) {
53
            $this->getTestCodeGenerator()
54
                 ->copyTo(self::WORK_DIR, self::TEST_PROJECT_ROOT_NAMESPACE);
55
//            $this->overrideCode();
56
            self::$built = true;
57
        }
58
        $this->setupCopiedWorkDirAndCreateDatabase();
59
//        $this->recreateDtos();
60
        $cacheDir = $this->copiedWorkDir . '/cache';
61
        mkdir($cacheDir, 0777, true);
62
        $this->helper = new FixturesHelper(
63
            $this->getEntityManager(),
64
            $this->container->get(Database::class),
65
            $this->container->get(Schema::class),
66
            new FilesystemCache($cacheDir),
67
            $this->container->get(EntitySaverFactory::class),
68
            $this->getNamespaceHelper(),
69
            $this->getTestEntityGeneratorFactory(),
70
            $this->container
71
        );
72
    }
73
74
    /**
75
     * @test
76
     * @large
77
     */
78
    public function itLoadsAllTheFixturesWithRandomDataByDefault(): array
79
    {
80
        $this->helper->setCacheKey(__CLASS__ . '_unmodified');
81
        $fixture = $this->getUnmodifiedFixture();
82
        $this->helper->addFixture($fixture);
83
        $this->helper->createDb();
84
        $entityFqn   = $this->getCopiedFqn(self::ENTITY_WITHOUT_MODIFIER);
85
        $actual      = $this->getRepositoryFactory()
86
                            ->getRepository($entityFqn)
87
                            ->findAll();
88
        $actualCount = count($actual);
89
        self::assertSame($fixture::BULK_AMOUNT_TO_GENERATE, $actualCount);
90
91
        return $actual;
92
    }
93
94
    private function getUnmodifiedFixture(): AbstractEntityFixtureLoader
95
    {
96
        return $this->getFixture($this->getCopiedFqn(self::ENTITY_WITHOUT_MODIFIER));
97
    }
98
99
    private function getFixture(
100
        string $entityFqn,
101
        ?FixtureEntitiesModifierInterface $modifier = null
102
    ): AbstractEntityFixtureLoader {
103
        return $this->helper->createFixtureInstanceForEntityFqn($entityFqn, $modifier);
104
    }
105
106
    /**
107
     * @test
108
     * @large
109
     * @depends itLoadsAllTheFixturesWithRandomDataByDefault
110
     *
111
     * @param array $loadedFirstTime
112
     *
113
     * @return array
114
     * @throws DoctrineStaticMetaException
115
     * @throws ReflectionException
116
     */
117
    public function itUsesTheCacheTheSecondTime(array $loadedFirstTime): array
118
    {
119
        $this->getFileSystem()
120
             ->mirror(
121
                 $this->copiedWorkDir .
122
                 '/../FixturesHelperTest_ItLoadsAllTheFixturesWithRandomDataByDefault_/cache',
123
                 $this->copiedWorkDir . '/cache'
124
             );
125
        $this->helper->setCacheKey(__CLASS__ . '_unmodified');
126
        $fixture = $this->getUnmodifiedFixture();
127
        $this->helper->addFixture($fixture);
128
        $this->helper->createDb();
129
        self::assertTrue($this->helper->isLoadedFromCache());
130
        /**
131
         * @var EntityInterface[] $loadedSecondTime
132
         */
133
        $loadedSecondTime = $this->getRepositoryFactory()
134
                                 ->getRepository($this->getCopiedFqn(self::ENTITY_WITHOUT_MODIFIER))
135
                                 ->findAll();
136
        $actualCount      = count($loadedSecondTime);
137
        $expectedCount    = count($loadedFirstTime);
138
        self::assertSame($expectedCount, $actualCount);
139
        $first  = $this->getArrayKeyedByUuid($loadedFirstTime);
140
        $second = $this->getArrayKeyedByUuid($loadedSecondTime);
141
        foreach ($second as $secondId => $actualEntity) {
142
            self::assertArrayHasKey($secondId, $first, 'Failed finding UUID ' . $secondId . ' in first Entities');
143
            $expectedEntity = $first[$secondId];
144
            $expectedText   = $expectedEntity->getString();
145
            $actualText     = $actualEntity->getString();
146
            self::assertEquals($expectedText, $actualText, 'Cached Faker data does not match');
147
        }
148
149
        return $loadedSecondTime;
150
    }
151
152
    /**
153
     * @param array $entities
154
     *
155
     * @return EntityInterface[]
156
     * @return EntityInterface[]
157
     */
158
    private function getArrayKeyedByUuid(array $entities): array
159
    {
160
        $return = [];
161
        foreach ($entities as $entity) {
162
            $return[$entity->getId()->toString()] = $entity;
163
        }
164
165
        return $return;
166
    }
167
168
    /**
169
     * @test
170
     * @large
171
     * @depends itUsesTheCacheTheSecondTime
172
     *
173
     * @param array $loadedSecondTime
174
     *
175
     * @throws DoctrineStaticMetaException
176
     * @throws ReflectionException
177
     */
178
    public function itCanBeConfiguredNotToLoadFromTheCache(array $loadedSecondTime): void
179
    {
180
        $this->getFileSystem()
181
             ->mirror(
182
                 $this->copiedWorkDir .
183
                 '/../FixturesHelperTest_ItUsesTheCacheTheSecondTime_/cache',
184
                 $this->copiedWorkDir . '/cache'
185
             );
186
        $this->helper->setCacheKey(__CLASS__ . '_unmodified');
187
        $fixture = $this->getUnmodifiedFixture();
188
        $this->helper->setLoadFromCache(false);
189
        $this->helper->addFixture($fixture);
190
        $this->helper->createDb();
191
        self::assertFalse($this->helper->isLoadedFromCache());
192
        /**
193
         * @var EntityInterface[] $loadedThirdTime
194
         */
195
        $loadedThirdTime = $this->getRepositoryFactory()
196
                                ->getRepository($this->getCopiedFqn(self::ENTITY_WITHOUT_MODIFIER))
197
                                ->findAll();
198
        $actualCount     = count($loadedThirdTime);
199
        $expectedCount   = count($loadedSecondTime);
200
        self::assertSame($expectedCount, $actualCount);
201
        $second = $this->getArrayKeyedByUuid($loadedSecondTime);
202
        foreach ($loadedThirdTime as $actualEntity) {
203
            self::assertArrayNotHasKey($actualEntity->getId()->toString(), $second);
204
        }
205
    }
206
207
    /**
208
     * @test
209
     * @large
210
     */
211
    public function itCanTakeAModifierToCustomiseTheFixtures(): void
212
    {
213
        $this->helper->setCacheKey(__CLASS__ . '_modified');
214
        $fixture = $this->getModifiedFixture();
215
        $this->helper->addFixture($fixture);
216
        $this->helper->createDb();
217
        /**
218
         * @var EntityInterface[] $actual
219
         */
220
        $actual      = $this->getRepositoryFactory()
221
                            ->getRepository($this->getCopiedFqn(self::ENTITY_WITH_MODIFIER))
222
                            ->findAll();
223
        $actualCount = count($actual);
224
        self::assertSame($fixture::BULK_AMOUNT_TO_GENERATE + 1, $actualCount);
225
        $foundStrings = [];
226
        foreach ($actual as $entity) {
227
            $foundStrings[$entity->getString()] = true;
0 ignored issues
show
Bug introduced by
The method getString() does not exist on EdmondsCommerce\Doctrine...erfaces\EntityInterface. ( Ignorable by Annotation )

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

227
            $foundStrings[$entity->/** @scrutinizer ignore-call */ getString()] = true;

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
228
        }
229
        $overwrittenString = 'This has been overridden';
230
        $createdString     = 'This has been created';
231
        self::assertArrayHasKey($overwrittenString, $foundStrings);
232
        self::assertArrayHasKey($createdString, $foundStrings);
233
    }
234
235
    private function getModifiedFixture(): AbstractEntityFixtureLoader
236
    {
237
        return $this->getFixture(
238
            $this->getCopiedFqn(self::ENTITY_WITH_MODIFIER),
239
            $this->getFixtureModifier()
240
        );
241
    }
242
243
    /**
244
     * @return FixtureEntitiesModifierInterface
245
     * @throws DoctrineStaticMetaException
246
     * @throws ReflectionException
247
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
248
     */
249
    private function getFixtureModifier(): FixtureEntitiesModifierInterface
250
    {
251
252
        return new class(
253
            $this->getCopiedFqn(self::ENTITY_WITH_MODIFIER),
254
            $this->getEntityFactory(),
255
            $this->getEntityDtoFactory(),
256
            $this->getUuidFactory(),
257
            $this->getCopiedFqn(self::TEST_ENTITIES_ROOT_NAMESPACE . TestCodeGenerator::TEST_ENTITY_EMAIL)
258
        )
259
            implements FixtureEntitiesModifierInterface
260
        {
261
            /**
262
             * @var string
263
             */
264
            protected $entityFqn;
265
            /**
266
             * @var EntityFactoryInterface
267
             */
268
            protected $factory;
269
            /**
270
             * @var array|EntityInterface[]
271
             */
272
            private $entities;
273
            /**
274
             * @var DtoFactory
275
             */
276
            private $dtoFactory;
277
            /**
278
             * @var UuidFactory
279
             */
280
            private $uuidFactory;
281
            /**
282
             * @var string
283
             */
284
            private $emailFqn;
285
286
            public function __construct(
287
                string $entityFqn,
288
                EntityFactoryInterface $factory,
289
                DtoFactory $dtoFactory,
290
                UuidFactory $uuidFactory,
291
                string $emailFqn
292
            ) {
293
                $this->entityFqn   = $entityFqn;
294
                $this->factory     = $factory;
295
                $this->dtoFactory  = $dtoFactory;
296
                $this->uuidFactory = $uuidFactory;
297
                $this->emailFqn    = $emailFqn;
298
            }
299
300
            /**
301
             * Update the entities array by reference
302
             *
303
             * @param array $entities
304
             */
305
            public function modifyEntities(array &$entities): void
306
            {
307
                $this->entities = &$entities;
308
                $this->updateFirstEntity();
309
                $this->addAnotherEntity();
310
            }
311
312
            private function updateFirstEntity(): void
313
            {
314
                $firstEntity = current($this->entities);
315
                $firstEntity->update(
316
                    new class($this->entityFqn, $firstEntity->getId())
317
                        implements DataTransferObjectInterface
318
                    {
319
                        /**
320
                         * @var string
321
                         */
322
                        private static $entityFqn;
323
                        /**
324
                         * @var UuidInterface
325
                         */
326
                        private $id;
327
328
                        public function __construct(string $entityFqn, UuidInterface $id)
329
                        {
330
                            self::$entityFqn = $entityFqn;
331
                            $this->id        = $id;
332
                        }
333
334
                        public function getString(): string
335
                        {
336
                            return 'This has been overridden';
337
                        }
338
339
                        public static function getEntityFqn(): string
340
                        {
341
                            return self::$entityFqn;
342
                        }
343
344
                        public function getId(): UuidInterface
345
                        {
346
                            return $this->id;
347
                        }
348
                    }
349
                );
350
            }
351
352
            private function addAnotherEntity(): void
353
            {
354
                $address = $this->factory->create($this->emailFqn);
355
                $entity  = $this->factory->create(
356
                    $this->entityFqn,
357
                    new class($this->entityFqn, $this->uuidFactory, $address) implements DataTransferObjectInterface
358
                    {
359
                        /**
360
                         * @var string
361
                         */
362
                        private static $entityFqn;
363
                        /**
364
                         * @var UuidInterface
365
                         */
366
                        private $id;
367
                        /**
368
                         * @var EntityInterface
369
                         */
370
                        private $email;
371
372
                        public function __construct(string $entityFqn, UuidFactory $factory, EntityInterface $email)
373
                        {
374
                            self::$entityFqn = $entityFqn;
375
                            $this->id        = $factory->getOrderedTimeUuid();
376
                            $this->email     = $email;
377
                        }
378
379
                        public function getString(): string
380
                        {
381
                            return 'This has been created';
382
                        }
383
384
                        public static function getEntityFqn(): string
385
                        {
386
                            return self::$entityFqn;
387
                        }
388
389
                        public function getId(): UuidInterface
390
                        {
391
                            return $this->id;
392
                        }
393
394
                        public function getAttributesEmails(): ArrayCollection
395
                        {
396
                            $collection = new ArrayCollection();
397
                            $collection->add($this->email);
398
399
                            return $collection;
400
                        }
401
                    }
402
                );
403
404
                $this->entities[] = $entity;
405
            }
406
        };
407
    }
408
}
409