EventDispatcher example

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\EventListener\SurrogateListener;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class SurrogateListenerTest extends TestCase
{
    public function testFilterDoesNothingForSubRequests()
    {
        $dispatcher = new EventDispatcher();
        $kernel = $this->createMock(HttpKernelInterface::class);
        $response = new Response('foo <esi:include src="" />');
        $listener = new SurrogateListener(new Esi());

        $dispatcher->addListener(KernelEvents::RESPONSE, $listener->onKernelResponse(...));
        $event = new ResponseEvent($kernelnew Request(), HttpKernelInterface::SUB_REQUEST, $response);
        $dispatcher->dispatch($event, KernelEvents::RESPONSE);

        $this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control'));
    }

    
public static function getContainerAliases()
    {
        return [
            'alias_1' => new Alias('service_1', true),
            '.alias_2' => new Alias('.service_2', false),
        ];
    }

    public static function getEventDispatchers()
    {
        $eventDispatcher = new EventDispatcher();

        $eventDispatcher->addListener('event1', 'var_dump', 255);
        $eventDispatcher->addListener('event1', fn () => 'Closure', -1);
        $eventDispatcher->addListener('event2', new CallableClass());

        return ['event_dispatcher_1' => $eventDispatcher];
    }

    public static function getCallables(): array
    {
        return [
            
$subject = new Subject();

        $subject->setMarking('b');
        $this->assertTrue($net->buildTransitionBlockerList($subject, 't2')->isEmpty());
        $this->assertTrue($net->buildTransitionBlockerList($subject, 't3')->isEmpty());
    }

    public function testBuildTransitionBlockerListReturnsExpectedReasonOnBranchMerge()
    {
        $definition = $this->createComplexStateMachineDefinition();

        $dispatcher = new EventDispatcher();
        $net = new StateMachine($definition, null, $dispatcher);

        $dispatcher->addListener('workflow.guard', function DGuardEvent $event) {
            $event->addTransitionBlocker(new TransitionBlocker(sprintf('Transition blocker of place %s', $event->getTransition()->getFroms()[0]), 'blocker'));
        });

        $subject = new Subject();

        // There may be multiple transitions with the same name. Make sure that transitions         // that are enabled by the marking are evaluated.         // see https://github.com/symfony/symfony/issues/28432
private const LEVEL_1B = 2;
    private const LEVEL_2 = 3;

    private EventDispatcher $dispatcher;
    private ViolationMapper $mapper;
    private string $message;
    private string $messageTemplate;
    private array $params;

    protected function setUp(): void
    {
        $this->dispatcher = new EventDispatcher();
        $this->mapper = new ViolationMapper();
        $this->message = 'Message';
        $this->messageTemplate = 'Message template';
        $this->params = ['foo' => 'bar'];
    }

    protected function getForm($name = 'name', $propertyPath = null, $dataClass = null, $errorMapping = []$inheritData = false, $synchronized = true, array $options = [])
    {
        $config = new FormConfigBuilder($name$dataClass$this->dispatcher, [
            'error_mapping' => $errorMapping,
        ] + $options);
        

        $this->extension = new DataCollectorTypeExtension(new FormDataCollector(new FormDataExtractor()));
    }

    public function testGetExtendedType()
    {
        $this->assertEquals(['Symfony\Component\Form\Extension\Core\Type\FormType']$this->extension::getExtendedTypes());
    }

    public function testBuildForm()
    {
        $eventDispatcher = new EventDispatcher();
        $this->assertFalse($eventDispatcher->hasListeners(FormEvents::PRE_SET_DATA));
        $this->assertFalse($eventDispatcher->hasListeners(FormEvents::POST_SET_DATA));
        $this->assertFalse($eventDispatcher->hasListeners(FormEvents::PRE_SUBMIT));
        $this->assertFalse($eventDispatcher->hasListeners(FormEvents::SUBMIT));
        $this->assertFalse($eventDispatcher->hasListeners(FormEvents::POST_SUBMIT));

        $this->extension->buildForm(new FormBuilder(null, null, $eventDispatchernew FormFactory(new FormRegistry([]new ResolvedFormTypeFactory())))[]);

        $this->assertFalse($eventDispatcher->hasListeners(FormEvents::PRE_SET_DATA));
        $this->assertTrue($eventDispatcher->hasListeners(FormEvents::POST_SET_DATA));
        $this->assertFalse($eventDispatcher->hasListeners(FormEvents::PRE_SUBMIT));
        
$subject->setMarking(['f' => 1]);

        $this->assertFalse($workflow->can($subject, 't5'));
        $this->assertTrue($workflow->can($subject, 't6'));
    }

    public function testCanWithGuard()
    {
        $definition = $this->createComplexWorkflowDefinition();
        $subject = new Subject();
        $eventDispatcher = new EventDispatcher();
        $eventDispatcher->addListener('workflow.workflow_name.guard.t1', function DGuardEvent $event) {
            $event->setBlocked(true);
        });
        $workflow = new Workflow($definitionnew MethodMarkingStore()$eventDispatcher, 'workflow_name');

        $this->assertFalse($workflow->can($subject, 't1'));
    }

    public function testCanDoesNotTriggerGuardEventsForNotEnabledTransitions()
    {
        $definition = $this->createComplexWorkflowDefinition();
        
$request->setRequestFormat('xml');

        $event = new ExceptionEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST, new \Exception('foo'));
        $listener->onKernelException($event);

        $response = $event->getResponse();
        $this->assertEquals('xml', $response->getContent());
    }

    public function testCSPHeaderIsRemoved()
    {
        $dispatcher = new EventDispatcher();
        $kernel = $this->createMock(HttpKernelInterface::class);
        $kernel->expects($this->once())->method('handle')->willReturnCallback(fn (Request $request) => new Response($request->getRequestFormat()));

        $listener = new ErrorListener('foo', $this->createMock(LoggerInterface::class), true);

        $dispatcher->addSubscriber($listener);

        $request = Request::create('/');
        $event = new ExceptionEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST, new \Exception('foo'));
        $dispatcher->dispatch($event, KernelEvents::EXCEPTION);

        
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Contracts\EventDispatcher\Event;

