File: LifecycleCallbackTest.php

package info (click to toggle)
doctrine 3.5.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 11,552 kB
  • sloc: php: 108,302; xml: 1,340; makefile: 35; sh: 14
file content (662 lines) | stat: -rw-r--r-- 19,108 bytes parent folder | download | duplicates (2)
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
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Event\PostLoadEventArgs;
use Doctrine\ORM\Event\PostPersistEventArgs;
use Doctrine\ORM\Event\PostRemoveEventArgs;
use Doctrine\ORM\Event\PostUpdateEventArgs;
use Doctrine\ORM\Event\PreFlushEventArgs;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Event\PreRemoveEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\MappedSuperclass;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping\PostLoad;
use Doctrine\ORM\Mapping\PostPersist;
use Doctrine\ORM\Mapping\PostRemove;
use Doctrine\ORM\Mapping\PostUpdate;
use Doctrine\ORM\Mapping\PreFlush;
use Doctrine\ORM\Mapping\PrePersist;
use Doctrine\ORM\Mapping\PreRemove;
use Doctrine\ORM\Mapping\PreUpdate;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Query;
use Doctrine\Tests\OrmFunctionalTestCase;
use PHPUnit\Framework\Attributes\Group;

use function count;
use function current;
use function iterator_to_array;
use function sprintf;

