-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryBudgetTest.php
More file actions
822 lines (727 loc) · 38.1 KB
/
Copy pathQueryBudgetTest.php
File metadata and controls
822 lines (727 loc) · 38.1 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
<?php
declare(strict_types=1);
namespace Tmi\TranslationBundle\Test\Performance;
use Doctrine\ORM\UnitOfWork;
use Symfony\Component\Console\Tester\CommandTester;
use Tmi\TranslationBundle\Command\AdoptRootCommand;
use Tmi\TranslationBundle\Command\SyncSharedTranslationsCommand;
use Tmi\TranslationBundle\Command\TranslationDoctorCommand;
use Tmi\TranslationBundle\Doctrine\LocaleVariantFinder;
use Tmi\TranslationBundle\Doctrine\Root\RootAdopterRegistry;
use Tmi\TranslationBundle\Doctrine\Root\RootCheckAggregator;
use Tmi\TranslationBundle\Doctrine\SharedDriftScanner;
use Tmi\TranslationBundle\Doctrine\SharedValueSynchronizer;
use Tmi\TranslationBundle\Doctrine\TranslatableEntityLocator;
use Tmi\TranslationBundle\Fixtures\Entity\Bughunt\Node;
use Tmi\TranslationBundle\Fixtures\Entity\Root\Estate;
use Tmi\TranslationBundle\Fixtures\Entity\Root\EstateA;
use Tmi\TranslationBundle\Fixtures\Entity\Root\Listing;
use Tmi\TranslationBundle\Fixtures\Entity\Root\ListingA;
use Tmi\TranslationBundle\Fixtures\Entity\Scalar\Scalar;
use Tmi\TranslationBundle\Fixtures\Entity\SharedBackReference\SharedBackReferenceChild;
use Tmi\TranslationBundle\Fixtures\Entity\SharedBackReference\SharedBackReferenceParent;
use Tmi\TranslationBundle\Fixtures\Entity\Translatable\TranslatableManyToManyBidirectionalChild;
use Tmi\TranslationBundle\Fixtures\Entity\Translatable\TranslatableManyToManyBidirectionalParent;
use Tmi\TranslationBundle\Fixtures\Entity\Translatable\TranslatableManyToManyUnidirectionalChild;
use Tmi\TranslationBundle\Fixtures\Entity\Translatable\TranslatableManyToManyUnidirectionalParent;
use Tmi\TranslationBundle\Fixtures\Entity\Translatable\TranslatableManyToOneBidirectionalChild;
use Tmi\TranslationBundle\Fixtures\Entity\Translatable\TranslatableOneToManyBidirectionalParent;
use Tmi\TranslationBundle\Test\IntegrationTestCase;
use Tmi\TranslationBundle\Test\Support\QueryCounter;
use Tmi\TranslationBundle\Test\Support\Root\EstateRootAdopter;
use Tmi\TranslationBundle\Translation\Cache\InMemoryTranslationCache;
use Tmi\TranslationBundle\Translation\LocaleCompletenessResolver;
use Tmi\TranslationBundle\ValueObject\Tuuid;
/**
* Turns the performance claims WP17's README table makes into assertions: each
* test here is the one a README/llms.md number is allowed to cite (Leitplanke
* 7 -- no performance number without a test enforcing it).
*
* Counts come from {@see QueryCounter}, the PSR-3 logger wired into
* TestKernel behind DBAL's own logging middleware -- one debug log per
* executed statement or query, transaction control excluded (see its
* docblock). Every assertion below is exact (assertSame), not a ceiling.
*/
final class QueryBudgetTest extends IntegrationTestCase
{
public function testFindTranslatableEntityUnderActiveFilterIsOneQuery(): void
{
$entity = new Scalar()->setLocale('en_US')->setTitle('EN');
$this->entityManager()->persist($entity);
$this->entityManager()->flush();
$id = $entity->getId();
$this->entityManager()->clear();
$this->counter()->reset();
$found = $this->entityManager()->find(Scalar::class, $id);
self::assertNotNull($found);
self::assertSame(1, $this->counter()->count());
}
/**
* translate() of an entity whose target-locale variant already exists:
* EntityTranslator::processTranslation() finds it via its own preload()
* call and returns straight from the cache, never reaching the handler
* chain at all.
*/
public function testTranslateEntityWithExistingVariantIsOneQueryAndNoInserts(): void
{
$tuuid = Tuuid::generate();
$en = new Scalar()->setTuuid($tuuid)->setLocale('en_US')->setTitle('EN');
$de = new Scalar()->setTuuid($tuuid)->setLocale('de_DE')->setTitle('DE');
$this->entityManager()->persist($en);
$this->entityManager()->persist($de);
$this->entityManager()->flush();
$this->entityManager()->clear();
$this->counter()->reset();
$result = $this->translator()->translate($en, 'de_DE');
self::assertSame('de_DE', $result->getLocale());
self::assertSame(1, $this->counter()->count());
// The identity check above already proves no new row was created for
// this Tuuid; confirm no INSERT reached the database either.
self::assertSame(2, $this->countScalarRows());
}
/**
* The mechanism preload() exists for: K entities of the same class, each
* already translated, cost K individual lookup queries when translate()d
* one at a time -- each one's own internal preload() call is a separate
* single-Tuuid query, since nothing warmed its cache entry yet. Calling
* preload() once with the whole batch first turns that into a single
* query for the class (LocaleVariantFinder::findLocaleVariantsBatch()),
* after which every translate() in the loop is a pure cache hit.
*/
public function testPreloadCollapsesPerEntityLookupsIntoOneQueryPerClass(): void
{
$baseline = $this->createTranslatedScalarPairs(3);
$this->counter()->reset();
foreach ($baseline as $en) {
$this->translator()->translate($en, 'de_DE');
}
self::assertSame(3, $this->counter()->count(), 'one lookup query per entity, without preload()');
$preloaded = $this->createTranslatedScalarPairs(3);
$this->counter()->reset();
$this->translator()->preload($preloaded, 'de_DE');
foreach ($preloaded as $en) {
$this->translator()->translate($en, 'de_DE');
}
self::assertSame(1, $this->counter()->count(), 'one batched query for the whole class, with preload()');
}
/**
* A parent entity (no existing target-locale variant, so it must be
* created) with K already-translated children reachable through a
* bidirectional OneToMany: BidirectionalOneToManyHandler::translate()
* preloads the whole children collection in one batched query per
* child class before looping, instead of leaving each child's own
* translate() call to query for itself (BidirectionalOneToManyHandler
* recurses through EntityTranslator::processTranslation(), not around
* it) -- so K already-translated children of one class cost one query
* total, not K. The parent itself costs exactly one more: its own
* preload() lookup (a miss). TranslatableEntityHandler, reached once
* that miss falls through to the handler chain, does not look for an
* existing variant a second time -- existence is resolved exactly
* once, by processTranslation()'s own preload()-then-cache-check,
* before any handler runs (see TranslatableEntityHandler's class
* docblock).
*/
public function testTranslateWithExistingChildVariantsCostsOneQueryPerChildClass(): void
{
$parentTuuid = Tuuid::generate();
$parent = new TranslatableOneToManyBidirectionalParent()->setTuuid($parentTuuid)->setLocale('en_US')->setTitle('Parent EN');
$childCount = 3;
for ($i = 0; $i < $childCount; ++$i) {
$childTuuid = Tuuid::generate();
$childEn = new TranslatableManyToOneBidirectionalChild()->setTuuid($childTuuid)->setLocale('en_US')->setTitle('Child EN '.$i);
$childDe = new TranslatableManyToOneBidirectionalChild()->setTuuid($childTuuid)->setLocale('de_DE')->setTitle('Child DE '.$i);
$childEn->setParentSimple($parent);
$parent->getSimpleChildren()->add($childEn);
$this->entityManager()->persist($childEn);
$this->entityManager()->persist($childDe);
}
$this->entityManager()->persist($parent);
$this->entityManager()->flush();
$this->counter()->reset();
$translated = $this->translator()->translate($parent, 'de_DE');
self::assertInstanceOf(TranslatableOneToManyBidirectionalParent::class, $translated);
self::assertSame('de_DE', $translated->getLocale());
self::assertCount($childCount, $translated->getSimpleChildren());
// 1 (parent's own preload(), a miss) + 1 (one batched
// BidirectionalOneToManyHandler preload() query covering all K
// children, since they are all the same class) -- see the method
// docblock above.
self::assertSame(2, $this->counter()->count());
}
/**
* Same shape as testTranslateWithExistingChildVariantsCostsOneQueryPerChildClass(),
* except none of the K children have a de_DE variant yet: the upfront
* batched preload() still costs exactly one query for the whole class --
* it looks up all K children and finds nothing, remembering every one of
* their Tuuids as a known miss for (tuuid, de_DE) (see
* EntityTranslator::preload()'s docblock). Each child's own internal
* preload() then finds its Tuuid already remembered and skips its query
* entirely, so TranslatableEntityHandler clones every child without
* asking the database again. The only queries before flush() are
* therefore the parent's own preload() miss and the one batched children
* lookup -- 2, not 1 + K. flush() then inserts every row that did not
* already exist: the parent and all K children, K + 1 INSERTs.
*/
public function testTranslateWithNewChildVariantsCostsTwoQueriesAndKPlusOneInserts(): void
{
$parent = new TranslatableOneToManyBidirectionalParent()->setTuuid(Tuuid::generate())->setLocale('en_US')->setTitle('Parent EN');
$childCount = 3;
for ($i = 0; $i < $childCount; ++$i) {
$child = new TranslatableManyToOneBidirectionalChild()->setTuuid(Tuuid::generate())->setLocale('en_US')->setTitle('Child EN '.$i);
$child->setParentSimple($parent);
$parent->getSimpleChildren()->add($child);
$this->entityManager()->persist($child);
}
$this->entityManager()->persist($parent);
$this->entityManager()->flush();
$this->counter()->reset();
$translated = $this->translator()->getOrTranslate($parent, 'de_DE');
self::assertInstanceOf(TranslatableOneToManyBidirectionalParent::class, $translated);
self::assertCount($childCount, $translated->getSimpleChildren());
self::assertSame(2, $this->counter()->count(), '1 parent preload miss + 1 batched children lookup, regardless of K');
$this->counter()->reset();
$this->entityManager()->flush();
self::assertSame($childCount + 1, $this->counter()->count(), 'K child inserts + 1 parent insert, no further lookups');
self::assertNotNull($translated->getId());
foreach ($translated->getSimpleChildren() as $child) {
self::assertNotNull($child->getId());
}
}
/**
* A mixed collection: some children already have a de_DE variant,
* others do not. The upfront batched preload() still costs exactly one
* query for the whole class -- findLocaleVariantsBatch() is one query
* regardless of how many of the Tuuids it actually finds -- and the
* parent's own preload() miss is the other, so the budget stays at 2
* exactly like the all-existing and all-new cases above. flush() then
* inserts a row only for what did not already exist -- the new parent
* and the missing children; the existing children are reused (same
* managed instance, same id), so the child table grows by exactly
* $newCount rows, never $newCount + $existingCount. (The reused
* children still cost an UPDATE apiece, fixing their back-reference to
* the newly created parent -- since that parent did not exist before
* this call, no row could have pointed at it yet -- which is why this
* test measures the row-count delta rather than the flush()'s raw
* statement count.).
*/
public function testTranslateWithMixedChildVariantsCostsTwoQueriesAndInsertsOnlyTheMissing(): void
{
$parent = new TranslatableOneToManyBidirectionalParent()->setTuuid(Tuuid::generate())->setLocale('en_US')->setTitle('Parent EN');
$existingCount = 2;
$newCount = 2;
$existingDeChildren = [];
for ($i = 0; $i < $existingCount; ++$i) {
$tuuid = Tuuid::generate();
$childEn = new TranslatableManyToOneBidirectionalChild()->setTuuid($tuuid)->setLocale('en_US')->setTitle('Existing EN '.$i);
$childDe = new TranslatableManyToOneBidirectionalChild()->setTuuid($tuuid)->setLocale('de_DE')->setTitle('Existing DE '.$i);
$childEn->setParentSimple($parent);
$parent->getSimpleChildren()->add($childEn);
$this->entityManager()->persist($childEn);
$this->entityManager()->persist($childDe);
$existingDeChildren[] = $childDe;
}
for ($i = 0; $i < $newCount; ++$i) {
$child = new TranslatableManyToOneBidirectionalChild()->setTuuid(Tuuid::generate())->setLocale('en_US')->setTitle('New EN '.$i);
$child->setParentSimple($parent);
$parent->getSimpleChildren()->add($child);
$this->entityManager()->persist($child);
}
$this->entityManager()->persist($parent);
$this->entityManager()->flush();
$this->counter()->reset();
$translated = $this->translator()->getOrTranslate($parent, 'de_DE');
self::assertInstanceOf(TranslatableOneToManyBidirectionalParent::class, $translated);
self::assertCount($existingCount + $newCount, $translated->getSimpleChildren());
self::assertSame(2, $this->counter()->count(), '1 parent preload miss + 1 batched children lookup covering both hits and misses');
foreach ($existingDeChildren as $existingDe) {
self::assertTrue(
$translated->getSimpleChildren()->contains($existingDe),
'the existing de_DE variant is reused (same managed instance, same id), never duplicated',
);
}
$childRowsBefore = $this->countChildRows();
$this->entityManager()->flush();
$childRowsAfter = $this->countChildRows();
self::assertSame(
$newCount,
$childRowsAfter - $childRowsBefore,
'the child table grows by exactly the missing count -- the existing variants were reused, not duplicated',
);
}
/**
* Same mechanism as testTranslateWithExistingChildVariantsCostsOneQueryPerChildClass(),
* for a bidirectional ManyToMany collection: BidirectionalManyToManyHandler::
* translateCollection() preloads the whole collection in one batched
* query per item class before looping, instead of leaving each item's
* own translate() call to query for itself.
*/
public function testTranslateManyToManyBidirectionalWithExistingItemsCostsOneQueryPerItemClass(): void
{
$parent = new TranslatableManyToManyBidirectionalParent()->setTuuid(Tuuid::generate())->setLocale('en_US')->setTitle('Parent EN');
$itemCount = 3;
for ($i = 0; $i < $itemCount; ++$i) {
$itemTuuid = Tuuid::generate();
$itemEn = new TranslatableManyToManyBidirectionalChild()->setTuuid($itemTuuid)->setLocale('en_US');
$itemDe = new TranslatableManyToManyBidirectionalChild()->setTuuid($itemTuuid)->setLocale('de_DE');
$parent->addSimpleChild($itemEn);
$this->entityManager()->persist($itemEn);
$this->entityManager()->persist($itemDe);
}
$this->entityManager()->persist($parent);
$this->entityManager()->flush();
$this->counter()->reset();
$translated = $this->translator()->translate($parent, 'de_DE');
self::assertInstanceOf(TranslatableManyToManyBidirectionalParent::class, $translated);
self::assertCount($itemCount, $translated->getSimpleChildren());
// 1 (parent's own preload(), a miss) + 1 (one batched
// BidirectionalManyToManyHandler preload() query covering all K
// items, since they are all the same class).
self::assertSame(2, $this->counter()->count());
}
/**
* A unidirectional ManyToMany collection mixing translatable items
* (some already translated) with a non-translatable one:
* UnidirectionalManyToManyHandler::translateCollection() preloads the
* whole collection in one batched query before looping -- preload()
* ignores the non-translatable item on its own, so it costs nothing
* extra and is preserved in the result untouched.
*/
public function testTranslateUnidirectionalManyToManyWithMixedItemsCostsOneBatchedLookup(): void
{
$parent = new TranslatableManyToManyUnidirectionalParent()->setTuuid(Tuuid::generate())->setLocale('en_US');
$itemCount = 3;
for ($i = 0; $i < $itemCount; ++$i) {
$itemTuuid = Tuuid::generate();
$itemEn = new TranslatableManyToManyUnidirectionalChild()->setTuuid($itemTuuid)->setLocale('en_US')->setName('Item EN '.$i);
$itemDe = new TranslatableManyToManyUnidirectionalChild()->setTuuid($itemTuuid)->setLocale('de_DE')->setName('Item DE '.$i);
$parent->addSimpleChild($itemEn);
$this->entityManager()->persist($itemEn);
$this->entityManager()->persist($itemDe);
}
$this->entityManager()->persist($parent);
$this->entityManager()->flush();
// Appended after the flush establishing the existing de_DE variants
// above, directly on the still-plain (never reloaded) ArrayCollection
// -- in-memory only, never itself flushed, so a non-entity object can
// stand in for a non-translatable item (tags, categories) without
// needing a second, differently-typed join table. The collection
// enforces nothing at runtime (generics are PHPDoc-only); only
// PHPStan's own reading of getSimpleChildren()'s declared
// `Collection<int, ...Child>` return type objects to a stdClass
// going in, hence the two targeted ignores below.
$nonTranslatable = new \stdClass();
// @phpstan-ignore argument.type
$parent->getSimpleChildren()->add($nonTranslatable);
$this->counter()->reset();
$translated = $this->translator()->translate($parent, 'de_DE');
self::assertInstanceOf(TranslatableManyToManyUnidirectionalParent::class, $translated);
self::assertCount($itemCount + 1, $translated->getSimpleChildren());
// @phpstan-ignore staticMethod.impossibleType
self::assertTrue($translated->getSimpleChildren()->contains($nonTranslatable), 'the non-translatable item is preserved as-is');
// 1 (parent's own preload(), a miss) + 1 (one batched
// UnidirectionalManyToManyHandler preload() query covering the K
// translatable items; the stdClass is never looked up).
self::assertSame(2, $this->counter()->count());
}
public function testResolveBatchOfManyTuuidsIsOneQuery(): void
{
$tuuids = [];
for ($i = 0; $i < 100; ++$i) {
$tuuid = Tuuid::generate();
$tuuids[] = $tuuid;
$this->entityManager()->persist(new Scalar()->setTuuid($tuuid)->setLocale('en_US')->setTitle('EN '.$i));
}
$this->entityManager()->flush();
$this->entityManager()->clear();
$finder = new LocaleVariantFinder($this->entityManager());
$resolver = new LocaleCompletenessResolver(
$this->entityManager(),
new SharedValueSynchronizer($this->entityManager(), $finder, $this->attributeHelper()),
'en_US',
['en_US', 'de_DE', 'it_IT'],
$finder,
);
$this->counter()->reset();
$result = $resolver->resolveBatch(Scalar::class, $tuuids);
self::assertCount(100, $result);
self::assertSame(1, $this->counter()->count());
}
public function testFindAllLocaleVariantsBatchIsOneQuery(): void
{
$tuuids = [];
for ($i = 0; $i < 5; ++$i) {
$tuuid = Tuuid::generate();
$tuuids[] = $tuuid;
$this->entityManager()->persist(new Scalar()->setTuuid($tuuid)->setLocale('en_US')->setTitle('EN '.$i));
$this->entityManager()->persist(new Scalar()->setTuuid($tuuid)->setLocale('de_DE')->setTitle('DE '.$i));
}
$this->entityManager()->flush();
$this->entityManager()->clear();
$finder = new LocaleVariantFinder($this->entityManager());
$this->counter()->reset();
$result = $finder->findAllLocaleVariantsBatch(Scalar::class, $tuuids);
self::assertCount(5, $result);
self::assertSame(1, $this->counter()->count());
}
public function testDoctorQueriesPerRootClass(): void
{
$this->entityManager()->persist(new Scalar()->setLocale('en_US')->setTitle('Lonely'));
$this->entityManager()->flush();
$command = new TranslationDoctorCommand(
$this->entityManager(),
new TranslatableEntityLocator($this->entityManager()),
new LocaleVariantFinder($this->entityManager()),
['en_US', 'de_DE', 'it_IT'],
'en_US',
);
$tester = new CommandTester($command);
// --entity restricts the scan to exactly one root class, so the
// count below is the per-class budget itself, independent of how
// many translatable fixtures the test suite happens to declare: one
// grouped query covering the untranslated/orphan/incomplete/duplicate
// classes together (TranslationDoctorCommand::inspect(), a single
// GROUP BY tuuid, locale) plus inspectNullTuuid()'s own query.
$this->counter()->reset();
$tester->execute(['--entity' => Scalar::class]);
self::assertSame(2, $this->counter()->count());
}
/**
* The recommended import shape: preload() once for the whole batch,
* then getOrTranslate() + flush() per entity. Every Tuuid here is brand
* new (no existing de_DE variant), so the upfront preload() pays one
* query that finds nothing and remembers every Tuuid as a known miss
* for (tuuid, de_DE) (see EntityTranslator::preload()'s docblock).
* Each entity's own translate() call still runs its internal preload()
* for that one entity, but finds its Tuuid already remembered as a
* miss and skips the query entirely instead of asking the database the
* same question again -- and TranslatableEntityHandler, reached once
* that (remembered, query-free) miss falls through to the handler
* chain, does not look for an existing variant either (see its class
* docblock): existence for a Tuuid this preload() batch already ruled
* out is never re-asked. The only queries left are the upfront one and
* the N inserts flush() issues -- 1 + N, not 1 + 3N.
*
* preload() pays off twice over on a re-run of the same import: every
* Tuuid is now an actual cache hit (not just a remembered miss), so the
* upfront preload() call itself is the only query for the whole batch
* (see testPreloadCollapsesPerEntityLookupsIntoOneQueryPerClass()).
*/
public function testImportWithPreloadCostsOneLookupPlusNInserts(): void
{
$entities = [];
$n = 4;
for ($i = 0; $i < $n; ++$i) {
$entities[] = new Scalar()->setTuuid(Tuuid::generate())->setLocale('en_US')->setTitle('Import '.$i);
}
$this->counter()->reset();
$this->translator()->preload($entities, 'de_DE');
foreach ($entities as $entity) {
$this->translator()->getOrTranslate($entity, 'de_DE');
}
$this->entityManager()->flush();
// 1 (the upfront batched preload(), a miss for every Tuuid, remembered) +
// N (INSERT on flush) -- see the method docblock above.
self::assertSame(1 + $n, $this->counter()->count());
}
/**
* A cache hit surviving an EntityManager::clear() (import batches, long-running
* workers) must not suppress preload()'s query: the entry still sits in the
* cache holding an identifier, but the UnitOfWork no longer tracks it, and a
* later persist() on that stale instance would silently re-insert it as a new
* row instead of reusing the existing one (see EntityTranslator::preload()'s
* docblock, and EntityTranslatorCacheIdentityTest for the same rule applied to
* processTranslation()'s own cache-hit sites).
*/
public function testPreloadRequeriesADetachedCacheHitExactlyOnce(): void
{
$tuuid = Tuuid::generate();
$en = new Scalar()->setTuuid($tuuid)->setLocale('en_US')->setTitle('EN');
$this->entityManager()->persist($en);
$this->entityManager()->flush();
// Prime the cache with a managed de_DE instance.
$de = $this->translator()->getOrTranslate($en, 'de_DE');
$this->entityManager()->flush();
self::assertInstanceOf(Scalar::class, $de);
$deId = $de->getId();
self::assertNotNull($deId);
// clear() detaches every managed instance, including the de_DE clone still
// sitting in the cache.
$this->entityManager()->clear();
$this->counter()->reset();
$this->translator()->preload([$en], 'de_DE');
self::assertSame(1, $this->counter()->count(), 'a detached cache hit must not suppress the preload query');
$cache = self::getContainer()->get(InMemoryTranslationCache::class);
self::assertInstanceOf(InMemoryTranslationCache::class, $cache);
$cached = $cache->get((string) $tuuid, 'de_DE');
self::assertInstanceOf(Scalar::class, $cached);
self::assertSame(
UnitOfWork::STATE_MANAGED,
$this->entityManager()->getUnitOfWork()->getEntityState($cached),
'preload() must overwrite the detached hit with a freshly resolved, managed instance',
);
$again = $this->translator()->getOrTranslate($en, 'de_DE');
$this->entityManager()->flush();
self::assertInstanceOf(Scalar::class, $again);
self::assertSame($deId, $again->getId(), 'must reuse the existing row rather than mint a new one');
self::assertSame(2, $this->countScalarRows());
}
/**
* reset() (tagged kernel.reset in services.yaml) forgets every (tuuid, locale)
* pair preload() has recorded as a miss -- see EntityTranslator::preload()'s
* docblock. Without a reset() in between, translate()'s own internal preload()
* finds this same Tuuid already remembered as a miss and skips its query
* entirely -- exactly the mechanism that keeps the import in
* testImportWithPreloadCostsOneLookupPlusNInserts() at 1 + N instead of 1 + 3N.
* reset() clears that memory, so the miss is asked about again.
*/
public function testResetForgetsAKnownMissSoTranslateQueriesAgain(): void
{
$entity = new Scalar()->setTuuid(Tuuid::generate())->setLocale('en_US')->setTitle('Reset');
// Establishes a known miss for (tuuid, de_DE) without resolving it --
// preload() alone never creates a translation, so nothing forgets the
// miss on its own the way runHandlers() would after a translate() call.
$this->translator()->preload([$entity], 'de_DE');
$this->translator()->reset();
$this->counter()->reset();
$this->translator()->translate($entity, 'de_DE');
self::assertSame(1, $this->counter()->count(), 'reset() must forget the known miss, so translate()\'s own internal preload() queries again instead of skipping it');
}
/**
* `tmi:translation:adopt-root --check`'s roots-without-rows count (5.1): ONE
* NOT EXISTS query per root reference, whatever the table sizes.
*/
public function testRootsWithoutRowsIsOneQueryPerRootReference(): void
{
$tuuid = Tuuid::generate();
$root = new ListingA();
$root->adoptTuuid($tuuid);
$orphan = new ListingA();
$orphan->mintTuuid();
$this->entityManager()->persist($root);
$this->entityManager()->persist($orphan);
$this->entityManager()->persist(new EstateA()->setTuuid($tuuid)->setLocale('en_US')->setListing($root));
$this->entityManager()->persist(new EstateA()->setTuuid($tuuid)->setLocale('de_DE')->setListing($root));
$this->entityManager()->flush();
$this->entityManager()->clear();
$aggregator = new RootCheckAggregator($this->entityManager(), new LocaleVariantFinder($this->entityManager()));
$this->counter()->reset();
$count = $aggregator->countRootsWithoutRows(Listing::class, Estate::class, 'listing');
self::assertSame(1, $count);
self::assertSame(1, $this->counter()->count());
}
/**
* A child reached through its parent's OneToMany -- its back-reference declared
* #[SharedAmongstTranslations] -- is cached under its own (tuuid, locale) like any
* other translation, so translating it on its own afterwards is a cache hit.
* Negative proof against 5.1: the shared early return in runHandlers() skipped the
* cache for exactly this shape, and the same call cost 1 lookup query.
*/
public function testTranslateAChildAlreadyClonedThroughItsParentCostsNoQuery(): void
{
$child = new SharedBackReferenceChild()->setLocale('en_US')->setTitle('Day 1 EN');
$parent = new SharedBackReferenceParent()->setLocale('en_US')->setTitle('Itinerary EN')->addChild($child);
$this->entityManager()->persist($parent);
$this->entityManager()->flush();
$translatedParent = $this->translator()->translateAndPersist($parent, 'de_DE');
$this->entityManager()->flush();
self::assertInstanceOf(SharedBackReferenceParent::class, $translatedParent);
$this->counter()->reset();
$translatedChild = $this->translator()->translate($child, 'de_DE');
self::assertSame(0, $this->counter()->count(), 'the child clone is a cache hit, no lookup');
self::assertSame($translatedParent->getChildren()->first(), $translatedChild);
}
/**
* A read-only sync-shared run over one class is the stream and nothing else:
* shared-property discovery is reflection, group comparison is in memory, and
* GroupBatch flushes nothing in --dry-run / --check.
*/
public function testSyncSharedDryRunCostsOneQueryPerClass(): void
{
$this->seedScalarGroups(5, drifted: 3);
$this->counter()->reset();
$tester = $this->syncShared(['--dry-run' => true, '--entity' => Scalar::class]);
self::assertStringContainsString('3 translation(s) would be updated', $tester->getDisplay());
self::assertSame(1, $this->counter()->count());
}
/**
* Write mode adds exactly one UPDATE per drifted sibling row: the stream, then
* GroupBatch's flush every 10 groups -- no re-read, no per-row SELECT.
*/
public function testSyncSharedWriteCostsTheStreamPlusOneUpdatePerDriftedRow(): void
{
$this->seedScalarGroups(5, drifted: 3);
$this->counter()->reset();
$tester = $this->syncShared(['--entity' => Scalar::class]);
self::assertStringContainsString('3 translation(s) updated', $tester->getDisplay());
self::assertSame(1 + 3, $this->counter()->count());
}
/**
* adopt-root --dry-run / --check over G complete groups: the stream -- with the
* root reference fetch-joined, since a root that is an STI/JOINED hierarchy can
* never be a lazy proxy and Doctrine would otherwise find() it once per row --
* and the roots-without-rows NOT EXISTS count. Independent of G: 25 groups, 2.
* Negative proof against 5.1: 27 (one root load per group).
*/
public function testAdoptRootCheckCostsTheStreamPlusTheRootsWithoutRowsCount(): void
{
for ($i = 0; $i < 25; ++$i) {
$this->seedEstateGroup();
}
self::assertSame(0, $this->adoptRoot([])->getStatusCode());
$this->entityManager()->clear();
$this->counter()->reset();
$tester = $this->adoptRoot(['--check' => true]);
self::assertSame(0, $tester->getStatusCode());
self::assertSame(1 + 1, $this->counter()->count());
self::assertSame(0, $this->entityManager()->getUnitOfWork()->size(), 'rows and roots detached, nothing left managed');
}
/**
* adopt-root write mode over K new groups of R rows in total: pass 1 streams and
* classifies (no root to load), pass 2 streams again and adopts -- K root INSERTs
* and R row UPDATEs on the batch flush -- then the roots-without-rows count.
* 3 groups of 2 rows: 1 + 1 + 3 + 6 + 1.
*/
public function testAdoptRootWriteCostsTwoStreamsPlusOneInsertPerGroupPlusOneUpdatePerRow(): void
{
for ($i = 0; $i < 3; ++$i) {
$this->seedEstateGroup();
}
$this->counter()->reset();
$tester = $this->adoptRoot([]);
self::assertStringContainsString('3 group(s) adopted', $tester->getDisplay());
self::assertSame(1 + 1 + 3 + 6 + 1, $this->counter()->count());
}
/**
* A self-referential bidirectional tree (Node::$parent inversedBy $children):
* translating a leaf walks up to its parent (the direct ManyToOne form) and, from
* there, back down through the parent's collection to every sibling. Each Node's
* own lookup is a preload() miss and the parent's children collection is one
* batched lookup: the leaf, its parent, the parent's own parent lookup (null, no
* query) and one batched children query. Pinned here as a regression number for
* the WP4 self-reference fix (#54).
*/
public function testTranslateALeafOfASelfReferentialTreeCostsThreeQueries(): void
{
$root = new Node('root');
$child = new Node('child');
$other = new Node('other');
$root->setLocale('en_US');
$child->setLocale('en_US');
$other->setLocale('en_US');
$root->addChild($child);
$root->addChild($other);
$this->entityManager()->persist($root);
$this->entityManager()->persist($child);
$this->entityManager()->persist($other);
$this->entityManager()->flush();
$this->counter()->reset();
$translated = $this->translator()->translate($child, 'de_DE');
self::assertInstanceOf(Node::class, $translated);
self::assertSame('de_DE', $translated->getParent()?->getLocale());
self::assertSame(3, $this->counter()->count());
}
private function counter(): QueryCounter
{
$counter = self::getContainer()->get(QueryCounter::class);
self::assertInstanceOf(QueryCounter::class, $counter);
return $counter;
}
private function countScalarRows(): int
{
/** @var int|string $count */
$count = $this->entityManager()->createQueryBuilder()
->select('COUNT(t.id)')
->from(Scalar::class, 't')
->getQuery()
->getSingleScalarResult();
return (int) $count;
}
private function countChildRows(): int
{
/** @var int|string $count */
$count = $this->entityManager()->createQueryBuilder()
->select('COUNT(t.id)')
->from(TranslatableManyToOneBidirectionalChild::class, 't')
->getQuery()
->getSingleScalarResult();
return (int) $count;
}
/**
* @return list<Scalar>
*/
private function createTranslatedScalarPairs(int $count): array
{
$entities = [];
for ($i = 0; $i < $count; ++$i) {
$tuuid = Tuuid::generate();
$en = new Scalar()->setTuuid($tuuid)->setLocale('en_US')->setTitle('EN '.$i);
$de = new Scalar()->setTuuid($tuuid)->setLocale('de_DE')->setTitle('DE '.$i);
$this->entityManager()->persist($en);
$this->entityManager()->persist($de);
$entities[] = $en;
}
$this->entityManager()->flush();
$this->entityManager()->clear();
return $entities;
}
/**
* @param int $drifted how many of the groups get a stale de_DE shared value
*/
private function seedScalarGroups(int $groups, int $drifted): void
{
for ($i = 0; $i < $groups; ++$i) {
$tuuid = Tuuid::generate();
$this->entityManager()->persist(new Scalar()->setTuuid($tuuid)->setLocale('en_US')->setTitle('EN')->setShared('shared '.$i));
$this->entityManager()->persist(new Scalar()->setTuuid($tuuid)->setLocale('de_DE')->setTitle('DE')->setShared($i < $drifted ? 'stale '.$i : 'shared '.$i));
}
$this->entityManager()->flush();
$this->entityManager()->clear();
}
private function seedEstateGroup(): void
{
$tuuid = Tuuid::generate();
$this->entityManager()->persist(new EstateA()->setTuuid($tuuid)->setLocale('en_US')->setTitle('EN'));
$this->entityManager()->persist(new EstateA()->setTuuid($tuuid)->setLocale('de_DE')->setTitle('DE'));
$this->entityManager()->flush();
$this->entityManager()->clear();
}
/**
* @param array<string, bool|string> $input
*/
private function syncShared(array $input): CommandTester
{
$synchronizer = self::getContainer()->get('test.shared_value_synchronizer');
self::assertInstanceOf(SharedValueSynchronizer::class, $synchronizer);
$finder = new LocaleVariantFinder($this->entityManager());
$tester = new CommandTester(new SyncSharedTranslationsCommand(
$this->entityManager(),
new TranslatableEntityLocator($this->entityManager()),
$finder,
$synchronizer,
new SharedDriftScanner($this->entityManager(), $finder, $synchronizer, 'en_US'),
'en_US',
));
$tester->execute($input, ['interactive' => false]);
return $tester;
}
/**
* @param array<string, bool|string> $input
*/
private function adoptRoot(array $input): CommandTester
{
$registry = new RootAdopterRegistry();
$adopter = new EstateRootAdopter();
$registry->addAdopter($adopter, $adopter->getTranslatableClass());
$finder = new LocaleVariantFinder($this->entityManager());
$tester = new CommandTester(new AdoptRootCommand(
$this->entityManager(),
$finder,
$registry,
new RootCheckAggregator($this->entityManager(), $finder),
$this->attributeHelper(),
new TranslatableEntityLocator($this->entityManager()),
));
$tester->execute([...$input, '--entity' => Estate::class]);
return $tester;
}
}