Completed
Pull Request — master (#6017)
by Jeremy
10:17
created

entitiesWithInvalidIdentifiersProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
nc 1
nop 0
1
<?php
2
3
namespace Doctrine\Tests\ORM;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Doctrine\Common\NotifyPropertyChanged;
7
use Doctrine\Common\PropertyChangedListener;
8
use Doctrine\ORM\Mapping\ClassMetadata;
9
use Doctrine\ORM\ORMInvalidArgumentException;
10
use Doctrine\ORM\UnitOfWork;
11
use Doctrine\Tests\Mocks\ConnectionMock;
12
use Doctrine\Tests\Mocks\DriverMock;
13
use Doctrine\Tests\Mocks\EntityManagerMock;
14
use Doctrine\Tests\Mocks\EntityPersisterMock;
15
use Doctrine\Tests\Mocks\UnitOfWorkMock;
16
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
17
use Doctrine\Tests\Models\CMS\CmsUser;
18
use Doctrine\Tests\Models\Forum\ForumAvatar;
19
use Doctrine\Tests\Models\Forum\ForumUser;
20
use Doctrine\Tests\Models\GeoNames\City;
21
use Doctrine\Tests\Models\GeoNames\Country;
22
use Doctrine\Tests\OrmTestCase;
23
use stdClass;
24
25
/**
26
 * UnitOfWork tests.
27
 */
28
class UnitOfWorkTest extends OrmTestCase
29
{
30
    /**
31
     * SUT
32
     *
33
     * @var UnitOfWorkMock
34
     */
35
    private $_unitOfWork;
36
37
    /**
38
     * Provides a sequence mock to the UnitOfWork
39
     *
40
     * @var ConnectionMock
41
     */
42
    private $_connectionMock;
43
44
    /**
45
     * The EntityManager mock that provides the mock persisters
46
     *
47
     * @var EntityManagerMock
48
     */
49
    private $_emMock;
50
51
    protected function setUp() {
52
        parent::setUp();
53
        $this->_connectionMock = new ConnectionMock(array(), new DriverMock());
54
        $this->_emMock = EntityManagerMock::create($this->_connectionMock);
55
        // SUT
56
        $this->_unitOfWork = new UnitOfWorkMock($this->_emMock);
57
        $this->_emMock->setUnitOfWork($this->_unitOfWork);
58
    }
59
60
    protected function tearDown() {
61
    }
62
63
    public function testRegisterRemovedOnNewEntityIsIgnored()
64
    {
65
        $user = new ForumUser();
66
        $user->username = 'romanb';
67
        $this->assertFalse($this->_unitOfWork->isScheduledForDelete($user));
68
        $this->_unitOfWork->scheduleForDelete($user);
69
        $this->assertFalse($this->_unitOfWork->isScheduledForDelete($user));
70
    }
71
72
73
    /* Operational tests */
74
75
    public function testSavingSingleEntityWithIdentityColumnForcesInsert()
76
    {
77
        // Setup fake persister and id generator for identity generation
78
        $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser'));
79
        $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\Forum\ForumUser', $userPersister);
80
        $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
81
82
        // Test
83
        $user = new ForumUser();
84
        $user->username = 'romanb';
85
        $this->_unitOfWork->persist($user);
86
87
        // Check
88
        $this->assertEquals(0, count($userPersister->getInserts()));
89
        $this->assertEquals(0, count($userPersister->getUpdates()));
90
        $this->assertEquals(0, count($userPersister->getDeletes()));
91
        $this->assertFalse($this->_unitOfWork->isInIdentityMap($user));
92
        // should no longer be scheduled for insert
93
        $this->assertTrue($this->_unitOfWork->isScheduledForInsert($user));
94
95
        // Now lets check whether a subsequent commit() does anything
96
        $userPersister->reset();
97
98
        // Test
99
        $this->_unitOfWork->commit();
100
101
        // Check.
102
        $this->assertEquals(1, count($userPersister->getInserts()));
103
        $this->assertEquals(0, count($userPersister->getUpdates()));
104
        $this->assertEquals(0, count($userPersister->getDeletes()));
105
106
        // should have an id
107
        $this->assertTrue(is_numeric($user->id));
108
    }
109
110
    /**
111
     * Tests a scenario where a save() operation is cascaded from a ForumUser
112
     * to its associated ForumAvatar, both entities using IDENTITY id generation.
113
     */
114
    public function testCascadedIdentityColumnInsert()
115
    {
116
        // Setup fake persister and id generator for identity generation
117
        //ForumUser
118
        $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser'));
119
        $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\Forum\ForumUser', $userPersister);
120
        $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
121
        // ForumAvatar
122
        $avatarPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumAvatar'));
123
        $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\Forum\ForumAvatar', $avatarPersister);
124
        $avatarPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
125
126
        // Test
127
        $user = new ForumUser();
128
        $user->username = 'romanb';
129
        $avatar = new ForumAvatar();
130
        $user->avatar = $avatar;
131
        $this->_unitOfWork->persist($user); // save cascaded to avatar
132
133
        $this->_unitOfWork->commit();
134
135
        $this->assertTrue(is_numeric($user->id));
136
        $this->assertTrue(is_numeric($avatar->id));
137
138
        $this->assertEquals(1, count($userPersister->getInserts()));
139
        $this->assertEquals(0, count($userPersister->getUpdates()));
140
        $this->assertEquals(0, count($userPersister->getDeletes()));
141
142
        $this->assertEquals(1, count($avatarPersister->getInserts()));
143
        $this->assertEquals(0, count($avatarPersister->getUpdates()));
144
        $this->assertEquals(0, count($avatarPersister->getDeletes()));
145
    }
146
147
    public function testChangeTrackingNotify()
148
    {
149
        $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\NotifyChangedEntity'));
150
        $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedEntity', $persister);
151
        $itemPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\NotifyChangedRelatedItem'));
152
        $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedRelatedItem', $itemPersister);
153
154
        $entity = new NotifyChangedEntity;
155
        $entity->setData('thedata');
156
        $this->_unitOfWork->persist($entity);
157
158
        $this->_unitOfWork->commit();
159
        $this->assertEquals(1, count($persister->getInserts()));
160
        $persister->reset();
161
162
        $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity));
163
164
        $entity->setData('newdata');
165
        $entity->setTransient('newtransientvalue');
166
167
        $this->assertTrue($this->_unitOfWork->isScheduledForDirtyCheck($entity));
168
169
        $this->assertEquals(array('data' => array('thedata', 'newdata')), $this->_unitOfWork->getEntityChangeSet($entity));
170
171
        $item = new NotifyChangedRelatedItem();
172
        $entity->getItems()->add($item);
173
        $item->setOwner($entity);
174
        $this->_unitOfWork->persist($item);
175
176
        $this->_unitOfWork->commit();
177
        $this->assertEquals(1, count($itemPersister->getInserts()));
178
        $persister->reset();
179
        $itemPersister->reset();
180
181
182
        $entity->getItems()->removeElement($item);
183
        $item->setOwner(null);
184
        $this->assertTrue($entity->getItems()->isDirty());
185
        $this->_unitOfWork->commit();
186
        $updates = $itemPersister->getUpdates();
187
        $this->assertEquals(1, count($updates));
188
        $this->assertTrue($updates[0] === $item);
189
    }