class LifecycleCallbackTest extends OrmFunctionalTestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->createSchemaForModels(
            LifecycleCallbackEventArgEntity::class,
            LifecycleCallbackTestEntity::class,
            LifecycleCallbackTestUser::class,
            LifecycleCallbackCascader::class,
        );
    }

    public function testPreSavePostSaveCallbacksAreInvoked(): void
    {
        $entity        = new LifecycleCallbackTestEntity();
        $entity->value = 'hello';
        $this->_em->persist($entity);
        $this->_em->flush();

        self::assertTrue($entity->prePersistCallbackInvoked);
        self::assertTrue($entity->postPersistCallbackInvoked);

        $this->_em->clear();
        LifecycleCallbackTestEntity::$postLoadCallbackInvoked = false; // Reset the tracking of the postLoad invocation

        $query  = $this->_em->createQuery('select e from Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity e');
        $result = $query->getResult();
        self::assertTrue($result[0]::$postLoadCallbackInvoked);

        $result[0]->value = 'hello again';

        $this->_em->flush();

        self::assertEquals('changed from preUpdate callback!', $result[0]->value);
    }

    public function testPreFlushCallbacksAreInvoked(): void
    {
        $entity        = new LifecycleCallbackTestEntity();
        $entity->value = 'hello';
        $this->_em->persist($entity);

        $this->_em->flush();

        self::assertTrue($entity->prePersistCallbackInvoked);
        self::assertTrue($entity->preFlushCallbackInvoked);

        $entity->preFlushCallbackInvoked = false;
        $this->_em->flush();

        self::assertTrue($entity->preFlushCallbackInvoked);

        $entity->value                   = 'bye';
        $entity->preFlushCallbackInvoked = false;
        $this->_em->flush();

        self::assertTrue($entity->preFlushCallbackInvoked);
    }

    public function testChangesDontGetLost(): void
    {
        $user = new LifecycleCallbackTestUser();
        $user->setName('Bob');
        $user->setValue('value');
        $this->_em->persist($user);
        $this->_em->flush();

        $user->setName('Alice');
        $this->_em->flush(); // Triggers preUpdate

        $this->_em->clear();

        $user2 = $this->_em->find($user::class, $user->getId());

        self::assertEquals('Alice', $user2->getName());
        self::assertEquals('Hello World', $user2->getValue());
    }

    #[Group('DDC-194')]
    public function testGetReferenceWithPostLoadEventIsDelayedUntilProxyTrigger(): void
    {
        $entity        = new LifecycleCallbackTestEntity();
        $entity->value = 'hello';
        $this->_em->persist($entity);
        $this->_em->flush();
        $id = $entity->getId();

        $this->_em->clear();
        LifecycleCallbackTestEntity::$postLoadCallbackInvoked = false; // Reset the tracking of the postLoad invocation

        $reference = $this->_em->getReference(LifecycleCallbackTestEntity::class, $id);
        self::assertArrayNotHasKey('postLoadCallbackInvoked', (array) $reference);
        $this->assertTrue($this->isUninitializedObject($reference));

        $reference->getValue(); // trigger proxy load
        self::assertTrue($reference::$postLoadCallbackInvoked);
    }

    #[Group('DDC-958')]
    public function testPostLoadTriggeredOnRefresh(): void
    {
        $entity        = new LifecycleCallbackTestEntity();
        $entity->value = 'hello';
        $this->_em->persist($entity);
        $this->_em->flush();
        $id = $entity->getId();

        $this->_em->clear();
        LifecycleCallbackTestEntity::$postLoadCallbackInvoked = false; // Reset the tracking of the postLoad invocation

        $reference = $this->_em->find(LifecycleCallbackTestEntity::class, $id);
        self::assertTrue($reference::$postLoadCallbackInvoked);
        $reference::$postLoadCallbackInvoked = false;

        $this->_em->refresh($reference);
        self::assertTrue($reference::$postLoadCallbackInvoked, 'postLoad should be invoked when refresh() is called.');
    }

    #[Group('DDC-113')]
    public function testCascadedEntitiesCallsPrePersist(): void
    {
        $e1 = new LifecycleCallbackTestEntity();
        $e2 = new LifecycleCallbackTestEntity();

        $c = new LifecycleCallbackCascader();
        $this->_em->persist($c);

        $c->entities[] = $e1;
        $c->entities[] = $e2;
        $e1->cascader  = $c;
        $e2->cascader  = $c;

        //$this->_em->persist($c);
        $this->_em->flush();

        self::assertTrue($e1->prePersistCallbackInvoked);
        self::assertTrue($e2->prePersistCallbackInvoked);
    }

    #[Group('DDC-54')]
    #[Group('DDC-3005')]
    public function testCascadedEntitiesLoadedInPostLoad(): void
    {
        $e1 = new LifecycleCallbackTestEntity();
        $e2 = new LifecycleCallbackTestEntity();

        $c = new LifecycleCallbackCascader();
        $this->_em->persist($c);

        $c->entities[] = $e1;
        $c->entities[] = $e2;
        $e1->cascader  = $c;
        $e2->cascader  = $c;

        $this->_em->flush();
        $this->_em->clear();
        LifecycleCallbackTestEntity::$postLoadCallbackInvoked = false; // Reset the tracking of the postLoad invocation

        $dql = <<<'DQL'
SELECT
    e, c
FROM
    Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity AS e
LEFT JOIN
    e.cascader AS c
WHERE
    e.id IN (%s, %s)
DQL;

        $entities = $this
            ->_em
            ->createQuery(sprintf($dql, $e1->getId(), $e2->getId()))
            ->getResult();

        self::assertTrue(current($entities)::$postLoadCallbackInvoked);
        self::assertTrue(current($entities)->postLoadCascaderNotNull);
        self::assertTrue(current($entities)->cascader::$postLoadCallbackInvoked);
        self::assertEquals(current($entities)->cascader->postLoadEntitiesCount, 2);
    }

    #[Group('DDC-54')]
    #[Group('DDC-3005')]
    public function testCascadedEntitiesNotLoadedInPostLoadDuringIteration(): void
    {
        $e1 = new LifecycleCallbackTestEntity();
        $e2 = new LifecycleCallbackTestEntity();

        $c = new LifecycleCallbackCascader();
        $this->_em->persist($c);

        $c->entities[] = $e1;
        $c->entities[] = $e2;
        $e1->cascader  = $c;
        $e2->cascader  = $c;

        $this->_em->flush();
        $this->_em->clear();
        LifecycleCallbackTestEntity::$postLoadCallbackInvoked = false; // Reset the tracking of the postLoad invocation
        LifecycleCallbackCascader::$postLoadCallbackInvoked   = false;

        $dql = <<<'DQL'
SELECT
    e, c
FROM
    Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity AS e
LEFT JOIN
    e.cascader AS c
WHERE
    e.id IN (%s, %s)
DQL;

        $query = $this->_em->createQuery(sprintf($dql, $e1->getId(), $e2->getId()));

        $iterableResult = iterator_to_array($query->toIterable());

        foreach ($iterableResult as $entity) {
            self::assertTrue($entity::$postLoadCallbackInvoked);
            self::assertFalse($entity->postLoadCascaderNotNull);

            break;
        }
    }

    #[Group('DDC-54')]
    #[Group('DDC-3005')]
    public function testCascadedEntitiesNotLoadedInPostLoadDuringIterationWithSimpleObjectHydrator(): void
    {
        $this->_em->persist(new LifecycleCallbackTestEntity());
        $this->_em->persist(new LifecycleCallbackTestEntity());

        $this->_em->flush();
        $this->_em->clear();
        LifecycleCallbackTestEntity::$postLoadCallbackInvoked = false; // Reset the tracking of the postLoad invocation

        $query  = $this->_em->createQuery(
            'SELECT e FROM Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity AS e',
        );
        $result = iterator_to_array($query->toIterable([], Query::HYDRATE_SIMPLEOBJECT));

        foreach ($result as $entity) {
            self::assertTrue($entity::$postLoadCallbackInvoked);
            self::assertFalse($entity->postLoadCascaderNotNull);

            break;
        }
    }

    /**
     * https://github.com/doctrine/orm/issues/6568
     */
    public function testPostLoadIsInvokedOnFetchJoinedEntities(): void
    {
        $entA = new LifecycleCallbackCascader();
        $this->_em->persist($entA);

        $entB1 = new LifecycleCallbackTestEntity();
        $entB2 = new LifecycleCallbackTestEntity();

        $entA->entities[] = $entB1;
        $entA->entities[] = $entB2;
        $entB1->cascader  = $entA;
        $entB2->cascader  = $entA;

        $this->_em->flush();
        $this->_em->clear();
        LifecycleCallbackTestEntity::$postLoadCallbackInvoked = false; // Reset the tracking of the postLoad invocation
        LifecycleCallbackCascader::$postLoadCallbackInvoked   = false;

        $dql = <<<'DQL'
SELECT
    entA, entB
FROM
    Doctrine\Tests\ORM\Functional\LifecycleCallbackCascader AS entA
LEFT JOIN
    entA.entities AS entB
WHERE
    entA.id = :entA_id
DQL;

        $fetchedA = $this
            ->_em
            ->createQuery($dql)->setParameter('entA_id', $entA->getId())
            ->getOneOrNullResult();

        self::assertTrue($fetchedA::$postLoadCallbackInvoked);
        foreach ($fetchedA->entities as $fetchJoinedEntB) {
            self::assertTrue($fetchJoinedEntB::$postLoadCallbackInvoked);
        }
    }

    public function testLifecycleCallbacksGetInherited(): void
    {
        $childMeta = $this->_em->getClassMetadata(LifecycleCallbackChildEntity::class);
        self::assertEquals(['prePersist' => [0 => 'doStuff']], $childMeta->lifecycleCallbacks);
    }

    public function testLifecycleListenerChangeUpdateChangeSet(): void
    {
        $listener = new LifecycleListenerPreUpdate();
        $this->_em->getEventManager()->addEventListener(['preUpdate'], $listener);

        $user = new LifecycleCallbackTestUser();
        $user->setName('Bob');
        $user->setValue('value');
        $this->_em->persist($user);
        $this->_em->flush();
        $this->_em->clear();

        $dql = "SELECT u FROM Doctrine\Tests\ORM\Functional\LifecycleCallbackTestUser u WHERE u.name = 'Bob'";
        $bob = $this->_em->createQuery($dql)->getSingleResult();
        $bob->setName('Alice');

        $this->_em->flush(); // preUpdate reverts Alice to Bob
        $this->_em->clear();

        $this->_em->getEventManager()->removeEventListener(['preUpdate'], $listener);

        $bob = $this->_em->createQuery($dql)->getSingleResult();

        self::assertEquals('Bob', $bob->getName());
    }

    #[Group('DDC-1955')]
    public function testLifecycleCallbackEventArgs(): void
    {
        $e = new LifecycleCallbackEventArgEntity();

        $e->value = 'foo';
        $this->_em->persist($e);
        $this->_em->flush();

        $e->value = 'var';
        $this->_em->persist($e);
        $this->_em->flush();

        $this->_em->refresh($e);

        $this->_em->remove($e);
        $this->_em->flush();

        self::assertArrayHasKey('preFlushHandler', $e->calls);
        self::assertArrayHasKey('postLoadHandler', $e->calls);
        self::assertArrayHasKey('prePersistHandler', $e->calls);
        self::assertArrayHasKey('postPersistHandler', $e->calls);
        self::assertArrayHasKey('preUpdateHandler', $e->calls);
        self::assertArrayHasKey('postUpdateHandler', $e->calls);
        self::assertArrayHasKey('preRemoveHandler', $e->calls);
        self::assertArrayHasKey('postRemoveHandler', $e->calls);

        self::assertInstanceOf(PreFlushEventArgs::class, $e->calls['preFlushHandler']);
        self::assertInstanceOf(PostLoadEventArgs::class, $e->calls['postLoadHandler']);
        self::assertInstanceOf(PrePersistEventArgs::class, $e->calls['prePersistHandler']);
        self::assertInstanceOf(PostPersistEventArgs::class, $e->calls['postPersistHandler']);
        self::assertInstanceOf(PreUpdateEventArgs::class, $e->calls['preUpdateHandler']);
        self::assertInstanceOf(PostUpdateEventArgs::class, $e->calls['postUpdateHandler']);
        self::assertInstanceOf(PreRemoveEventArgs::class, $e->calls['preRemoveHandler']);
        self::assertInstanceOf(PostRemoveEventArgs::class, $e->calls['postRemoveHandler']);
    }
}

