vendor/symfony/ux-live-component/src/EventListener/ResetDeterministicIdSubscriber.php line 51

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\UX\LiveComponent\EventListener;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\UX\LiveComponent\Twig\DeterministicTwigIdCalculator;
  13. use Symfony\UX\TwigComponent\ComponentStack;
  14. use Symfony\UX\TwigComponent\Event\PostRenderEvent;
  15. /**
  16.  * Resets the "deterministic id calculator" after each full "parent" component has finished rendering.
  17.  *
  18.  * When a component (and all of its children) have finished rendering, this resets
  19.  * the internal "counter" on the id calculator. Suppose this situation:
  20.  *
  21.  *      Parent Component A
  22.  *          Child Component 1
  23.  *
  24.  *      Parent Component B
  25.  *          Child Component 1
  26.  *
  27.  * If we didn't reset, the deterministic id of the two "Child Component 1" objects
  28.  * would be *different*: the first would end with "-0" and the second with "-1".
  29.  * This is a problem because when "Parent Component B" renders later via Ajax,
  30.  * its child will generate an id ending in "-0", since there wasn't a previous
  31.  * Child Component 1 that rendered during that request.
  32.  *
  33.  * @author Ryan Weaver <ryan@symfonycasts.com>
  34.  *
  35.  * @experimental
  36.  *
  37.  * @internal
  38.  */
  39. final class ResetDeterministicIdSubscriber implements EventSubscriberInterface
  40. {
  41.     public function __construct(
  42.         private DeterministicTwigIdCalculator $idCalculator,
  43.         private ComponentStack $componentStack
  44.     ) {
  45.     }
  46.     public function onPostRender(): void
  47.     {
  48.         if (!$this->componentStack->getCurrentComponent()) {
  49.             $this->idCalculator->reset();
  50.         }
  51.     }
  52.     public static function getSubscribedEvents(): array
  53.     {
  54.         return [PostRenderEvent::class => 'onPostRender'];
  55.     }
  56. }