190
191
    public function testGetEntityStateOnVersionedEntityWithAssignedIdentifier()
192
    {
193
        $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\VersionedAssignedIdentifierEntity'));
194
        $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\VersionedAssignedIdentifierEntity', $persister);
195
196
        $e = new VersionedAssignedIdentifierEntity();
197
        $e->id = 42;
198
        $this->assertEquals(UnitOfWork::STATE_NEW, $this->_unitOfWork->getEntityState($e));
199
        $this->assertFalse($persister->isExistsCalled());
200
    }
201
202
    public function testGetEntityStateWithAssignedIdentity()
203
    {
204
        $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'));
205
        $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\CMS\CmsPhonenumber', $persister);
206
207
        $ph = new CmsPhonenumber();
208
        $ph->phonenumber = '12345';
209
210
        $this->assertEquals(UnitOfWork::STATE_NEW, $this->_unitOfWork->getEntityState($ph));
211
        $this->assertTrue($persister->isExistsCalled());
212
213
        $persister->reset();
214
215
        // if the entity is already managed the exists() check should be skipped
216
        $this->_unitOfWork->registerManaged($ph, array('phonenumber' => '12345'), array());
217
        $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_unitOfWork->getEntityState($ph));
218
        $this->assertFalse($persister->isExistsCalled());
219
        $ph2 = new CmsPhonenumber();
220
        $ph2->phonenumber = '12345';
221
        $this->assertEquals(UnitOfWork::STATE_DETACHED, $this->_unitOfWork->getEntityState($ph2));