#[Entity]
#[HasLifecycleCallbacks]
class LifecycleCallbackTestUser
{
    #[Id]
    #[Column(type: 'integer')]
    #[GeneratedValue]
    private int $id;

    #[Column(type: 'string', length: 255)]
    private string|null $value = null;

    #[Column(type: 'string', length: 255)]
    private string|null $name = null;

    public function getId(): int
    {
        return $this->id;
    }

    public function getValue(): string
    {
        return $this->value;
    }

    public function setValue(string $value): void
    {
        $this->value = $value;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function setName(string $name): void
    {
        $this->name = $name;
    }

    #[PreUpdate]
    public function testCallback(): void
    {
        $this->value = 'Hello World';
    }
}

#[Table(name: 'lc_cb_test_entity')]
#[Entity]
#[HasLifecycleCallbacks]
class LifecycleCallbackTestEntity
{
    /* test stuff */

    /** @var bool */
    public $prePersistCallbackInvoked = false;

    /** @var bool */
    public $postPersistCallbackInvoked = false;

    /** @var bool */
    public static $postLoadCallbackInvoked = false;

    /** @var bool */
    public $postLoadCascaderNotNull = false;

    /** @var bool */
    public $preFlushCallbackInvoked = false;

    #[Id]
    #[Column(type: 'integer')]
    #[GeneratedValue(strategy: 'AUTO')]
    private int $id;

