-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
UnitOfWorkTest.php
1238 lines (1004 loc) · 41.9 KB
/
UnitOfWorkTest.php
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 Doctrine\Tests\ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\Deprecations\PHPUnit\VerifyDeprecations;
use Doctrine\ORM\EntityNotFoundException;
use Doctrine\ORM\Events;
use Doctrine\ORM\Exception\EntityIdentityCollisionException;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping\Version;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMInvalidArgumentException;
use Doctrine\ORM\UnitOfWork;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Doctrine\Persistence\NotifyPropertyChanged;
use Doctrine\Persistence\PropertyChangedListener;
use Doctrine\Tests\Mocks\ConnectionMock;
use Doctrine\Tests\Mocks\EntityManagerMock;
use Doctrine\Tests\Mocks\EntityPersisterMock;
use Doctrine\Tests\Mocks\UnitOfWorkMock;
use Doctrine\Tests\Models\CMS\CmsGroup;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\Forum\ForumAvatar;
use Doctrine\Tests\Models\Forum\ForumUser;
use Doctrine\Tests\Models\GeoNames\City;
use Doctrine\Tests\Models\GeoNames\Country;
use Doctrine\Tests\OrmTestCase;
use Doctrine\Tests\PHPUnitCompatibility\MockBuilderCompatibilityTools;
use PHPUnit\Framework\MockObject\MockObject;
use stdClass;
use function assert;
use function count;
use function gc_collect_cycles;
use function get_class;
use function method_exists;
use function random_int;
use function uniqid;
/**
* UnitOfWork tests.
*/
class UnitOfWorkTest extends OrmTestCase
{
use MockBuilderCompatibilityTools;
use VerifyDeprecations;
/**
* SUT
*
* @var UnitOfWorkMock
*/
private $_unitOfWork;
/**
* Provides a sequence mock to the UnitOfWork
*
* @var ConnectionMock&MockObject
*/
private $_connectionMock;
/**
* The EntityManager mock that provides the mock persisters
*
* @var EntityManagerMock
*/
private $_emMock;
/** @var EventManager&MockObject */
private $eventManager;
protected function setUp(): void
{
parent::setUp();
$platform = $this->createMock(AbstractPlatform::class);
$platform->method('supportsIdentityColumns')
->willReturn(true);
if (method_exists($platform, 'getSQLResultCasing')) {
$platform->method('getSQLResultCasing')
->willReturnCallback(static function (string $column): string {
return $column;
});
}
$driverStatement = $this->createMock(Driver\Statement::class);
if (method_exists($driverStatement, 'rowCount')) {
$driverStatement->method('rowCount')
->willReturn(0);
}
$driverConnection = $this->createMock(Driver\Connection::class);
$driverConnection->method('prepare')
->willReturn($driverStatement);
$driverConnection->method('lastInsertId')
->willReturnOnConsecutiveCalls(1, 2, 3, 4, 5, 6);
$driver = $this->createMock(Driver::class);
$driver->method('getDatabasePlatform')
->willReturn($platform);
$driver->method('connect')
->willReturn($driverConnection);
$this->eventManager = $this->getMockBuilder(EventManager::class)->getMock();
$this->_connectionMock = new Connection([], $driver, null, $this->eventManager);
$this->_emMock = new EntityManagerMock($this->_connectionMock);
// SUT
$this->_unitOfWork = new UnitOfWorkMock($this->_emMock);
$this->_emMock->setUnitOfWork($this->_unitOfWork);
}
public function testRegisterRemovedOnNewEntityIsIgnored(): void
{
$user = new ForumUser();
$user->username = 'romanb';
self::assertFalse($this->_unitOfWork->isScheduledForDelete($user));
$this->_unitOfWork->scheduleForDelete($user);
self::assertFalse($this->_unitOfWork->isScheduledForDelete($user));
}
/* Operational tests */
public function testSavingSingleEntityWithIdentityColumnForcesInsert(): void
{
// Setup fake persister and id generator for identity generation
$userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class));
$this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister);
$userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
// Test
$user = new ForumUser();
$user->username = 'romanb';
$this->_unitOfWork->persist($user);
// Check
self::assertCount(0, $userPersister->getInserts());
self::assertCount(0, $userPersister->getUpdates());
self::assertCount(0, $userPersister->getDeletes());
self::assertFalse($this->_unitOfWork->isInIdentityMap($user));
// should no longer be scheduled for insert
self::assertTrue($this->_unitOfWork->isScheduledForInsert($user));
// Now lets check whether a subsequent commit() does anything
$userPersister->reset();
// Test
$this->_unitOfWork->commit();
// Check.
self::assertCount(1, $userPersister->getInserts());
self::assertCount(0, $userPersister->getUpdates());
self::assertCount(0, $userPersister->getDeletes());
// should have an id
self::assertIsNumeric($user->id);
}
/**
* Tests a scenario where a save() operation is cascaded from a ForumUser
* to its associated ForumAvatar, both entities using IDENTITY id generation.
*/
public function testCascadedIdentityColumnInsert(): void
{
// Setup fake persister and id generator for identity generation
//ForumUser
$userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class));
$this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister);
$userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
// ForumAvatar
$avatarPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumAvatar::class));
$this->_unitOfWork->setEntityPersister(ForumAvatar::class, $avatarPersister);
$avatarPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
// Test
$user = new ForumUser();
$user->username = 'romanb';
$avatar = new ForumAvatar();
$user->avatar = $avatar;
$this->_unitOfWork->persist($user); // save cascaded to avatar
$this->_unitOfWork->commit();
self::assertIsNumeric($user->id);
self::assertIsNumeric($avatar->id);
self::assertCount(1, $userPersister->getInserts());
self::assertCount(0, $userPersister->getUpdates());
self::assertCount(0, $userPersister->getDeletes());
self::assertCount(1, $avatarPersister->getInserts());
self::assertCount(0, $avatarPersister->getUpdates());
self::assertCount(0, $avatarPersister->getDeletes());
}
public function testChangeTrackingNotify(): void
{
$persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(NotifyChangedEntity::class));
$this->_unitOfWork->setEntityPersister(NotifyChangedEntity::class, $persister);
$itemPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(NotifyChangedRelatedItem::class));
$this->_unitOfWork->setEntityPersister(NotifyChangedRelatedItem::class, $itemPersister);
$entity = new NotifyChangedEntity();
$entity->setData('thedata');
$this->_unitOfWork->persist($entity);
$this->_unitOfWork->commit();
self::assertCount(1, $persister->getInserts());
$persister->reset();
self::assertTrue($this->_unitOfWork->isInIdentityMap($entity));
$entity->setData('newdata');
$entity->setTransient('newtransientvalue');
self::assertTrue($this->_unitOfWork->isScheduledForDirtyCheck($entity));
self::assertEquals(['data' => ['thedata', 'newdata']], $this->_unitOfWork->getEntityChangeSet($entity));
$item = new NotifyChangedRelatedItem();
$entity->getItems()->add($item);
$item->setOwner($entity);
$this->_unitOfWork->persist($item);
$this->_unitOfWork->commit();
self::assertCount(1, $itemPersister->getInserts());
$persister->reset();
$itemPersister->reset();
$entity->getItems()->removeElement($item);
$item->setOwner(null);
self::assertTrue($entity->getItems()->isDirty());
$this->_unitOfWork->commit();
$updates = $itemPersister->getUpdates();
self::assertCount(1, $updates);
self::assertSame($updates[0], $item);
}
public function testChangeTrackingNotifyIndividualCommit(): void
{
$persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\NotifyChangedEntity'));
$this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedEntity', $persister);
$itemPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\NotifyChangedRelatedItem'));
$this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedRelatedItem', $itemPersister);
$entity = new NotifyChangedEntity();
$entity->setData('thedata');
$entity2 = new NotifyChangedEntity();
$entity2->setData('thedata');
$this->_unitOfWork->persist($entity);
$this->_unitOfWork->persist($entity2);
$this->expectDeprecationWithIdentifier('https://github.com/doctrine/orm/issues/8459');
$this->_unitOfWork->commit($entity);
$this->_unitOfWork->commit();
self::assertEquals(2, count($persister->getInserts()));
$persister->reset();
self::assertTrue($this->_unitOfWork->isInIdentityMap($entity2));
$entity->setData('newdata');
$entity2->setData('newdata');
$this->_unitOfWork->commit($entity);
self::assertTrue($this->_unitOfWork->isScheduledForDirtyCheck($entity2));
self::assertEquals(['data' => ['thedata', 'newdata']], $this->_unitOfWork->getEntityChangeSet($entity2));
self::assertFalse($this->_unitOfWork->isScheduledForDirtyCheck($entity));
self::assertEquals([], $this->_unitOfWork->getEntityChangeSet($entity));
}
public function testGetEntityStateOnVersionedEntityWithAssignedIdentifier(): void
{
$persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(VersionedAssignedIdentifierEntity::class));
$this->_unitOfWork->setEntityPersister(VersionedAssignedIdentifierEntity::class, $persister);
$e = new VersionedAssignedIdentifierEntity();
$e->id = 42;
self::assertEquals(UnitOfWork::STATE_NEW, $this->_unitOfWork->getEntityState($e));
self::assertFalse($persister->isExistsCalled());
}
public function testGetEntityStateWithAssignedIdentity(): void
{
$persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CmsPhonenumber::class));
$this->_unitOfWork->setEntityPersister(CmsPhonenumber::class, $persister);
$ph = new CmsPhonenumber();
$ph->phonenumber = '12345';
self::assertEquals(UnitOfWork::STATE_NEW, $this->_unitOfWork->getEntityState($ph));
self::assertTrue($persister->isExistsCalled());
$persister->reset();
// if the entity is already managed the exists() check should be skipped
$this->_unitOfWork->registerManaged($ph, ['phonenumber' => '12345'], []);
self::assertEquals(UnitOfWork::STATE_MANAGED, $this->_unitOfWork->getEntityState($ph));
self::assertFalse($persister->isExistsCalled());
$ph2 = new CmsPhonenumber();
$ph2->phonenumber = '12345';
self::assertEquals(UnitOfWork::STATE_DETACHED, $this->_unitOfWork->getEntityState($ph2));
self::assertFalse($persister->isExistsCalled());
}
/**
* DDC-2086 [GH-484] Prevented 'Undefined index' notice when updating.
*/
public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges(): void
{
// Setup fake persister and id generator
$userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class));
$userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
$this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister);
// Create a test user
$user = new ForumUser();
$user->username = 'Jasper';
$this->_unitOfWork->persist($user);
$this->_unitOfWork->commit();
// Schedule user for update without changes
$this->_unitOfWork->scheduleForUpdate($user);
self::assertNotEmpty($this->_unitOfWork->getScheduledEntityUpdates());
// This commit should not raise an E_NOTICE
$this->_unitOfWork->commit();
self::assertEmpty($this->_unitOfWork->getScheduledEntityUpdates());
}
/**
* @param mixed $invalidValue
*
* @group DDC-3490
* @dataProvider invalidAssociationValuesDataProvider
*/
public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($invalidValue): void
{
$this->_unitOfWork->setEntityPersister(
ForumUser::class,
new EntityPersisterMock(
$this->_emMock,
$this->_emMock->getClassMetadata(ForumUser::class)
)
);
$user = new ForumUser();
$user->username = 'John';
$user->avatar = $invalidValue;
$this->expectException(ORMInvalidArgumentException::class);
$this->_unitOfWork->persist($user);
}
/**
* @param mixed $invalidValue
*
* @group DDC-3490
* @dataProvider invalidAssociationValuesDataProvider
*/
public function testRejectsChangeSetComputationForObjectsWithInvalidAssociationValue($invalidValue): void
{
$metadata = $this->_emMock->getClassMetadata(ForumUser::class);
$this->_unitOfWork->setEntityPersister(
ForumUser::class,
new EntityPersisterMock($this->_emMock, $metadata)
);
$user = new ForumUser();
$this->_unitOfWork->persist($user);
$user->username = 'John';
$user->avatar = $invalidValue;
$this->expectException(ORMInvalidArgumentException::class);
$this->_unitOfWork->computeChangeSet($metadata, $user);
}
/**
* @group DDC-3619
* @group 1338
*/
public function testRemovedAndRePersistedEntitiesAreInTheIdentityMapAndAreNotGarbageCollected(): void
{
$entity = new ForumUser();
$entity->id = 123;
$this->_unitOfWork->registerManaged($entity, ['id' => 123], []);
self::assertSame(UnitOfWork::STATE_MANAGED, $this->_unitOfWork->getEntityState($entity));
self::assertFalse($this->_unitOfWork->isScheduledForDelete($entity));
self::assertTrue($this->_unitOfWork->isInIdentityMap($entity));
$this->_unitOfWork->remove($entity);
self::assertSame(UnitOfWork::STATE_REMOVED, $this->_unitOfWork->getEntityState($entity));
self::assertTrue($this->_unitOfWork->isScheduledForDelete($entity));
self::assertTrue($this->_unitOfWork->isInIdentityMap($entity));
$this->_unitOfWork->persist($entity);
self::assertSame(UnitOfWork::STATE_MANAGED, $this->_unitOfWork->getEntityState($entity));
self::assertFalse($this->_unitOfWork->isScheduledForDelete($entity));
self::assertTrue($this->_unitOfWork->isInIdentityMap($entity));
}
/**
* @group 5849
* @group 5850
*/
public function testPersistedEntityAndClearManager(): void
{
$entity1 = new City(123, 'London');
$entity2 = new Country(456, 'United Kingdom');
$this->_unitOfWork->persist($entity1);
self::assertTrue($this->_unitOfWork->isInIdentityMap($entity1));
$this->_unitOfWork->persist($entity2);
self::assertTrue($this->_unitOfWork->isInIdentityMap($entity2));
$this->expectDeprecationWithIdentifier('https://github.com/doctrine/orm/issues/8460');
$this->_unitOfWork->clear(Country::class);
self::assertTrue($this->_unitOfWork->isInIdentityMap($entity1));
self::assertFalse($this->_unitOfWork->isInIdentityMap($entity2));
self::assertTrue($this->_unitOfWork->isScheduledForInsert($entity1));
self::assertFalse($this->_unitOfWork->isScheduledForInsert($entity2));
}
/** @group #5579 */
public function testEntityChangeSetIsNotClearedAfterFlushOnSingleEntity(): void
{
$entity1 = new NotifyChangedEntity();
$entity2 = new NotifyChangedEntity();
$entity1->setData('thedata');
$entity2->setData('thedata');
$this->_unitOfWork->persist($entity1);
$this->_unitOfWork->persist($entity2);
$this->expectDeprecationWithIdentifier('https://github.com/doctrine/orm/issues/8459');
$this->_unitOfWork->commit($entity1);
self::assertEmpty($this->_unitOfWork->getEntityChangeSet($entity1));
self::assertCount(1, $this->_unitOfWork->getEntityChangeSet($entity2));
}
/** @group #5579 */
public function testEntityChangeSetIsNotClearedAfterFlushOnArrayOfEntities(): void
{
$entity1 = new NotifyChangedEntity();
$entity2 = new NotifyChangedEntity();
$entity3 = new NotifyChangedEntity();
$entity1->setData('thedata');
$entity2->setData('thedata');
$entity3->setData('thedata');
$this->_unitOfWork->persist($entity1);
$this->_unitOfWork->persist($entity2);
$this->_unitOfWork->persist($entity3);
$this->expectDeprecationWithIdentifier('https://github.com/doctrine/orm/issues/8459');
$this->_unitOfWork->commit([$entity1, $entity3]);
self::assertEmpty($this->_unitOfWork->getEntityChangeSet($entity1));
self::assertEmpty($this->_unitOfWork->getEntityChangeSet($entity3));
self::assertCount(1, $this->_unitOfWork->getEntityChangeSet($entity2));
}
/**
* Data Provider
*
* @return mixed[][]
*/
public static function invalidAssociationValuesDataProvider(): array
{
return [
['foo'],
[['foo']],
[''],
[[]],
[new stdClass()],
[new ArrayCollection()],
];
}
/**
* @param object $entity
*
* @dataProvider entitiesWithValidIdentifiersProvider
*/
public function testAddToIdentityMapValidIdentifiers($entity, string $idHash): void
{
$this->_unitOfWork->persist($entity);
$this->_unitOfWork->addToIdentityMap($entity);
self::assertSame($entity, $this->_unitOfWork->getByIdHash($idHash, get_class($entity)));
}
/** @psalm-return array<string, array{object, string}> */
public static function entitiesWithValidIdentifiersProvider(): array
{
$emptyString = new EntityWithStringIdentifier();
$emptyString->id = '';
$nonEmptyString = new EntityWithStringIdentifier();
$nonEmptyString->id = uniqid('id', true);
$emptyStrings = new EntityWithCompositeStringIdentifier();
$emptyStrings->id1 = '';
$emptyStrings->id2 = '';
$nonEmptyStrings = new EntityWithCompositeStringIdentifier();
$nonEmptyStrings->id1 = uniqid('id1', true);
$nonEmptyStrings->id2 = uniqid('id2', true);
$booleanTrue = new EntityWithBooleanIdentifier();
$booleanTrue->id = true;
$booleanFalse = new EntityWithBooleanIdentifier();
$booleanFalse->id = false;
return [
'empty string, single field' => [$emptyString, ''],
'non-empty string, single field' => [$nonEmptyString, $nonEmptyString->id],
'empty strings, two fields' => [$emptyStrings, ' '],
'non-empty strings, two fields' => [$nonEmptyStrings, $nonEmptyStrings->id1 . ' ' . $nonEmptyStrings->id2],
'boolean true' => [$booleanTrue, '1'],
'boolean false' => [$booleanFalse, ''],
];
}
public function testRegisteringAManagedInstanceRequiresANonEmptyIdentifier(): void
{
$this->expectException(ORMInvalidArgumentException::class);
$this->_unitOfWork->registerManaged(new EntityWithBooleanIdentifier(), [], []);
}
/**
* @param object $entity
* @param array<string, mixed> $identifier
*
* @dataProvider entitiesWithInvalidIdentifiersProvider
*/
public function testAddToIdentityMapInvalidIdentifiers($entity, array $identifier): void
{
$this->expectException(ORMInvalidArgumentException::class);
$this->_unitOfWork->registerManaged($entity, $identifier, []);
}
/** @psalm-return array<string, array{object, array<string, mixed>}> */
public static function entitiesWithInvalidIdentifiersProvider(): array
{
$firstNullString = new EntityWithCompositeStringIdentifier();
$firstNullString->id2 = uniqid('id2', true);
$secondNullString = new EntityWithCompositeStringIdentifier();
$secondNullString->id1 = uniqid('id1', true);
return [
'null string, single field' => [new EntityWithStringIdentifier(), ['id' => null]],
'null strings, two fields' => [new EntityWithCompositeStringIdentifier(), ['id1' => null, 'id2' => null]],
'first null string, two fields' => [$firstNullString, ['id1' => null, 'id2' => $firstNullString->id2]],
'second null string, two fields' => [$secondNullString, ['id1' => $secondNullString->id1, 'id2' => null]],
];
}
/**
* @group 5689
* @group 1465
*/
public function testObjectHashesOfMergedEntitiesAreNotUsedInOriginalEntityDataMap(): void
{
$user = new CmsUser();
$user->name = 'ocramius';
$mergedUser = $this->_unitOfWork->merge($user);
self::assertSame([], $this->_unitOfWork->getOriginalEntityData($user), 'No original data was stored');
self::assertSame([], $this->_unitOfWork->getOriginalEntityData($mergedUser), 'No original data was stored');
$user = null;
$mergedUser = null;
// force garbage collection of $user (frees the used object hashes, which may be recycled)
gc_collect_cycles();
$newUser = new CmsUser();
$newUser->name = 'ocramius';
$this->_unitOfWork->persist($newUser);
self::assertSame([], $this->_unitOfWork->getOriginalEntityData($newUser), 'No original data was stored');
}
/**
* @group DDC-1955
* @group 5570
* @group 6174
*/
public function testMergeWithNewEntityWillPersistItAndTriggerPrePersistListenersWithMergedEntityData(): void
{
$entity = new EntityWithRandomlyGeneratedField();
$generatedFieldValue = $entity->generatedField;
$this
->eventManager
->expects(self::any())
->method('hasListeners')
->willReturnCallback(static function ($eventName) {
return $eventName === Events::prePersist;
});
$this
->eventManager
->expects(self::once())
->method('dispatchEvent')
->with(
self::anything(),
self::callback(static function (LifecycleEventArgs $args) use ($entity, $generatedFieldValue) {
$object = $args->getObject();
assert($object instanceof EntityWithRandomlyGeneratedField);
self::assertInstanceOf(EntityWithRandomlyGeneratedField::class, $object);
self::assertNotSame($entity, $object);
self::assertSame($generatedFieldValue, $object->generatedField);
return true;
})
);
$object = $this->_unitOfWork->merge($entity);
assert($object instanceof EntityWithRandomlyGeneratedField);
self::assertNotSame($object, $entity);
self::assertInstanceOf(EntityWithRandomlyGeneratedField::class, $object);
self::assertSame($object->generatedField, $entity->generatedField);
}
/**
* @group DDC-1955
* @group 5570
* @group 6174
*/
public function testMergeWithExistingEntityWillNotPersistItNorTriggerPrePersistListeners(): void
{
$persistedEntity = new EntityWithRandomlyGeneratedField();
$mergedEntity = new EntityWithRandomlyGeneratedField();
$mergedEntity->id = $persistedEntity->id;
$mergedEntity->generatedField = random_int(
$persistedEntity->generatedField + 1,
$persistedEntity->generatedField + 1000
);
$this
->eventManager
->expects(self::any())
->method('hasListeners')
->willReturnCallback(static function ($eventName) {
return $eventName === Events::prePersist;
});
$this->eventManager->expects(self::never())->method('dispatchEvent');
$this->_unitOfWork->registerManaged(
$persistedEntity,
['id' => $persistedEntity->id],
['generatedField' => $persistedEntity->generatedField]
);
$merged = $this->_unitOfWork->merge($mergedEntity);
assert($merged instanceof EntityWithRandomlyGeneratedField);
self::assertSame($merged, $persistedEntity);
self::assertSame($persistedEntity->generatedField, $mergedEntity->generatedField);
}
/**
* Unlike next test, this one demonstrates that the problem does
* not necessarily reproduce if all the pieces are being flushed together.
*
* @group DDC-2922
* @group #1521
*/
public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughCascadedAssociationsFirst(): void
{
$persister1 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CascadePersistedEntity::class));
$persister2 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithCascadingAssociation::class));
$persister3 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithNonCascadingAssociation::class));
$this->_unitOfWork->setEntityPersister(CascadePersistedEntity::class, $persister1);
$this->_unitOfWork->setEntityPersister(EntityWithCascadingAssociation::class, $persister2);
$this->_unitOfWork->setEntityPersister(EntityWithNonCascadingAssociation::class, $persister3);
$cascadePersisted = new CascadePersistedEntity();
$cascading = new EntityWithCascadingAssociation();
$nonCascading = new EntityWithNonCascadingAssociation();
// First we persist and flush a EntityWithCascadingAssociation with
// the cascading association not set. Having the "cascading path" involve
// a non-new object is important to show that the ORM should be considering
// cascades across entity changesets in subsequent flushes.
$cascading->cascaded = $cascadePersisted;
$nonCascading->nonCascaded = $cascadePersisted;
$this->_unitOfWork->persist($cascading);
$this->_unitOfWork->persist($nonCascading);
$this->_unitOfWork->commit();
self::assertCount(1, $persister1->getInserts());
self::assertCount(1, $persister2->getInserts());
self::assertCount(1, $persister3->getInserts());
}
/**
* This test exhibits the bug describe in the ticket, where an object that
* ought to be reachable causes errors.
*
* @group DDC-2922
* @group #1521
*/
public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughNonCascadedAssociationsFirst(): void
{
$persister1 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CascadePersistedEntity::class));
$persister2 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithCascadingAssociation::class));
$persister3 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithNonCascadingAssociation::class));
$this->_unitOfWork->setEntityPersister(CascadePersistedEntity::class, $persister1);
$this->_unitOfWork->setEntityPersister(EntityWithCascadingAssociation::class, $persister2);
$this->_unitOfWork->setEntityPersister(EntityWithNonCascadingAssociation::class, $persister3);
$cascadePersisted = new CascadePersistedEntity();
$cascading = new EntityWithCascadingAssociation();
$nonCascading = new EntityWithNonCascadingAssociation();
// First we persist and flush a EntityWithCascadingAssociation with
// the cascading association not set. Having the "cascading path" involve
// a non-new object is important to show that the ORM should be considering
// cascades across entity changesets in subsequent flushes.
$cascading->cascaded = null;
$this->_unitOfWork->persist($cascading);
$this->_unitOfWork->commit();
self::assertCount(0, $persister1->getInserts());
self::assertCount(1, $persister2->getInserts());
self::assertCount(0, $persister3->getInserts());
// Note that we have NOT directly persisted the CascadePersistedEntity,
// and EntityWithNonCascadingAssociation does NOT have a configured
// cascade-persist.
$nonCascading->nonCascaded = $cascadePersisted;
// However, EntityWithCascadingAssociation *does* have a cascade-persist
// association, which ought to allow us to save the CascadePersistedEntity
// anyway through that connection.
$cascading->cascaded = $cascadePersisted;
$this->_unitOfWork->persist($nonCascading);
$this->_unitOfWork->commit();
self::assertCount(1, $persister1->getInserts());
self::assertCount(1, $persister2->getInserts());
self::assertCount(1, $persister3->getInserts());
}
/**
* This test exhibits the bug describe in the ticket, where an object that
* ought to be reachable causes errors.
*
* @group DDC-2922
* @group #1521
*/
public function testPreviousDetectedIllegalNewNonCascadedEntitiesAreCleanedUpOnSubsequentCommits(): void
{
$persister1 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CascadePersistedEntity::class));
$persister2 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithNonCascadingAssociation::class));
$this->_unitOfWork->setEntityPersister(CascadePersistedEntity::class, $persister1);
$this->_unitOfWork->setEntityPersister(EntityWithNonCascadingAssociation::class, $persister2);
$cascadePersisted = new CascadePersistedEntity();
$nonCascading = new EntityWithNonCascadingAssociation();
// We explicitly cause the ORM to detect a non-persisted new entity in the association graph:
$nonCascading->nonCascaded = $cascadePersisted;
$this->_unitOfWork->persist($nonCascading);
try {
$this->_unitOfWork->commit();
self::fail('An exception was supposed to be raised');
} catch (ORMInvalidArgumentException $ignored) {
self::assertEmpty($persister1->getInserts());
self::assertEmpty($persister2->getInserts());
}
$this->_unitOfWork->clear();
$this->_unitOfWork->persist(new CascadePersistedEntity());
$this->_unitOfWork->commit();
// Persistence operations should just recover normally:
self::assertCount(1, $persister1->getInserts());
self::assertCount(0, $persister2->getInserts());
}
/** @group #7946 Throw OptimisticLockException when connection::commit() returns false. */
public function testCommitThrowOptimisticLockExceptionWhenConnectionCommitReturnFalse(): void
{
$driver = $this->createMock(Driver::class);
$driver->method('connect')
->willReturn($this->createMock(Driver\Connection::class));
// Set another connection mock that fail on commit
$this->_connectionMock = $this->getMockBuilderWithOnlyMethods(ConnectionMock::class, ['commit'])
->setConstructorArgs([[], $driver])
->getMock();
$this->_emMock = new EntityManagerMock($this->_connectionMock);
$this->_unitOfWork = new UnitOfWorkMock($this->_emMock);
$this->_emMock->setUnitOfWork($this->_unitOfWork);
$this->_connectionMock->method('commit')->willReturn(false);
// Setup fake persister and id generator
$userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class));
$userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
$this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister);
// Create a test user
$user = new ForumUser();
$user->username = 'Jasper';
$this->_unitOfWork->persist($user);
$this->expectException(OptimisticLockException::class);
$this->_unitOfWork->commit();
}
public function testItThrowsWhenLookingUpIdentifierForUnknownEntity(): void
{
$this->expectException(EntityNotFoundException::class);
$this->_unitOfWork->getEntityIdentifier(new stdClass());
}
public function testRemovedEntityIsRemovedFromManyToManyCollection(): void
{
$group = new CmsGroup();
$group->name = 'test';
$this->_unitOfWork->persist($group);
$user = new CmsUser();
$user->name = 'test';
$user->groups->add($group);
$this->_unitOfWork->persist($user);
$this->_unitOfWork->commit();
self::assertFalse($user->groups->isDirty());
$this->_unitOfWork->remove($group);
$this->_unitOfWork->commit();
// Test that the removed entity has been removed from the many to many collection
self::assertEmpty(
$user->groups,
'the removed entity should have been removed from the many to many collection'
);
// Collection is clean, snapshot has been updated
self::assertFalse($user->groups->isDirty());
self::assertEmpty($user->groups->getSnapshot());
}
public function testRemovedEntityIsRemovedFromOneToManyCollection(): void
{
$user = new CmsUser();
$user->name = 'test';
$phonenumber = new CmsPhonenumber();
$phonenumber->phonenumber = '0800-123456';
$user->addPhonenumber($phonenumber);
$this->_unitOfWork->persist($user);
$this->_unitOfWork->persist($phonenumber);
$this->_unitOfWork->commit();
self::assertFalse($user->phonenumbers->isDirty());
$this->_unitOfWork->remove($phonenumber);
$this->_unitOfWork->commit();
// Test that the removed entity has been removed from the one to many collection
self::assertEmpty($user->phonenumbers);
// Collection is clean, snapshot has been updated
self::assertFalse($user->phonenumbers->isDirty());
self::assertEmpty($user->phonenumbers->getSnapshot());
}
public function testItTriggersADeprecationNoticeWhenApplicationProvidedIdsCollide(): void
{
// We're using application-provided IDs and assign the same ID twice
// Note this is about colliding IDs in the identity map in memory.
// Duplicate database-level IDs would be spotted when the EM is flushed.
$phone1 = new CmsPhonenumber();
$phone1->phonenumber = '1234';
$this->_unitOfWork->persist($phone1);
$phone2 = new CmsPhonenumber();
$phone2->phonenumber = '1234';
$this->expectDeprecationWithIdentifier('https://github.com/doctrine/orm/pull/10785');
$this->_unitOfWork->persist($phone2);
}
public function testItThrowsWhenApplicationProvidedIdsCollide(): void
{
$this->_emMock->getConfiguration()->setRejectIdCollisionInIdentityMap(true);
// We're using application-provided IDs and assign the same ID twice
// Note this is about colliding IDs in the identity map in memory.
// Duplicate database-level IDs would be spotted when the EM is flushed.
$phone1 = new CmsPhonenumber();
$phone1->phonenumber = '1234';
$this->_unitOfWork->persist($phone1);
$phone2 = new CmsPhonenumber();
$phone2->phonenumber = '1234';
$this->expectException(EntityIdentityCollisionException::class);
$this->expectExceptionMessageMatches('/another object .* was already present for the same ID/');
$this->_unitOfWork->persist($phone2);
}
}
/** @Entity */
class NotifyChangedEntity implements NotifyPropertyChanged
{
/** @psalm-var list<PropertyChangedListener> */
private $_listeners = [];
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
private $id;
/**
* @var string
* @Column(type="string", length=255)
*/
private $data;
/** @var mixed */
private $transient; // not persisted
/**
* @psalm-var Collection<int, NotifyChangedRelatedItem>