222
        $this->assertFalse($persister->isExistsCalled());
223
    }
224
225
    /**
226
     * DDC-2086 [GH-484] Prevented 'Undefined index' notice when updating.
227
     */
228
    public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges()
229
    {
230
        // Setup fake persister and id generator
231
        $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser'));
232
        $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
233
        $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\Forum\ForumUser', $userPersister);
234
235
        // Create a test user
236
        $user = new ForumUser();
237
        $user->name = 'Jasper';
238
        $this->_unitOfWork->persist($user);
239
        $this->_unitOfWork->commit();
240
241
        // Schedule user for update without changes
242
        $this->_unitOfWork->scheduleForUpdate($user);
243
244
        // This commit should not raise an E_NOTICE
245
        $this->_unitOfWork->commit();
246
    }
247
248
    /**
249
     * @group DDC-1984
250
     */
251
    public function testLockWithoutEntityThrowsException()
252
    {
253
        $this->expectException(\InvalidArgumentException::class);
254
        $this->_unitOfWork->lock(null, null, null);
255
    }
256
257
    /**
258
     * @group DDC-3490
259
     *
260
     * @dataProvider invalidAssociationValuesDataProvider
261
     *
262
     * @param mixed $invalidValue
263
     */
264
    public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($invalidValue)
265
    {
266
        $this->_unitOfWork->setEntityPersister(
267
            'Doctrine\Tests\Models\Forum\ForumUser',
268
            new EntityPersisterMock(
269
                $this->_emMock,
270
                $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser')
271
            )
272
        );
273
274
        $user           = new ForumUser();
275
        $user->username = 'John';
276
        $user->avatar   = $invalidValue;
277
278
        $this->expectException(\Doctrine\ORM\ORMInvalidArgumentException::class);
279
280
        $this->_unitOfWork->persist($user);
281
    }
282
283
    /**
284
     * @group DDC-3490
285
     *
286
     * @dataProvider invalidAssociationValuesDataProvider
287
     *
288
     * @param mixed $invalidValue
289
     */
290
    public function testRejectsChangeSetComputationForObjectsWithInvalidAssociationValue($invalidValue)
291
    {
292
        $metadata = $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser');
293
294
        $this->_unitOfWork->setEntityPersister(
295
            'Doctrine\Tests\Models\Forum\ForumUser',
296
            new EntityPersisterMock($this->_emMock, $metadata)
297
        );
298
299
        $user = new ForumUser();
300
301
        $this->_unitOfWork->persist($user);
302
303
        $user->username = 'John';
304
        $user->avatar   = $invalidValue;
305
306
        $this->expectException(\Doctrine\ORM\ORMInvalidArgumentException::class);
307
308
        $this->_unitOfWork->computeChangeSet($metadata, $user);
309
    }
310
311
    /**
312
     * @group DDC-3619
313
     * @group 1338
314
     */
315
    public function testRemovedAndRePersistedEntitiesAreInTheIdentityMapAndAreNotGarbageCollected()
316
    {
317
        $entity     = new ForumUser();
318
        $entity->id = 123;
319
320
        $this->_unitOfWork->registerManaged($entity, array('id' => 123), array());
321
        $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity));
322
323
        $this->_unitOfWork->remove($entity);
324
        $this->assertFalse($this->_unitOfWork->isInIdentityMap($entity));
325
326
        $this->_unitOfWork->persist($entity);
327
        $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity));
328
    }
329
330
    /**
331
     * @group 5849
332
     * @group 5850
333
     */
334
    public function testPersistedEntityAndClearManager()
335
    {
336
        $entity1 = new City(123, 'London');
337
        $entity2 = new Country(456, 'United Kingdom');
338
339
        $this->_unitOfWork->persist($entity1);
340
        $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity1));
341
342
        $this->_unitOfWork->persist($entity2);
343
        $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity2));
344
345
        $this->_unitOfWork->clear(Country::class);
346
        $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity1));
347
        $this->assertFalse($this->_unitOfWork->isInIdentityMap($entity2));
348
        $this->assertTrue($this->_unitOfWork->isScheduledForInsert($entity1));
349
        $this->assertFalse($this->_unitOfWork->isScheduledForInsert($entity2));
350
    }
351
352
    public function testClearManagerWithObject()
353
    {
354
        $entity = new Country(456, 'United Kingdom');
355
356
        $this->_unitOfWork->persist($entity);
357
        $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity));