    /** @var string */
    #[Column(type: 'string', nullable: true)]
    public $value;

    /** @var LifecycleCallbackCascader */
    #[ManyToOne(targetEntity: 'LifecycleCallbackCascader')]
    #[JoinColumn(name: 'cascader_id', referencedColumnName: 'id')]
    public $cascader;

    public function getId(): int
    {
        return $this->id;
    }

    public function getValue(): string
    {
        return $this->value;
    }

    #[PrePersist]
    public function doStuffOnPrePersist(): void
    {
        $this->prePersistCallbackInvoked = true;
    }

    #[PostPersist]
    public function doStuffOnPostPersist(): void
    {
        $this->postPersistCallbackInvoked = true;
    }

    #[PostLoad]
    public function doStuffOnPostLoad(): void
    {
        self::$postLoadCallbackInvoked = true;
        $this->postLoadCascaderNotNull = isset($this->cascader);
    }

    #[PreUpdate]
    public function doStuffOnPreUpdate(): void
    {
        $this->value = 'changed from preUpdate callback!';
    }

    #[PreFlush]
    public function doStuffOnPreFlush(): void
    {
        $this->preFlushCallbackInvoked = true;
    }
}

#[Table(name: 'lc_cb_test_cascade')]
#[Entity]
#[HasLifecycleCallbacks]
class LifecycleCallbackCascader
{
    /* test stuff */
    /** @var bool */
    public static $postLoadCallbackInvoked = false;

