-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathDoctrine2.php
More file actions
1074 lines (980 loc) · 36.5 KB
/
Doctrine2.php
File metadata and controls
1074 lines (980 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Codeception\Module;
use Codeception\Exception\ModuleConfigException;
use Codeception\Exception\ModuleException;
use Codeception\Exception\ModuleRequireException;
use Codeception\Lib\Interfaces\DataMapper;
use Codeception\Lib\Interfaces\DependsOnModule;
use Codeception\Lib\Interfaces\DoctrineProvider;
use Codeception\Module as CodeceptionModule;
use Codeception\Stub;
use Codeception\TestInterface;
use Codeception\Util\ReflectionPropertyAccessor;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Expr\Expression;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\Loader;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Exception;
use InvalidArgumentException;
use PDOException;
use ReflectionClass;
use ReflectionException;
use function array_merge;
use function get_class;
use function gettype;
use function is_array;
use function is_object;
use function is_string;
use function spl_object_id;
use function sprintf;
use function var_export;
/**
* Access the database using [Doctrine ORM](https://docs.doctrine-project.org/projects/doctrine-orm/en/latest/).
*
* When used with Symfony or Zend Framework 2, Doctrine's Entity Manager is automatically retrieved from Service Locator.
* Set up your `functional.suite.yml` like this:
*
* ```yaml
* modules:
* enabled:
* - Symfony # 'ZF2' or 'Symfony'
* - Doctrine2:
* depends: Symfony # Tells Doctrine to fetch the Entity Manager through Symfony
* cleanup: true # All doctrine queries will be wrapped in a transaction, which will be rolled back at the end of each test
* ```
*
* If you don't provide a `depends` key, you need to specify a callback function to retrieve the Entity Manager:
*
* ```yaml
* modules:
* enabled:
* - Doctrine2:
* connection_callback: ['MyDb', 'createEntityManager'] # Call the static method `MyDb::createEntityManager()` to get the Entity Manager
* ```
*
* By default, the module will wrap everything into a transaction for each test and roll it back afterwards
* (this is controlled by the `cleanup` setting).
* By doing this, tests will run much faster and will be isolated from each other.
*
* To use the Doctrine2 Module in acceptance tests, set up your `acceptance.suite.yml` like this:
*
* ```yaml
* modules:
* enabled:
* - Symfony:
* part: SERVICES
* - Doctrine2:
* depends: Symfony
* ```
*
* You cannot use `cleanup: true` in an acceptance test, since Codeception and your app (i.e. browser) are using two
* different connections to the database, so Codeception can't wrap changes made by the app into a transaction.
*
* Set the SQL statement that Doctrine fixtures ([`doctrine/data-fixtures`](https://github.com/doctrine/data-fixtures))
* are using to purge the database tables:
* ```yaml
* modules:
* enabled:
* - Doctrine2:
* purge_mode: 1 # 1: DELETE (=default), 2: TRUNCATE
* ```
*
* ## Grabbing Entities with Symfony
*
* For Symfony users, the recommended way to query for entities is not to use this module's `grab...()` methods, but rather
* "inject" Doctrine's repository:
*
* ```php
* public function _before(FunctionalTester $I): void
* {
* $this->fooRepository = $I->grabService(FooRepository::class);
* }
* ```
*
* Now you have access to all your familiar repository methods in your tests, e.g.:
*
* ```php
* $greenFoo = $this->fooRepository->findOneBy(['color' => 'green']);
* ```
*
* ## Public Properties
*
* * `em` - Entity Manager
*
* ## Doctrine `Criteria` as query parameters
*
* Every method that expects some query parameters (`see...()`,
* `dontSee...()`, `grab...()`) also accepts an instance of
* [\Doctrine\Common\Collections\Criteria](https://www.doctrine-project.org/projects/doctrine-collections/en/stable/expressions.html)
* for more flexibility, e.g.:
*
* ```php
* $I->seeInRepository(User::class, [
* 'name' => 'John',
* Criteria::create()->where(
* Criteria::expr()->endsWith('email', '@domain.com')
* ),
* ]);
* ```
*
* If criteria is just a `->where(...)` construct, you can pass just expression without criteria wrapper:
*
* ```php
* $I->seeInRepository(User::class, [
* 'name' => 'John',
* Criteria::expr()->endsWith('email', '@domain.com'),
* ]);
* ```
*
* Criteria can be used not only to filter data, but also to change the order of results:
*
* ```php
* $I->grabEntitiesFromRepository('User', [
* 'status' => 'active',
* Criteria::create()->orderBy(['name' => 'asc']),
* ]);
* ```
*
* Note that key is ignored, because actual field name is part of criteria and/or expression.
*/
class Doctrine2 extends CodeceptionModule implements DependsOnModule, DataMapper
{
private ?DoctrineProvider $dependentModule = null;
/**
* @var array<string, mixed>
*/
protected array $config = [
'cleanup' => true,
'connection_callback' => false,
'depends' => null,
'purge_mode' => 1, // ORMPurger::PURGE_MODE_DELETE
];
protected string $dependencyMessage = <<<EOF
Provide connection_callback function to establish database connection and get Entity Manager:
modules:
enabled:
- Doctrine2:
connection_callback: [My\ConnectionClass, getEntityManager]
Or set a dependent module, which can be either Symfony or ZF2 to get EM from service locator:
modules:
enabled:
- Doctrine2:
depends: Symfony
EOF;
public ?EntityManagerInterface $em = null;
public function _depends(): array
{
if ($this->config['connection_callback']) {
return [];
}
return [DoctrineProvider::class => $this->dependencyMessage];
}
public function _inject(DoctrineProvider $dependentModule = null): void
{
$this->dependentModule = $dependentModule;
}
/**
* @param array<mixed> $settings
*
* @throws ModuleConfigException
*/
public function _beforeSuite($settings = []): void
{
$this->retrieveEntityManager();
}
public function _before(TestInterface $test): void
{
$this->cleanupEntityManager();
}
public function onReconfigure(): void
{
if (!$this->em instanceof EntityManagerInterface) {
return;
}
if ($this->config['cleanup'] && $this->em->getConnection()->isTransactionActive()) {
try {
$this->em->getConnection()->rollback();
$this->debugSection('Database', 'Transaction cancelled; all changes reverted.');
} catch (PDOException $e) {
}
}
$this->clean();
$this->em->getConnection()->close();
$this->cleanupEntityManager();
}
protected function retrieveEntityManager(): void
{
if ($this->dependentModule) {
$this->em = $this->dependentModule->_getEntityManager();
} else {
if (is_callable($this->config['connection_callback'])) {
$this->em = call_user_func($this->config['connection_callback']);
}
}
if (!$this->em) {
throw new ModuleConfigException(
__CLASS__,
"EntityManager can't be obtained.\n \n"
. "Please specify either `connection_callback` config option\n"
. "with callable which will return instance of EntityManager or\n"
. "pass a dependent module which are Symfony or ZF2\n"
. "to connect to Doctrine using Dependency Injection Container"
);
}
if (!($this->em instanceof EntityManagerInterface)) {
throw new ModuleConfigException(
__CLASS__,
"Connection object is not an instance of \\Doctrine\\ORM\\EntityManagerInterface.\n"
. "Use `connection_callback` or dependent framework modules to specify one"
);
}
$this->em->getConnection()->connect();
}
/**
* @return void
*/
public function _after(TestInterface $test)
{
if (!$this->em instanceof EntityManagerInterface) {
return;
}
if ($this->config['cleanup'] && $this->em->getConnection()->isTransactionActive()) {
try {
while ($this->em->getConnection()->getTransactionNestingLevel() > 0) {
$this->em->getConnection()->rollback();
}
$this->debugSection('Database', 'Transaction cancelled; all changes reverted.');
} catch (PDOException $e) {
}
}
$this->clean();
$this->em->getConnection()->close();
}
protected function clean(): void
{
$em = $this->em;
$reflectedEm = new ReflectionClass($em);
if ($reflectedEm->hasProperty('repositories')) {
$property = $reflectedEm->getProperty('repositories');
$property->setAccessible(true);
$property->setValue($em, []);
}
$this->em->clear();
}
/**
* Performs $em->flush();
*/
public function flushToDatabase(): void
{
$this->em->flush();
}
/**
* Performs $em->refresh() on every passed entity:
*
* ``` php
* $I->refreshEntities($user);
* $I->refreshEntities([$post1, $post2, $post3]]);
* ```
*
* This can useful in acceptance tests where entity can become invalid due to
* external (relative to entity manager used in tests) changes.
*
* @param object|object[] $entities
*/
public function refreshEntities($entities): void
{
if (!is_array($entities)) {
$entities = [$entities];
}
foreach ($entities as $entity) {
$this->em->refresh($entity);
}
}
/**
* Performs $em->clear():
*
* ``` php
* $I->clearEntityManager();
* ```
*/
public function clearEntityManager(): void
{
$this->em->clear();
}
/**
* Mocks the repository.
*
* With this action you can redefine any method of any repository.
* Please, note: this fake repositories will be accessible through entity manager till the end of test.
*
* Example:
*
* ``` php
* <?php
*
* $I->haveFakeRepository(User::class, ['findByUsername' => function($username) { return null; }]);
*
* ```
*
* This creates a stub class for Entity\User repository with redefined method findByUsername,
* which will always return the NULL value.
*
* @param class-string $className
* @param array<string, callable> $methods
*/
public function haveFakeRepository(string $className, array $methods = []): void
{
$em = $this->em;
$metadata = $em->getMetadataFactory()->getMetadataFor($className);
$customRepositoryClassName = $metadata->customRepositoryClassName;
if (!$customRepositoryClassName) {
$customRepositoryClassName = '\Doctrine\ORM\EntityRepository';
}
$mock = Stub::make(
$customRepositoryClassName,
array_merge(
[
'_entityName' => $metadata->name,
'_em' => $em,
'_class' => $metadata
],
$methods
)
);
$em->clear();
$reflectedEm = new ReflectionClass($em);
if ($reflectedEm->hasProperty('repositories')) {
//Support doctrine versions before 2.4.0
$property = $reflectedEm->getProperty('repositories');
$property->setAccessible(true);
$property->setValue($em, array_merge($property->getValue($em), [$className => $mock]));
} elseif ($reflectedEm->hasProperty('repositoryFactory')) {
//For doctrine 2.4.0+ versions
$repositoryFactoryProperty = $reflectedEm->getProperty('repositoryFactory');
$repositoryFactoryProperty->setAccessible(true);
$repositoryFactory = $repositoryFactoryProperty->getValue($em);
$reflectedRepositoryFactory = new ReflectionClass($repositoryFactory);
if ($reflectedRepositoryFactory->hasProperty('repositoryList')) {
$repositoryListProperty = $reflectedRepositoryFactory->getProperty('repositoryList');
$repositoryListProperty->setAccessible(true);
$repositoryHash = $em->getClassMetadata($className)->getName() . spl_object_id($em);
$repositoryListProperty->setValue(
$repositoryFactory,
[$repositoryHash => $mock]
);
$repositoryFactoryProperty->setValue($em, $repositoryFactory);
} else {
$this->debugSection(
'Warning',
'Repository can\'t be mocked, the EventManager\'s repositoryFactory doesn\'t have "repositoryList" property'
);
}
} else {
$this->debugSection(
'Warning',
'Repository can\'t be mocked, the EventManager class doesn\'t have "repositoryFactory" or "repositories" property'
);
}
}
/**
* Persists a record into the repository.
* This method creates an entity, and sets its properties directly (via reflection).
* Setters of the entity won't be executed, but you can create almost any entity and save it to the database.
* If the entity has a constructor, for optional parameters the default value will be used and for non-optional parameters the given fields (with a matching name) will be passed when calling the constructor before the properties get set directly (via reflection).
*
* Returns the primary key of the newly created entity. The primary key value is extracted using Reflection API.
* If the primary key is composite, an array of values is returned.
*
* ```php
* $I->haveInRepository(User::class, ['name' => 'davert']);
* ```
*
* This method also accepts instances as first argument, which is useful when the entity constructor
* has some arguments:
*
* ```php
* $I->haveInRepository(new User($arg), ['name' => 'davert']);
* ```
*
* Alternatively, constructor arguments can be passed by name. Given User constructor signature is `__constructor($arg)`, the example above could be rewritten like this:
*
* ```php
* $I->haveInRepository(User::class, ['arg' => $arg, 'name' => 'davert']);
* ```
*
* If the entity has relations, they can be populated too. In case of
* [OneToMany](https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-bidirectional)
* the following format is expected:
*
* ```php
* $I->haveInRepository(User::class, [
* 'name' => 'davert',
* 'posts' => [
* ['title' => 'Post 1'],
* ['title' => 'Post 2'],
* ],
* ]);
* ```
*
* For [ManyToOne](https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#many-to-one-unidirectional)
* the format is slightly different:
*
* ```php
* $I->haveInRepository(User::class, [
* 'name' => 'davert',
* 'post' => [
* 'title' => 'Post 1',
* ],
* ]);
* ```
*
* This works recursively, so you can create deep structures in a single call.
*
* Note that `$em->persist()`, `$em->refresh()`, and `$em->flush()` are called every time.
*
* @template T of object
* @param class-string<T>|T $classNameOrInstance
* @param array $data
* @return mixed
*/
public function haveInRepository($classNameOrInstance, array $data = [])
{
// Here we'll have array of all instances (including any relations) created:
$instances = [];
// Create and/or populate main instance and gather all created relations:
if (is_object($classNameOrInstance)) {
$instance = $this->populateEntity($classNameOrInstance, $data, $instances);
} elseif (is_string($classNameOrInstance)) {
$instance = $this->instantiateAndPopulateEntity($classNameOrInstance, $data, $instances);
} else {
throw new InvalidArgumentException(sprintf('Doctrine2::haveInRepository expects a class name or instance as first argument, got "%s" instead', gettype($classNameOrInstance)));
}
// Flush all changes to database and then refresh all entities. We need this because
// currently all assignments are done via Reflection API without using setters, which means
// all OneToMany relations won't get set properly as real setter method would use some
// Collection operation.
$this->em->flush();
$this->refreshEntities($instances);
$pk = $this->extractPrimaryKey($instance);
$this->debugEntityCreation($instance, $pk);
return $pk;
}
/**
* @template T of object
* @param class-string<T> $className
* @param array $data
* @param list<object> $instances
* @return T
* @throws ReflectionException
*/
private function instantiateAndPopulateEntity(string $className, array $data, array &$instances)
{
$rpa = new ReflectionPropertyAccessor();
[$scalars, $relations] = $this->splitScalarsAndRelations($className, $data);
// Pass relations that are already objects to the constructor, too
$properties = array_merge(
$scalars,
array_filter($relations, fn($relation) => is_object($relation))
);
/** @var T $instance */
$instance = $rpa->createWithProperties($className, $properties);
$this->populateEntity($instance, $data, $instances);
return $instance;
}
/**
* @template T of object
* @param T $instance
* @param array $data
* @param list<object> $instances
* @return T
* @throws ReflectionException
*/
private function populateEntity($instance, array $data, array &$instances)
{
$rpa = new ReflectionPropertyAccessor();
$className = get_class($instance);
$instances[] = $instance;
[$scalars, $relations] = $this->splitScalarsAndRelations($className, $data);
$rpa->setProperties(
$instance,
array_merge(
$scalars,
$this->instantiateRelations($className, $instance, $relations, $instances)
)
);
$this->populateEmbeddables($instance, $data);
$this->em->persist($instance);
return $instance;
}
/**
* @param class-string $className
* @param array $data
* @return array{0: array, 1: array}
*/
private function splitScalarsAndRelations(string $className, array $data): array
{
$scalars = [];
$relations = [];
$metadata = $this->em->getClassMetadata($className);
foreach ($data as $field => $value) {
if ($metadata->hasAssociation($field)) {
$relations[$field] = $value;
} else {
$scalars[$field] = $value;
}
}
return [$scalars, $relations];
}
/**
* @param class-string $className
* @param object $master
* @param array $data
* @param list<object> $instances
* @return array
*/
private function instantiateRelations(string $className, $master, array $data, array &$instances): array
{
$metadata = $this->em->getClassMetadata($className);
foreach ($data as $field => $value) {
if (is_array($value) && $metadata->hasAssociation($field)) {
unset($data[$field]);
if ($metadata->isCollectionValuedAssociation($field)) {
foreach ($value as $subvalue) {
if (!is_array($subvalue)) {
throw new InvalidArgumentException('Association "' . $field . '" of entity "' . $className . '" requires array as input, got "' . gettype($subvalue) . '" instead"');
}
$instance = $this->instantiateAndPopulateEntity(
$metadata->getAssociationTargetClass($field),
array_merge($subvalue, [
$metadata->getAssociationMappedByTargetField($field) => $master,
]),
$instances
);
$instances[] = $instance;
}
} else {
$instance = $this->instantiateAndPopulateEntity(
$metadata->getAssociationTargetClass($field),
$value,
$instances
);
$instances[] = $instance;
$data[$field] = $instance;
}
}
}
return $data;
}
/**
* @param object $instance
* @return array|mixed
* @throws ReflectionException
*/
private function extractPrimaryKey(object $instance)
{
$className = get_class($instance);
$metadata = $this->em->getClassMetadata($className);
$rpa = new ReflectionPropertyAccessor();
if ($metadata->isIdentifierComposite) {
$pk = [];
foreach ($metadata->identifier as $field) {
$pk[] = $rpa->getProperty($instance, $field);
}
} else {
$pk = $rpa->getProperty($instance, $metadata->identifier[0]);
}
return $pk;
}
/**
* Loads fixtures. Fixture can be specified as a fully qualified class name,
* an instance, or an array of class names/instances.
*
* ```php
* <?php
* $I->loadFixtures(AppFixtures::class);
* $I->loadFixtures([AppFixtures1::class, AppFixtures2::class]);
* $I->loadFixtures(new AppFixtures);
* ```
*
* By default fixtures are loaded in 'append' mode. To replace all
* data in database, use `false` as second parameter:
*
* ```php
* <?php
* $I->loadFixtures(AppFixtures::class, false);
* ```
*
* This method requires [`doctrine/data-fixtures`](https://github.com/doctrine/data-fixtures) to be installed.
*
* @param class-string<FixtureInterface>|class-string<FixtureInterface>[]|list<FixtureInterface> $fixtures
* @param bool $append
* @throws ModuleException
* @throws ModuleRequireException
*/
public function loadFixtures($fixtures, bool $append = true): void
{
if (!class_exists(Loader::class)
|| !class_exists(ORMPurger::class)
|| !class_exists(ORMExecutor::class)) {
throw new ModuleRequireException(
__CLASS__,
'Doctrine fixtures support in unavailable.\nPlease, install doctrine/data-fixtures.'
);
}
if (!is_array($fixtures)) {
$fixtures = [$fixtures];
}
$loader = new Loader();
foreach ($fixtures as $fixture) {
if (is_string($fixture)) {
if (!class_exists($fixture)) {
throw new ModuleException(
__CLASS__,
sprintf(
'Fixture class "%s" does not exist',
$fixture
)
);
}
if (!is_a($fixture, FixtureInterface::class, true)) {
throw new ModuleException(
__CLASS__,
sprintf(
'Fixture class "%s" does not inherit from "%s"',
$fixture,
FixtureInterface::class
)
);
}
try {
$fixtureInstance = new $fixture();
} catch (Exception $exception) { // @phpstan-ignore-line https://github.com/phpstan/phpstan/issues/6574
throw new ModuleException(
__CLASS__,
sprintf(
'Fixture class "%s" could not be loaded, got %s%s',
$fixture,
get_class($exception),
empty($exception->getMessage()) ? '' : ': ' . $exception->getMessage()
)
);
}
} elseif (is_object($fixture)) {
if (!$fixture instanceof FixtureInterface) {
throw new ModuleException(
__CLASS__,
sprintf(
'Fixture "%s" does not inherit from "%s"',
get_class($fixture),
FixtureInterface::class
)
);
}
$fixtureInstance = $fixture;
} else {
throw new ModuleException(
__CLASS__,
sprintf(
'Fixture is expected to be an instance or class name, inherited from "%s"; got "%s" instead',
FixtureInterface::class,
gettype($fixture)
)
);
}
try {
$loader->addFixture($fixtureInstance);
} catch (Exception $exception) {
throw new ModuleException(
__CLASS__,
sprintf(
'Fixture class "%s" could not be loaded, got %s%s',
get_class($fixtureInstance),
get_class($exception),
empty($exception->getMessage()) ? '' : ': ' . $exception->getMessage()
)
);
}
}
try {
$purger = new ORMPurger($this->em);
$purger->setPurgeMode($this->config['purge_mode']);
$executor = new ORMExecutor($this->em, $purger);
$executor->execute($loader->getFixtures(), $append);
} catch (Exception $exception) {
throw new ModuleException(
__CLASS__,
sprintf(
'Fixtures could not be loaded, got %s%s',
get_class($exception),
empty($exception->getMessage()) ? '' : ': ' . $exception->getMessage()
)
);
}
}
/**
* Entity can have embeddable as a field, in which case $data argument of persistEntity() and haveInRepository()
* could contain keys like {field}.{subField}, where {field} is name of entity's embeddable field, and {subField}
* is embeddable's field.
*
* This method checks if entity has embeddables, and if data have keys as described above, and then uses
* Reflection API to set values.
*
* See https://www.doctrine-project.org/projects/doctrine-orm/en/current/tutorials/embeddables.html for
* details about this Doctrine feature.
*
* @param object $entityObject
* @param array $data
*
* @return void
* @throws ReflectionException
*/
private function populateEmbeddables(object $entityObject, array $data): void
{
$rpa = new ReflectionPropertyAccessor();
$metadata = $this->em->getClassMetadata(get_class($entityObject));
foreach (array_keys($metadata->embeddedClasses) as $embeddedField) {
$embeddedData = [];
foreach ($data as $entityField => $value) {
$parts = explode('.', $entityField, 2);
if (count($parts) === 2 && $parts[0] === $embeddedField) {
$embeddedData[$parts[1]] = $value;
}
}
if ($embeddedData !== []) {
$rpa->setProperties($rpa->getProperty($entityObject, $embeddedField), $embeddedData);
}
}
}
/**
* Flushes changes to database, and executes a query with parameters defined in an array.
* You can use entity associations to build complex queries.
*
* Example:
*
* ``` php
* <?php
* $I->seeInRepository(User::class, ['name' => 'davert']);
* $I->seeInRepository(User::class, ['name' => 'davert', 'Company' => ['name' => 'Codegyre']]);
* $I->seeInRepository(Client::class, ['User' => ['Company' => ['name' => 'Codegyre']]]);
* ```
*
* Fails if record for given criteria can\'t be found,
*
* @param class-string $entity
* @param array $params
* @return void
*/
public function seeInRepository(string $entity, array $params = []): void
{
$res = $this->proceedSeeInRepository($entity, $params);
$this->assert($res);
}
/**
* Flushes changes to database and performs `findOneBy()` call for current repository.
*
* @param class-string $entity
* @param array $params
* @return void
*/
public function dontSeeInRepository(string $entity, array $params = []): void
{
$res = $this->proceedSeeInRepository($entity, $params);
$this->assertNot($res);
}
/**
* @param class-string $entity
* @param array $params
*
* @return array{0: 'True', 1: bool, 2: non-empty-string}
*/
protected function proceedSeeInRepository(string $entity, array $params = []): array
{
// we need to store to database...
$this->em->flush();
$qb = $this->em->getRepository($entity)->createQueryBuilder('s');
$this->buildAssociationQuery($qb, $entity, 's', $params);
$this->debug($qb->getDQL());
$res = $qb->getQuery()->getArrayResult();
return ['True', (count($res) > 0), "$entity with " . $qb->getDQL()];
}
/**
* Selects field value from repository.
* It builds a query based on an array of parameters.
* You can use entity associations to build complex queries.
* For Symfony users, it's recommended to [use the entity's repository instead](#Grabbing-Entities-with-Symfony)
*
* Example:
*
* ``` php
* <?php
* $email = $I->grabFromRepository(User::class, 'email', ['name' => 'davert']);
* ```
*
* @param class-string $entity
* @param string $field
* @param array $params
* @return mixed
*/
public function grabFromRepository(string $entity, string $field, array $params = [])
{
// we need to store to database...
$this->em->flush();
$qb = $this->em->getRepository($entity)->createQueryBuilder('s');
$qb->select('s.' . $field);
$this->buildAssociationQuery($qb, $entity, 's', $params);
$this->debug($qb->getDQL());
return $qb->getQuery()->getSingleScalarResult();
}
/**
* Selects entities from repository.
* It builds a query based on an array of parameters.
* You can use entity associations to build complex queries.
* For Symfony users, it's recommended to [use the entity's repository instead](#Grabbing-Entities-with-Symfony)
*
* Example:
*
* ``` php
* <?php
* $users = $I->grabEntitiesFromRepository(User::class, ['name' => 'davert']);
* ```
*
* @template T of object
* @param class-string<T> $entity
* @param array $params . For `IS NULL`, use `['field' => null]`
* @return list<T>
*/
public function grabEntitiesFromRepository(string $entity, array $params = []): array
{
// we need to store to database...
$this->em->flush();
$qb = $this->em->getRepository($entity)->createQueryBuilder('s');
$qb->select('s');
$this->buildAssociationQuery($qb, $entity, 's', $params);
$this->debug($qb->getDQL());
return $qb->getQuery()->getResult();
}
/**
* Selects a single entity from repository.
* It builds a query based on an array of parameters.
* You can use entity associations to build complex queries.
* For Symfony users, it's recommended to [use the entity's repository instead](#Grabbing-Entities-with-Symfony)
*
* Example:
*
* ``` php
* <?php
* $user = $I->grabEntityFromRepository(User::class, ['id' => '1234']);
* ```
*
* @template T of object
* @param class-string<T> $entity
* @param array $params . For `IS NULL`, use `['field' => null]`
* @return T
* @version 1.1
*/
public function grabEntityFromRepository(string $entity, array $params = [])
{
// we need to store to database...
$this->em->flush();
$qb = $this->em->getRepository($entity)->createQueryBuilder('s');
$qb->select('s');
$this->buildAssociationQuery($qb, $entity, 's', $params);
$this->debug($qb->getDQL());
return $qb->getQuery()->getSingleResult();
}
protected function buildAssociationQuery(QueryBuilder $qb, string $assoc, string $alias, array $params): void
{
$paramIndex = 0;
$this->_buildAssociationQuery($qb, $assoc, $alias, $params, $paramIndex);
}
protected function _buildAssociationQuery(QueryBuilder $qb, string $assoc, string $alias, array $params, int &$paramIndex): void
{
$data = $this->em->getClassMetadata($assoc);
foreach ($params as $key => $val) {
if ($data->associationMappings !== null && array_key_exists($key, $data->associationMappings)) {
$map = $data->associationMappings[$key];
if (is_array($val)) {
$qb->innerJoin("$alias.$key", "{$alias}__$key");
$this->_buildAssociationQuery($qb, $map['targetEntity'], "{$alias}__$key", $val, $paramIndex);
continue;
}
}
if ($val === null) {
$qb->andWhere("$alias.$key IS NULL");
} elseif ($val instanceof Criteria) {
$qb->addCriteria($val);
} elseif ($val instanceof Expression) {
$qb->addCriteria(Criteria::create()->where($val));
} else {
$qb->andWhere(sprintf('%s.%s = ?%s', $alias, $key, $paramIndex));
$qb->setParameter($paramIndex, $val);
++$paramIndex;