358
359
        $this->_unitOfWork->clear($entity);
360
361
        // true because entity wasn't a string so it wasn't cleared
362
        $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity));
363
        $this->assertTrue($this->_unitOfWork->isScheduledForInsert($entity));
364
    }
365
366
    /**
367
     * Data Provider
368
     *
369
     * @return mixed[][]
370
     */
371
    public function invalidAssociationValuesDataProvider()
372
    {
373
        return [
374
            ['foo'],
375
            [['foo']],
376
            [''],
377
            [[]],
378
            [new stdClass()],
379
            [new ArrayCollection()],
380
        ];
381
    }
382
383
    /**
384
     * @dataProvider entitiesWithValidIdentifiersProvider
385
     *
386
     * @param object $entity
387
     * @param string $idHash
388
     *
389
     * @return void
390
     */
391
    public function testAddToIdentityMapValidIdentifiers($entity, $idHash)
392
    {
393
        $this->_unitOfWork->persist($entity);
394
        $this->_unitOfWork->addToIdentityMap($entity);
395
396
        self::assertSame($entity, $this->_unitOfWork->getByIdHash($idHash, get_class($entity)));
397
    }
398
399
    public function entitiesWithValidIdentifiersProvider()
400
    {
401
        $emptyString = new EntityWithStringIdentifier();
402
403
        $emptyString->id = '';
404
405
        $nonEmptyString = new EntityWithStringIdentifier();
406
407
        $nonEmptyString->id = uniqid('id', true);
408
409
        $emptyStrings = new EntityWithCompositeStringIdentifier();
410
411
        $emptyStrings->id1 = '';
412
        $emptyStrings->id2 = '';
413
414
        $nonEmptyStrings = new EntityWithCompositeStringIdentifier();
415
416
        $nonEmptyStrings->id1 = uniqid('id1', true);
417
        $nonEmptyStrings->id2 = uniqid('id2', true);
418
419
        $booleanTrue = new EntityWithBooleanIdentifier();
420
421
        $booleanTrue->id = true;
422
423
        $booleanFalse = new EntityWithBooleanIdentifier();
424
425
        $booleanFalse->id = false;
426
427
        return [
428
            'empty string, single field'     => [$emptyString, ''],
429
            'non-empty string, single field' => [$nonEmptyString, $nonEmptyString->id],
430
            'empty strings, two fields'      => [$emptyStrings, ' '],
431
            'non-empty strings, two fields'  => [$nonEmptyStrings, $nonEmptyStrings->id1 . ' ' . $nonEmptyStrings->id2],
432
            'boolean true'                   => [$booleanTrue, '1'],
433
            'boolean false'                  => [$booleanFalse, ''],
434
        ];
435
    }
436
437
    public function testRegisteringAManagedInstanceRequiresANonEmptyIdentifier()
438
    {
439
        $this->expectException(ORMInvalidArgumentException::class);
440
441
        $this->_unitOfWork->registerManaged(new EntityWithBooleanIdentifier(), [], []);
442
    }
443
444
    /**
445
     * @dataProvider entitiesWithInvalidIdentifiersProvider
446
     *
447
     * @param object $entity
448
     * @param array  $identifier
449
     *
450
     * @return void
451
     */
452
    public function testAddToIdentityMapInvalidIdentifiers($entity, array $identifier)
453
    {
454
        $this->expectException(ORMInvalidArgumentException::class);
455
456
        $this->_unitOfWork->registerManaged($entity, $identifier, []);
457
    }
458
459
460
    public function entitiesWithInvalidIdentifiersProvider()
461
    {
462
        $firstNullString  = new EntityWithCompositeStringIdentifier();
463
464
        $firstNullString->id2 = uniqid('id2', true);
465
466
        $secondNullString = new EntityWithCompositeStringIdentifier();
467
468
        $secondNullString->id1 = uniqid('id1', true);
469
470
        return [
471
            'null string, single field'      => [new EntityWithStringIdentifier(), ['id' => null]],
472
            'null strings, two fields'       => [new EntityWithCompositeStringIdentifier(), ['id1' => null, 'id2' => null]],
473
            'first null string, two fields'  => [$firstNullString, ['id1' => null, 'id2' => $firstNullString->id2]],
474
            'second null string, two fields' => [$secondNullString, ['id1' => $secondNullString->id1, 'id2' => null]],
475
        ];
476
    }