    /** @var int */
    public $postLoadEntitiesCount = 0;

    #[Id]
    #[Column(type: 'integer')]
    #[GeneratedValue(strategy: 'AUTO')]
    private int $id;

    /** @phpstan-var Collection<int, LifecycleCallbackTestEntity> */
    #[OneToMany(targetEntity: 'LifecycleCallbackTestEntity', mappedBy: 'cascader', cascade: ['persist'])]
    public $entities;

    public function __construct()
    {
        $this->entities = new ArrayCollection();
    }

    #[PostLoad]
    public function doStuffOnPostLoad(): void
    {
        self::$postLoadCallbackInvoked = true;
        $this->postLoadEntitiesCount   = count($this->entities);
    }

    public function getId(): int
    {
        return $this->id;
    }
}

#[MappedSuperclass]
#[HasLifecycleCallbacks]
class LifecycleCallbackParentEntity
{
    #[PrePersist]
    public function doStuff(): void
    {
    }
}

#[Table(name: 'lc_cb_childentity')]
#[Entity]
class LifecycleCallbackChildEntity extends LifecycleCallbackParentEntity
{
    #[Id]
    #[Column(type: 'integer')]
    #[GeneratedValue]
    private int $id;
}

class LifecycleListenerPreUpdate
{
    public function preUpdate(PreUpdateEventArgs $eventArgs): void
    {
        $eventArgs->setNewValue('name', 'Bob');
    }
}

#[Entity]
#[HasLifecycleCallbacks]
class LifecycleCallbackEventArgEntity
{
    /** @var int */
    #[Id]
    #[Column(type: 'integer')]
    #[GeneratedValue]
    public $id;

    /** @var string */
    #[Column]
    public $value;

    /** @var array<string, BaseLifecycleEventArgs> */
    public $calls = [];

    #[PostPersist]
    public function postPersistHandler(PostPersistEventArgs $event): void
    {
        $this->calls[__FUNCTION__] = $event;
    }

    #[PrePersist]
    public function prePersistHandler(PrePersistEventArgs $event): void
    {
        $this->calls[__FUNCTION__] = $event;
    }

    #[PostUpdate]
    public function postUpdateHandler(PostUpdateEventArgs $event): void
    {
        $this->calls[__FUNCTION__] = $event;
    }

    #[PreUpdate]
    public function preUpdateHandler(PreUpdateEventArgs $event): void
    {
        $this->calls[__FUNCTION__] = $event;
    }

    #[PostRemove]
    public function postRemoveHandler(PostRemoveEventArgs $event): void
    {
        $this->calls[__FUNCTION__] = $event;
    }

    #[PreRemove]
    public function preRemoveHandler(PreRemoveEventArgs $event): void
    {
        $this->calls[__FUNCTION__] = $event;
    }

    #[PreFlush]
    public function preFlushHandler(PreFlushEventArgs $event): void
    {
        $this->calls[__FUNCTION__] = $event;
    }

    #[PostLoad]
    public function postLoadHandler(PostLoadEventArgs $event): void
    {
        $this->calls[__FUNCTION__] = $event;
    }
}