478 lines
22 KiB
PHP
478 lines
22 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Symfony\EventCatalog;
|
|
use JumPHP\Ide\Symfony\EventCode;
|
|
use JumPHP\Ide\Symfony\EventListeners;
|
|
use JumPHP\Ide\Symfony\PhpSources;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/** The Events window: the events found (framework, project, dispatches), the listeners and their order, the code it writes. */
|
|
final class SymfonyEventsTest extends TestCase
|
|
{
|
|
private static function event(string $name): array
|
|
{
|
|
foreach (EventCatalog::all() as $e) {
|
|
if ($e['name'] === $name) {
|
|
return $e;
|
|
}
|
|
}
|
|
self::fail("no event $name");
|
|
}
|
|
|
|
private static function project(): PhpSources
|
|
{
|
|
return PhpSources::fromStrings([
|
|
'src/Event/OrderPlacedEvent.php' => <<<'PHP'
|
|
<?php
|
|
namespace App\Event;
|
|
use Symfony\Contracts\EventDispatcher\Event;
|
|
final class OrderPlacedEvent extends Event
|
|
{
|
|
public const NAME = 'order.placed';
|
|
public function __construct(public readonly int $id) {}
|
|
}
|
|
PHP,
|
|
'src/Event/BaseEvent.php' => "<?php\nnamespace App\\Event;\nabstract class BaseEvent extends \\Symfony\\Contracts\\EventDispatcher\\Event {}\n",
|
|
'src/Event/UserSignedUp.php' => "<?php\nnamespace App\\Event;\nfinal class UserSignedUp extends BaseEvent {}\n",
|
|
'src/Service/Shop.php' => <<<'PHP'
|
|
<?php
|
|
namespace App\Service;
|
|
use App\Event\OrderPlacedEvent;
|
|
use App\Event\UserSignedUp;
|
|
use App\Message\Mail;
|
|
use Psr\EventDispatcher\EventDispatcherInterface;
|
|
use Symfony\Component\Messenger\MessageBusInterface;
|
|
final class Shop
|
|
{
|
|
public function __construct(private EventDispatcherInterface $events, private MessageBusInterface $bus) {}
|
|
public function order(): void
|
|
{
|
|
$e = new OrderPlacedEvent(1);
|
|
$this->events->dispatch($e, OrderPlacedEvent::NAME);
|
|
$this->events->dispatch(new UserSignedUp());
|
|
$this->events->dispatch(new \stdClass(), 'cart.emptied');
|
|
$this->bus->dispatch(new Mail());
|
|
}
|
|
}
|
|
PHP,
|
|
'src/EventSubscriber/LocaleSubscriber.php' => <<<'PHP'
|
|
<?php
|
|
namespace App\EventSubscriber;
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
use Symfony\Component\HttpKernel\KernelEvents;
|
|
use App\Event\OrderPlacedEvent;
|
|
final class LocaleSubscriber implements EventSubscriberInterface
|
|
{
|
|
public static function getSubscribedEvents(): array
|
|
{
|
|
return [
|
|
KernelEvents::REQUEST => [['onRequest', 20], ['late', -10]],
|
|
OrderPlacedEvent::NAME => 'onOrder',
|
|
];
|
|
}
|
|
public function onRequest(): void {}
|
|
public function late(): void {}
|
|
public function onOrder(): void {}
|
|
}
|
|
PHP,
|
|
'src/EventListener/Listeners.php' => <<<'PHP'
|
|
<?php
|
|
namespace App\EventListener;
|
|
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
|
|
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
|
|
use Doctrine\ORM\Events;
|
|
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent;
|
|
use Symfony\Component\HttpKernel\KernelEvents;
|
|
#[AsEventListener(event: KernelEvents::REQUEST, priority: 50)]
|
|
final class FirstListener
|
|
{
|
|
public function onKernelRequest(RequestEvent $e): void {}
|
|
#[AsEventListener]
|
|
public function typed(RequestEvent $e): void {}
|
|
}
|
|
#[AsDoctrineListener(event: Events::postPersist, priority: 5)]
|
|
#[AsEntityListener(event: Events::preUpdate, method: 'changed', entity: \App\Entity\User::class)]
|
|
final class DbListener
|
|
{
|
|
public function postPersist(): void {}
|
|
public function changed(): void {}
|
|
}
|
|
PHP,
|
|
]);
|
|
}
|
|
|
|
public function testTheFrameworkEventsCarryTheirEventClassAndConstant(): void
|
|
{
|
|
$request = self::event('kernel.request');
|
|
self::assertSame('Symfony\Component\HttpKernel\Event\RequestEvent', $request['class']);
|
|
self::assertSame('KernelEvents::REQUEST', $request['const']);
|
|
self::assertSame('Symfony\Component\Security\Http\Event\LoginSuccessEvent', self::event('Symfony\Component\Security\Http\Event\LoginSuccessEvent')['class']);
|
|
self::assertSame('Doctrine\ORM\Event\PreUpdateEventArgs', self::event('preUpdate')['class']);
|
|
self::assertSame('doctrine', self::event('preUpdate')['kind']);
|
|
self::assertSame('form.pre_submit', EventCatalog::constantName('Symfony\Component\Form\FormEvents', 'PRE_SUBMIT'));
|
|
$groups = array_unique(array_column(EventCatalog::all(), 'group'));
|
|
self::assertSame(['Kernel', 'Security', 'Form', 'Console', 'Messenger', 'Mailer', 'Doctrine'], array_values($groups));
|
|
}
|
|
|
|
public function testOnlyTheEventsOfInstalledPackagesAreOffered(): void
|
|
{
|
|
$root = sys_get_temp_dir() . '/jph-events-' . getmypid();
|
|
@mkdir("$root/vendor/symfony/http-kernel", 0777, true);
|
|
$groups = array_values(array_unique(array_column(EventCatalog::framework($root), 'group')));
|
|
self::assertSame(['Kernel'], $groups);
|
|
exec('rm -rf ' . escapeshellarg($root));
|
|
}
|
|
|
|
public function testTheProjectEventsAreTheEventClassesAndWhatIsDispatched(): void
|
|
{
|
|
$events = EventCatalog::project(self::project());
|
|
$byName = array_column($events, null, 'name');
|
|
self::assertSame(['App\Event\UserSignedUp', 'cart.emptied', 'order.placed'], array_keys($byName));
|
|
self::assertSame('App\Event\OrderPlacedEvent', $byName['order.placed']['class']);
|
|
self::assertSame('OrderPlacedEvent::NAME', $byName['order.placed']['const']);
|
|
self::assertSame('src/Event/OrderPlacedEvent.php', $byName['order.placed']['file']);
|
|
self::assertSame([['file' => 'src/Service/Shop.php', 'line' => 14, 'in' => 'App\Service\Shop::order']], $byName['order.placed']['dispatches']);
|
|
// extends Event through a project class, dispatched without a name: named after its class
|
|
self::assertSame(15, $byName['App\Event\UserSignedUp']['dispatches'][0]['line']);
|
|
self::assertSame('src/Event/UserSignedUp.php', $byName['App\Event\UserSignedUp']['file']);
|
|
// the Messenger bus's dispatch is not an event
|
|
self::assertArrayNotHasKey('App\Message\Mail', $byName);
|
|
}
|
|
|
|
public function testTheListenersOfTheCodeInTheOrderTheyAreCalled(): void
|
|
{
|
|
$order = EventListeners::byEvent(EventListeners::fromCode(self::project()));
|
|
$byEvent = array_column($order, 'listeners', 'event');
|
|
self::assertSame(['kernel.request', 'order.placed', 'postPersist', 'preUpdate', 'Symfony\Component\HttpKernel\Event\RequestEvent'], array_keys($byEvent));
|
|
self::assertSame([['App\EventListener\FirstListener', 'onKernelRequest', 50], ['App\EventSubscriber\LocaleSubscriber', 'onRequest', 20], ['App\EventSubscriber\LocaleSubscriber', 'late', -10]],
|
|
array_map(fn ($l) => [$l['class'], $l['method'], $l['priority']], $byEvent['kernel.request']));
|
|
self::assertSame('typed', $byEvent['Symfony\Component\HttpKernel\Event\RequestEvent'][0]['method']);
|
|
self::assertSame(['doctrine', 'postPersist', 5], [$byEvent['postPersist'][0]['kind'], $byEvent['postPersist'][0]['method'], $byEvent['postPersist'][0]['priority']]);
|
|
self::assertSame(['entity', 'changed', 'App\Entity\User'], [$byEvent['preUpdate'][0]['kind'], $byEvent['preUpdate'][0]['method'], $byEvent['preUpdate'][0]['entity']]);
|
|
self::assertSame('src/EventSubscriber/LocaleSubscriber.php', $byEvent['order.placed'][0]['file']);
|
|
}
|
|
|
|
public function testTheDebugCommandGivesTheRealOrderWithTheVendors(): void
|
|
{
|
|
$json = ['kernel.request' => [
|
|
['type' => 'function', 'name' => 'onKernelRequest', 'class' => 'Symfony\Component\HttpKernel\EventListener\RouterListener', 'priority' => 32],
|
|
['type' => 'function', 'name' => 'onRequest', 'class' => 'App\EventSubscriber\LocaleSubscriber', 'priority' => 20],
|
|
['type' => 'closure', 'priority' => 0],
|
|
]];
|
|
$list = EventListeners::fromDebug($json, self::project(), fn (string $c) => $c === 'Symfony\Component\HttpKernel\EventListener\RouterListener' ? 'vendor/symfony/http-kernel/EventListener/RouterListener.php' : null);
|
|
self::assertSame(['vendor', 'project', 'vendor'], array_column($list, 'kind'));
|
|
self::assertSame('vendor/symfony/http-kernel/EventListener/RouterListener.php', $list[0]['file']);
|
|
self::assertSame('src/EventSubscriber/LocaleSubscriber.php', $list[1]['file']);
|
|
self::assertSame('{closure}', $list[2]['class']);
|
|
self::assertSame('onKernelRequest', EventListeners::defaultMethod('kernel.request'));
|
|
}
|
|
|
|
public function testANewSubscriberWithPrioritiesAndSeveralMethods(): void
|
|
{
|
|
$code = EventCode::subscriber('App\EventSubscriber\LocaleSubscriber', [
|
|
['event' => self::event('kernel.request'), 'method' => 'onKernelRequest', 'priority' => 20],
|
|
['event' => self::event('kernel.request'), 'method' => 'logRequest', 'priority' => -5],
|
|
['event' => self::event('Symfony\Component\Security\Http\Event\LoginSuccessEvent'), 'method' => 'onLoginSuccess', 'priority' => 0],
|
|
]);
|
|
self::assertSame(<<<'PHP'
|
|
<?php
|
|
|
|
namespace App\EventSubscriber;
|
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent;
|
|
use Symfony\Component\HttpKernel\KernelEvents;
|
|
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
|
|
|
|
final class LocaleSubscriber implements EventSubscriberInterface
|
|
{
|
|
public static function getSubscribedEvents(): array
|
|
{
|
|
return [
|
|
KernelEvents::REQUEST => [['onKernelRequest', 20], ['logRequest', -5]],
|
|
LoginSuccessEvent::class => 'onLoginSuccess',
|
|
];
|
|
}
|
|
|
|
public function onKernelRequest(RequestEvent $event): void
|
|
{
|
|
}
|
|
|
|
public function logRequest(RequestEvent $event): void
|
|
{
|
|
}
|
|
|
|
public function onLoginSuccess(LoginSuccessEvent $event): void
|
|
{
|
|
}
|
|
}
|
|
|
|
PHP, $code);
|
|
self::assertNotNull(PhpSources::parse($code));
|
|
}
|
|
|
|
public function testANewListenerWithAttributesOnMethodsOrOnTheClass(): void
|
|
{
|
|
$subs = [['event' => self::event('kernel.exception'), 'method' => 'onKernelException', 'priority' => 10]];
|
|
self::assertSame(<<<'PHP'
|
|
<?php
|
|
|
|
namespace App\EventListener;
|
|
|
|
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
|
|
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
|
|
use Symfony\Component\HttpKernel\KernelEvents;
|
|
|
|
final class ExceptionListener
|
|
{
|
|
#[AsEventListener(event: KernelEvents::EXCEPTION, priority: 10)]
|
|
public function onKernelException(ExceptionEvent $event): void
|
|
{
|
|
}
|
|
}
|
|
|
|
PHP, EventCode::listener('App\EventListener\ExceptionListener', $subs));
|
|
self::assertStringContainsString("#[AsEventListener(event: KernelEvents::EXCEPTION, method: 'onKernelException', priority: 10)]\nfinal class ExceptionListener\n{\n public function onKernelException(",
|
|
EventCode::listener('App\EventListener\ExceptionListener', $subs, 'class'));
|
|
}
|
|
|
|
public function testDoctrineAndEntityListeners(): void
|
|
{
|
|
self::assertSame(<<<'PHP'
|
|
<?php
|
|
|
|
namespace App\EventListener;
|
|
|
|
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
|
|
use Doctrine\ORM\Event\PostPersistEventArgs;
|
|
use Doctrine\ORM\Events;
|
|
|
|
#[AsDoctrineListener(event: Events::postPersist, priority: 500, connection: 'default')]
|
|
final class SearchIndexer
|
|
{
|
|
public function postPersist(PostPersistEventArgs $args): void
|
|
{
|
|
}
|
|
}
|
|
|
|
PHP, EventCode::doctrineListener('App\EventListener\SearchIndexer', [['event' => self::event('postPersist'), 'method' => 'x', 'priority' => 500]], null, 'default'));
|
|
self::assertSame(<<<'PHP'
|
|
<?php
|
|
|
|
namespace App\EventListener;
|
|
|
|
use App\Entity\User;
|
|
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
|
|
use Doctrine\ORM\Event\PreUpdateEventArgs;
|
|
use Doctrine\ORM\Events;
|
|
|
|
#[AsEntityListener(event: Events::preUpdate, method: 'preUpdate', entity: User::class)]
|
|
final class UserChangedNotifier
|
|
{
|
|
public function preUpdate(User $user, PreUpdateEventArgs $args): void
|
|
{
|
|
}
|
|
}
|
|
|
|
PHP, EventCode::doctrineListener('App\EventListener\UserChangedNotifier', [['event' => self::event('preUpdate'), 'method' => 'preUpdate', 'priority' => 0]], 'App\Entity\User'));
|
|
}
|
|
|
|
public function testANewProjectEvent(): void
|
|
{
|
|
self::assertSame(<<<'PHP'
|
|
<?php
|
|
|
|
namespace App\Event;
|
|
|
|
use App\Entity\Order;
|
|
use Symfony\Contracts\EventDispatcher\Event;
|
|
|
|
final class OrderPlacedEvent extends Event
|
|
{
|
|
public const NAME = 'order.placed';
|
|
|
|
public function __construct(
|
|
public readonly Order $order,
|
|
public readonly string $email,
|
|
) {
|
|
}
|
|
}
|
|
|
|
PHP, EventCode::event('App\Event\OrderPlacedEvent', [['name' => 'order', 'type' => 'App\Entity\Order'], ['name' => 'email', 'type' => 'string']], 'order.placed'));
|
|
self::assertSame("<?php\n\nnamespace App\\Event;\n\nuse Symfony\\Contracts\\EventDispatcher\\Event;\n\nfinal class Ping extends Event\n{\n}\n", EventCode::event('App\Event\Ping', []));
|
|
}
|
|
|
|
private const SUBSCRIBER = <<<'PHP'
|
|
<?php
|
|
|
|
namespace App\EventSubscriber;
|
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
use Symfony\Component\HttpKernel\KernelEvents;
|
|
|
|
// a comment that stays
|
|
final class S implements EventSubscriberInterface
|
|
{
|
|
public static function getSubscribedEvents(): array
|
|
{
|
|
return [
|
|
KernelEvents::REQUEST => 'onRequest',
|
|
];
|
|
}
|
|
|
|
public function onRequest(): void
|
|
{
|
|
// kept as it is
|
|
}
|
|
}
|
|
|
|
PHP;
|
|
|
|
public function testASubscriptionAddedToAnExistingSubscriberKeepsTheRestOfTheFile(): void
|
|
{
|
|
$code = EventCode::addSubscription(self::SUBSCRIBER, ['event' => self::event('kernel.response'), 'method' => 'onResponse', 'priority' => -8]);
|
|
self::assertSame(<<<'PHP'
|
|
<?php
|
|
|
|
namespace App\EventSubscriber;
|
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
use Symfony\Component\HttpKernel\Event\ResponseEvent;
|
|
use Symfony\Component\HttpKernel\KernelEvents;
|
|
|
|
// a comment that stays
|
|
final class S implements EventSubscriberInterface
|
|
{
|
|
public static function getSubscribedEvents(): array
|
|
{
|
|
return [
|
|
KernelEvents::REQUEST => 'onRequest',
|
|
KernelEvents::RESPONSE => ['onResponse', -8],
|
|
];
|
|
}
|
|
|
|
public function onRequest(): void
|
|
{
|
|
// kept as it is
|
|
}
|
|
|
|
public function onResponse(ResponseEvent $event): void
|
|
{
|
|
}
|
|
}
|
|
|
|
PHP, $code);
|
|
// one more method for an event already there
|
|
$twice = EventCode::addSubscription(self::SUBSCRIBER, ['event' => self::event('kernel.request'), 'method' => 'second', 'priority' => 5]);
|
|
self::assertStringContainsString("KernelEvents::REQUEST => [['onRequest', 0], ['second', 5]],\n", $twice);
|
|
}
|
|
|
|
public function testPrioritiesAreChangedInPlace(): void
|
|
{
|
|
self::assertStringContainsString("KernelEvents::REQUEST => ['onRequest', 30],\n", EventCode::setPriority(self::SUBSCRIBER, 'kernel.request', 'onRequest', 30));
|
|
$multi = str_replace("'onRequest',", "[['onRequest', 1], ['other', 2]],", self::SUBSCRIBER);
|
|
self::assertStringContainsString("[['onRequest', 1], ['other', -4]]", EventCode::setPriority($multi, 'kernel.request', 'other', -4));
|
|
$listener = "<?php\nuse Symfony\\Component\\EventDispatcher\\Attribute\\AsEventListener;\nfinal class L\n{\n #[AsEventListener(event: 'app.x')]\n public function onX(): void\n {\n }\n}\n";
|
|
self::assertStringContainsString("#[AsEventListener(event: 'app.x', priority: 7)]", EventCode::setPriority($listener, 'app.x', 'onX', 7));
|
|
$withPriority = str_replace("'app.x')", "'app.x', priority: 3)", $listener);
|
|
self::assertSame(str_replace('3', '9', $withPriority), EventCode::setPriority($withPriority, 'app.x', 'onX', 9));
|
|
}
|
|
|
|
public function testRemovingASubscription(): void
|
|
{
|
|
$code = EventCode::addSubscription(self::SUBSCRIBER, ['event' => self::event('kernel.response'), 'method' => 'onResponse', 'priority' => 0]);
|
|
$removed = EventCode::removeSubscription($code, 'kernel.request', 'onRequest');
|
|
self::assertStringNotContainsString('KernelEvents::REQUEST', $removed);
|
|
self::assertStringContainsString("KernelEvents::RESPONSE => 'onResponse',", $removed);
|
|
$listener = "<?php\nuse Symfony\\Component\\EventDispatcher\\Attribute\\AsEventListener;\nfinal class L\n{\n #[AsEventListener(event: 'app.x')]\n public function onX(): void\n {\n }\n}\n";
|
|
self::assertSame("<?php\nuse Symfony\\Component\\EventDispatcher\\Attribute\\AsEventListener;\nfinal class L\n{\n public function onX(): void\n {\n }\n}\n",
|
|
EventCode::removeSubscription($listener, 'app.x', 'onX'));
|
|
}
|
|
|
|
public function testAListenerMethodAddedToAnExistingClass(): void
|
|
{
|
|
$code = "<?php\n\nnamespace App\\EventListener;\n\nfinal class L\n{\n public function a(): void\n {\n }\n}\n";
|
|
self::assertSame(<<<'PHP'
|
|
<?php
|
|
|
|
namespace App\EventListener;
|
|
|
|
use Symfony\Component\Console\ConsoleEvents;
|
|
use Symfony\Component\Console\Event\ConsoleErrorEvent;
|
|
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
|
|
|
|
final class L
|
|
{
|
|
public function a(): void
|
|
{
|
|
}
|
|
|
|
#[AsEventListener(event: ConsoleEvents::ERROR, priority: -1)]
|
|
public function onConsoleError(ConsoleErrorEvent $event): void
|
|
{
|
|
}
|
|
}
|
|
|
|
PHP, EventCode::addListenerMethod($code, ['event' => self::event('console.error'), 'method' => 'onConsoleError', 'priority' => -1]));
|
|
}
|
|
|
|
public function testTheDispatchIsInsertedWithTheDispatcherInjected(): void
|
|
{
|
|
$service = <<<'PHP'
|
|
<?php
|
|
|
|
namespace App\Service;
|
|
|
|
use App\Repository\OrderRepository;
|
|
|
|
final class Checkout
|
|
{
|
|
public function __construct(private OrderRepository $orders)
|
|
{
|
|
}
|
|
|
|
public function place(int $id, string $email): bool
|
|
{
|
|
$this->orders->save($id);
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
PHP;
|
|
self::assertSame(<<<'PHP'
|
|
<?php
|
|
|
|
namespace App\Service;
|
|
|
|
use App\Event\OrderPlacedEvent;
|
|
use App\Repository\OrderRepository;
|
|
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
|
|
|
|
final class Checkout
|
|
{
|
|
public function __construct(private OrderRepository $orders, private readonly EventDispatcherInterface $eventDispatcher)
|
|
{
|
|
}
|
|
|
|
public function place(int $id, string $email): bool
|
|
{
|
|
$this->orders->save($id);
|
|
$this->eventDispatcher->dispatch(new OrderPlacedEvent($id, total: null), OrderPlacedEvent::NAME);
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
PHP, EventCode::insertDispatch($service, null, 'place', 'App\Event\OrderPlacedEvent', ['id', 'total'], 'NAME'));
|
|
// no constructor: one is written; a dispatcher already there is used
|
|
$bare = "<?php\n\nnamespace App\\Service;\n\nfinal class C\n{\n public function go(): void\n {\n }\n}\n";
|
|
self::assertSame("<?php\n\nnamespace App\\Service;\n\nuse App\\Event\\Ping;\nuse Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface;\n\nfinal class C\n{\n public function __construct(\n private readonly EventDispatcherInterface \$eventDispatcher,\n ) {\n }\n\n public function go(): void\n {\n \$this->eventDispatcher->dispatch(new Ping());\n }\n}\n",
|
|
EventCode::insertDispatch($bare, null, 'go', 'App\Event\Ping', []));
|
|
$has = "<?php\nuse Psr\\EventDispatcher\\EventDispatcherInterface;\nfinal class C\n{\n public function __construct(private EventDispatcherInterface \$events) {}\n public function go(): void\n {\n }\n}\n";
|
|
self::assertStringContainsString('$this->events->dispatch(new Ping());', EventCode::insertDispatch($has, null, 'go', 'Ping', []));
|
|
}
|
|
}
|