477
478
    /**
479
     * @group 5689
480
     * @group 1465
481
     */
482
    public function testObjectHashesOfMergedEntitiesAreNotUsedInOriginalEntityDataMap()
483
    {
484
        $user       = new CmsUser();
485
        $user->name = 'ocramius';
486
        $mergedUser = $this->_unitOfWork->merge($user);
487
488
        self::assertSame([], $this->_unitOfWork->getOriginalEntityData($user), 'No original data was stored');
489
        self::assertSame([], $this->_unitOfWork->getOriginalEntityData($mergedUser), 'No original data was stored');
490
491
492
        $user       = null;
493
        $mergedUser = null;
494
495
        // force garbage collection of $user (frees the used object hashes, which may be recycled)
496
        gc_collect_cycles();
497
498
        $newUser       = new CmsUser();
499
        $newUser->name = 'ocramius';
500
501
        $this->_unitOfWork->persist($newUser);
502
503
        self::assertSame([], $this->_unitOfWork->getOriginalEntityData($newUser), 'No original data was stored');
504
    }
505
}
506
507
/**
508
 * @Entity
509
 */
510
class NotifyChangedEntity implements NotifyPropertyChanged
511
{
512
    private $_listeners = array();
513
    /**
514
     * @Id
515
     * @Column(type="integer")
516
     * @GeneratedValue
517
     */
518
    private $id;
519
    /**
520
     * @Column(type="string")
521
     */
522
    private $data;
523
524
    private $transient; // not persisted
525
526
    /** @OneToMany(targetEntity="NotifyChangedRelatedItem", mappedBy="owner") */
527
    private $items;
528
529
    public function  __construct() {
530
        $this->items = new ArrayCollection;
531
    }
532
533
    public function getId() {
534
        return $this->id;
535
    }
536
537
    public function getItems() {
538
        return $this->items;
539
    }
540
541
    public function setTransient($value) {
542
        if ($value != $this->transient) {
543
            $this->_onPropertyChanged('transient', $this->transient, $value);
544
            $this->transient = $value;
545
        }
546
    }
547
548
    public function getData() {
549
        return $this->data;
550
    }
551
552
    public function setData($data) {
553
        if ($data != $this->data) {
554
            $this->_onPropertyChanged('data', $this->data, $data);
555
            $this->data = $data;
556
        }
557
    }
558
559
    public function addPropertyChangedListener(PropertyChangedListener $listener)
560
    {
561
        $this->_listeners[] = $listener;
562
    }
563
564
    protected function _onPropertyChanged($propName, $oldValue, $newValue) {
565
        if ($this->_listeners) {
566
            foreach ($this->_listeners as $listener) {
567
                $listener->propertyChanged($this, $propName, $oldValue, $newValue);
568
            }
569
        }
570
    }
571
}
572
573
/** @Entity */
574
class NotifyChangedRelatedItem
575
{
576
    /**
577
     * @Id
578
     * @Column(type="integer")
579
     * @GeneratedValue
580
     */
581
    private $id;
582
583
    /** @ManyToOne(targetEntity="NotifyChangedEntity", inversedBy="items") */
584
    private $owner;
585
586
    public function getId() {
587
        return $this->id;
588
    }
589
590
    public function getOwner() {
591
        return $this->owner;
592
    }
593
594
    public function setOwner($owner) {
595
        $this->owner = $owner;
596
    }
597
}
598
599
/** @Entity */
600
class VersionedAssignedIdentifierEntity
601
{
602
    /**
603
     * @Id @Column(type="integer")
604
     */
605
    public $id;
606
    /**
607
     * @Version @Column(type="integer")
608
     */
609
    public $version;
610
}
611
612
/** @Entity */
613
class EntityWithStringIdentifier
614
{
615
    /**
616
     * @Id @Column(type="string")
617
     *
618
     * @var string|null
619
     */
620
    public $id;
621
}
622
623
/** @Entity */
624
class EntityWithBooleanIdentifier
625
{
626
    /**
627
     * @Id @Column(type="boolean")
628
     *
629
     * @var bool|null
630
     */
631
    public $id;
632
}
633
634
/** @Entity */
635
class EntityWithCompositeStringIdentifier
636
{
637
    /**
638
     * @Id @Column(type="string")
639
     *
640
     * @var string|null
641
     */
642
    public $id1;
643
644
    /**
645
     * @Id @Column(type="string")
646
     *
647
     * @var string|null
648
     */
649
    public $id2;
650
}
651