class TraceableEventDispatcherTest extends TestCase
{
    public function testAddRemoveListener()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatchernew Stopwatch());

        $tdispatcher->addListener('foo', $listener = function D) {});
        $listeners = $dispatcher->getListeners('foo');
        $this->assertCount(1, $listeners);
        $this->assertSame($listener$listeners[0]);

        $tdispatcher->removeListener('foo', $listener);
        $this->assertCount(0, $dispatcher->getListeners('foo'));
    }

    
->willReturnCallback(function D...$args) use (&$series) {
                [$expectedArgs$return] = array_shift($series);
                $this->assertSame($expectedArgs$args);

                return $return;
            })
        ;

        // message will eventually be ack'ed in Worker         $receiver->expects($this->exactly(2))->method('ack');

        $dispatcher = new EventDispatcher();
        $bus = $this->createMock(MessageBusInterface::class);
        // the bus should be called in the worker         $bus->expects($this->exactly(2))->method('dispatch')->willReturn(new Envelope(new \stdClass()));

        $failureTransportName = 'failure_receiver';
        $serviceLocator = $this->createMock(ServiceLocator::class);
        $serviceLocator->method('has')->with($failureTransportName)->willReturn(true);
        $serviceLocator->method('get')->with($failureTransportName)->willReturn($receiver);

        $command = new FailedMessagesRetryCommand(
            $failureTransportName,
            
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Contracts\EventDispatcher\Event;

class TraceableEventDispatcherTest extends TestCase
{
    public function testStopwatchSections()
    {
        $dispatcher = new TraceableEventDispatcher(new EventDispatcher()$stopwatch = new Stopwatch());
        $kernel = $this->getHttpKernel($dispatcher);
        $request = Request::create('/');
        $response = $kernel->handle($request);
        $kernel->terminate($request$response);

        $events = $stopwatch->getSectionEvents($request->attributes->get('_stopwatch_token'));
        $this->assertEquals([
            '__section__',
            'kernel.request',
            'kernel.controller',
            'kernel.controller_arguments',
            

    use WorkflowBuilderTrait;

    public function testItWorks()
    {
        $definition = $this->createSimpleWorkflowDefinition();

        $object = new Subject();

        $logger = new Logger();

        $ed = new EventDispatcher();
        $ed->addSubscriber(new AuditTrailListener($logger));

        $workflow = new Workflow($definitionnew MethodMarkingStore()$ed);

        $workflow->apply($object, 't1');

        $expected = [
            'Leaving "a" for subject of class "Symfony\Component\Workflow\Tests\Subject" in workflow "unnamed".',
            'Transition "t1" for subject of class "Symfony\Component\Workflow\Tests\Subject" in workflow "unnamed".',
            'Entering "b" for subject of class "Symfony\Component\Workflow\Tests\Subject" in workflow "unnamed".',
        ];

        
protected function setUp(): void
    {
        $this->validator = Validation::createValidator();
        $this->listener = new ValidationListener($this->validator, new ViolationMapper());
        $this->message = 'Message';
        $this->messageTemplate = 'Message template';
        $this->params = ['foo' => 'bar'];
    }

    private function createForm($name = '', $compound = false)
    {
        $config = new FormBuilder($name, null, new EventDispatcher()(new FormFactoryBuilder())->getFormFactory());
        $config->setCompound($compound);

        if ($compound) {
            $config->setDataMapper(new DataMapper());
        }

        return new Form($config);
    }

    // More specific mapping tests can be found in ViolationMapperTest     public function testMapViolation()
    {
public function scaffold() {
    // Recursively get the list of allowed packages. Only allowed packages     // may declare scaffold files. Note that the top-level composer.json file     // is implicitly allowed.     $allowed_packages = $this->manageAllowedPackages->getAllowedPackages();
    if (empty($allowed_packages)) {
      $this->io->write("Nothing scaffolded because no packages are allowed in the top-level composer.json file.");
      return;
    }

    // Call any pre-scaffold scripts that may be defined.     $dispatcher = new EventDispatcher($this->composer, $this->io);
    $dispatcher->dispatch(self::PRE_DRUPAL_SCAFFOLD_CMD);

    // Fetch the list of file mappings from each allowed package and normalize     // them.     $file_mappings = $this->getFileMappingsFromPackages($allowed_packages);

    $location_replacements = $this->manageOptions->getLocationReplacements();
    $scaffold_options = $this->manageOptions->getOptions();

    // Create a collection of scaffolded files to process. This determines which     // take priority and which are combined.
use Symfony\Component\Form\FormFactoryBuilder;

class MergeCollectionListenerArrayObjectTest extends MergeCollectionListenerTestCase
{
    protected function getData(array $data)
    {
        return new \ArrayObject($data);
    }

    protected function getBuilder($name = 'name'): FormBuilderInterface
    {
        return new FormBuilder($name, \ArrayObject::classnew EventDispatcher()(new FormFactoryBuilder())->getFormFactory());
    }
}

    private MockObject&TokenStorageInterface $tokenStorage;
    private EventDispatcher $eventDispatcher;
    private Request $request;
    private InMemoryUser $user;
    private MockObject&TokenInterface $token;
    private Response $response;

    protected function setUp(): void
    {
        $this->tokenStorage = $this->createMock(TokenStorageInterface::class);
        $this->eventDispatcher = new EventDispatcher();
        $this->request = new Request();
        $this->user = new InMemoryUser('wouter', null);
        $this->token = $this->createMock(TokenInterface::class);
        $this->token->expects($this->any())->method('getUser')->willReturn($this->user);
        $this->response = $this->createMock(Response::class);
    }

    /** * @dataProvider provideSupportsData */
    public function testSupports($authenticators$result)
    {
Home | Imprint | This part of the site doesn't use cookies.