Listeners are registered on the manager and events are dispatched through the manager.
저자: Guilherme Blanco (guilhermeblanco@hotmail.com)
저자: Jonathan Wage (jonwage@gmail.com)
저자: Roman Borschel (roman@code-factory.org)
저자: Bernhard Schussek (bschussek@gmail.com)
저자: Fabien Potencier (fabien@symfony.com)
저자: Jordi Boggiano (j.boggiano@seld.be)
저자: Jordan Alliot (jordan.alliot@gmail.com)
상속: implements Symfony\Component\EventDispatcher\EventDispatcherInterface
예제 #1
0
 /**
  * Navbar Menu
  * 
  * @param array $options
  * @return ItemInterface
  */
 public function createPrimaryMenu(array $options)
 {
     $menu = $this->factory->createItem('root');
     $this->eventDispatcher->dispatch(WebsiteEvents::PRIMARY_MENU_INIT, new PrimaryMenuEvent($menu, $this->factory));
     $this->reorderMenuItems($menu);
     return $menu;
 }
예제 #2
0
 public function testRecursiveMessage()
 {
     $dispatcher = new EventDispatcher();
     $backend = new PostponeRuntimeBackend($dispatcher, true);
     $dispatcher->addListener('kernel.terminate', array($backend, 'onEvent'));
     $message1 = $backend->create('notification.demo1', array());
     $message2 = $backend->create('notification.demo2', array());
     $backend->publish($message1);
     $phpunit = $this;
     $phpunit->passed1 = false;
     $phpunit->passed2 = false;
     $dispatcher->addListener('notification.demo1', function (ConsumerEventInterface $event) use($phpunit, $message1, $message2, $backend, $dispatcher) {
         $phpunit->assertSame($message1, $event->getMessage());
         $phpunit->passed1 = true;
         $backend->publish($message2);
     });
     $dispatcher->addListener('notification.demo2', function (ConsumerEventInterface $event) use($phpunit, $message2) {
         $phpunit->assertSame($message2, $event->getMessage());
         $phpunit->passed2 = true;
     });
     $dispatcher->dispatch('kernel.terminate');
     $this->assertTrue($phpunit->passed1);
     $this->assertTrue($phpunit->passed2);
     $this->assertEquals(MessageInterface::STATE_DONE, $message1->getState());
     $this->assertEquals(MessageInterface::STATE_DONE, $message2->getState());
 }
예제 #3
0
 public function checkAndProxyEvent(CrawlerRequestEvent $event, $name)
 {
     $uri = $event->getRequest()->getUri();
     if ($this->matcher->matches($uri)) {
         $this->dispatcher->dispatch($name, $event);
     }
 }
예제 #4
0
 /**
  * @test
  */
 function shouldSortSimpleDoctrineQuery()
 {
     $em = $this->getMockSqliteEntityManager();
     $this->populate($em);
     $dispatcher = new EventDispatcher();
     $dispatcher->addSubscriber(new PaginationSubscriber());
     $dispatcher->addSubscriber(new Sortable());
     $p = new Paginator($dispatcher);
     $_GET['sort'] = 'a.title';
     $_GET['direction'] = 'asc';
     $this->startQueryLog();
     $query = $this->em->createQuery('SELECT a FROM Test\\Fixture\\Entity\\Article a');
     $view = $p->paginate($query, 1, 10);
     $items = $view->getItems();
     $this->assertEquals(4, count($items));
     $this->assertEquals('autumn', $items[0]->getTitle());
     $this->assertEquals('spring', $items[1]->getTitle());
     $this->assertEquals('summer', $items[2]->getTitle());
     $this->assertEquals('winter', $items[3]->getTitle());
     $_GET['direction'] = 'desc';
     $view = $p->paginate($query, 1, 10);
     $items = $view->getItems();
     $this->assertEquals(4, count($items));
     $this->assertEquals('winter', $items[0]->getTitle());
     $this->assertEquals('summer', $items[1]->getTitle());
     $this->assertEquals('spring', $items[2]->getTitle());
     $this->assertEquals('autumn', $items[3]->getTitle());
     $this->assertEquals(6, $this->queryAnalyzer->getNumExecutedQueries());
     $executed = $this->queryAnalyzer->getExecutedQueries();
     $this->assertEquals('SELECT DISTINCT a0_.id AS id0, a0_.title AS title1 FROM Article a0_ ORDER BY a0_.title ASC LIMIT 10 OFFSET 0', $executed[1]);
     $this->assertEquals('SELECT DISTINCT a0_.id AS id0, a0_.title AS title1 FROM Article a0_ ORDER BY a0_.title DESC LIMIT 10 OFFSET 0', $executed[4]);
 }
예제 #5
0
 /**
  * Verifies that all events are logged.
  */
 public function testListen()
 {
     // create the test sources
     mkdir($this->dir . '/src/a', 0755, true);
     mkdir($this->dir . '/src/b', 0755, true);
     mkdir($this->dir . '/src/c', 0755, true);
     file_put_contents($this->dir . '/src/a/a', 'a');
     file_put_contents($this->dir . '/src/b/b', 'b');
     file_put_contents($this->dir . '/src/c/c', 'c');
     // create the logger
     $handler = new TestHandler();
     $logger = new Logger('test');
     $logger->pushHandler($handler);
     // create the event dispatcher and register the subscriber
     $dispatcher = new EventDispatcher();
     $dispatcher->addSubscriber(new LoggerSubscriber($logger));
     // register the dispatcher with the builder
     $this->builder->setEventDispatcher($dispatcher);
     // build the archive
     $this->builder->addEmptyDir('path/to/d');
     $this->builder->addFile($this->dir . '/src/a/a', 'path/to/e');
     $this->builder->addFromString('path/to/f', 'f');
     $this->builder->buildFromDirectory($this->dir . '/src/b', '/(^test)/');
     $this->builder->buildFromIterator(new ArrayIterator(array('c/c' => $this->dir . '/src/c/c')), $this->dir . '/src/');
     $this->builder->setStub('<?php __HALT_COMPILER();');
     // make sure the log is what we expected
     $records = $handler->getRecords();
     $expected = array(array('message' => 'The empty directory "d" is about to be added.', 'context' => array('local' => 'path/to/d')), array('message' => 'The empty directory "d" has been added.', 'context' => array('local' => 'path/to/d')), array('message' => 'The file "a" is about to be added as "e".', 'context' => array('file' => $this->dir . '/src/a/a', 'local' => 'path/to/e')), array('message' => 'The string is about to be added as "e".', 'context' => array('local' => 'path/to/e')), array('message' => 'The string has been added as "e".', 'context' => array('local' => 'path/to/e')), array('message' => 'The file "a" has been added as "e".', 'context' => array('file' => $this->dir . '/src/a/a', 'local' => 'path/to/e')), array('message' => 'The string is about to be added as "f".', 'context' => array('local' => 'path/to/f')), array('message' => 'The string has been added as "f".', 'context' => array('local' => 'path/to/f')), array('message' => 'The directory "b" is about to be added.', 'context' => array('filter' => '/(^test)/', 'path' => $this->dir . '/src/b')), array('message' => 'The items from the "RegexIterator" iterator are about to be added.', 'context' => array('base' => $this->dir . '/src/b', 'class' => 'Box\\Component\\Builder\\Iterator\\RegexIterator')), array('message' => 'The items from the "RegexIterator" iterator have been added.', 'context' => array('base' => $this->dir . '/src/b', 'class' => 'Box\\Component\\Builder\\Iterator\\RegexIterator')), array('message' => 'The directory "b" has been added.', 'context' => array('filter' => '/(^test)/', 'path' => $this->dir . '/src/b')), array('message' => 'The items from the "ArrayIterator" iterator are about to be added.', 'context' => array('base' => $this->dir . '/src/', 'class' => 'ArrayIterator')), array('message' => 'The path "c" is about to be added as "c".', 'context' => array('path' => $this->dir . '/src/c/c', 'local' => 'c/c')), array('message' => 'The items from the "ArrayIterator" iterator have been added.', 'context' => array('base' => $this->dir . '/src/', 'class' => 'ArrayIterator')), array('message' => 'The custom stub is about to be set.', 'context' => array()), array('message' => 'The custom stub has been set.', 'context' => array()));
     foreach ($expected as $i => $e) {
         self::assertEquals($e['message'], $records[$i]['message']);
         self::assertEquals($e['context'], $records[$i]['context']);
     }
 }
 public function setUp()
 {
     $dispatcher = new EventDispatcher();
     $this->wsdl = new DefinitionsReader(null, $dispatcher);
     $this->soap = new SoapReader();
     $dispatcher->addSubscriber($this->soap);
 }
예제 #7
0
 /**
  * Dispatch event.
  *
  * @param string $name
  * @param Event  $event
  */
 private function dispatchEvent($name, Event $event)
 {
     if (null === $this->eventDispatcher) {
         return;
     }
     $this->eventDispatcher->dispatch($name, $event);
 }
예제 #8
0
 /**
  * @return EventDispatcher
  */
 protected function getEventDispatcher()
 {
     $dispatcher = new EventDispatcher();
     $redirect_subsciber = new RedirectSubscriber();
     $dispatcher->addSubscriber($redirect_subsciber);
     return $dispatcher;
 }
예제 #9
0
 public function onCommitDone()
 {
     $this->eventDispatcher->dispatch('commitDone', new CommitDoneEvent());
     foreach ($this->onCommitDoneCallbacks as $callback) {
         call_user_func($callback);
     }
 }
예제 #10
0
 public function setUp()
 {
     $this->requestStack = new RequestStack();
     $request = new Request();
     $this->requestStack->push($request);
     $this->session = new Session(new MockArraySessionStorage());
     $request->setSession($this->session);
     $this->dispatcher = new EventDispatcher();
     $translator = new Translator($this->getMock('\\Symfony\\Component\\DependencyInjection\\ContainerInterface'));
     $token = new TokenProvider($this->requestStack, $translator, 'test');
     $this->dispatcher->addSubscriber(new \Thelia\Action\Cart($this->requestStack, $token));
     $this->session->setSessionCart(null);
     $request->setSession($this->session);
     /** @var \Thelia\Action\Cart  cartAction */
     $this->cartAction = new \Thelia\Action\Cart($this->requestStack, new TokenProvider($this->requestStack, $translator, 'baba au rhum'));
     $this->dispatcherNull = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface');
     $this->dispatcher = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface', array(), array(), '', true, true, true, false);
     $this->dispatcher->expects($this->any())->method('dispatch')->will($this->returnCallback(function ($type, $event) {
         if ($type == TheliaEvents::CART_RESTORE_CURRENT) {
             $this->cartAction->restoreCurrentCart($event, null, $this->dispatcher);
         } elseif ($type == TheliaEvents::CART_CREATE_NEW) {
             $this->cartAction->createEmptyCart($event, null, $this->dispatcher);
         }
     }));
 }
 /**
  * @param array $items
  */
 public function write(array $items)
 {
     //      file_put_contents('options.json', json_encode($items));
     foreach ($items as $item) {
         try {
             $this->webservice->sendAttributeOption($item);
         } catch (\Exception $e) {
             $event = new InvalidItemEvent(__CLASS__, $e->getMessage(), array(), ['code' => key($item)]);
             // Logging file
             $this->eventDispatcher->dispatch(EventInterface::INVALID_ITEM, $event);
             // Loggin Interface
             $this->stepExecution->addWarning(__CLASS__, $e->getMessage(), array(), ['code' => key($item)]);
             /** @var ClientErrorResponseException  $e */
             if ($e->getResponse()->getStatusCode() <= 404) {
                 $e = new \Exception($e->getResponse()->getReasonPhrase());
                 $this->stepExecution->addFailureException($e);
                 $exitStatus = new ExitStatus(ExitStatus::FAILED);
                 $this->stepExecution->setExitStatus($exitStatus);
             }
             // Handle next element.
         }
         $this->stepExecution->incrementWriteCount();
         $this->stepExecution->incrementSummaryInfo('write');
     }
 }
예제 #12
0
 public function __construct($name, array $params = [])
 {
     $app = $this;
     $locator = new FileLocator();
     $this->routesFileLoader = new YamlFileLoader($locator);
     $this['context'] = function () {
         return new RequestContext();
     };
     $this['matcher'] = function () {
         return new UrlMatcher($this['routes'], $this['context']);
     };
     $this['resolver'] = function () {
         return new ControllerResolver($this);
     };
     $this['dispatcher'] = function () use($app) {
         $dispatcher = new EventDispatcher();
         $dispatcher->addSubscriber(new RouterListener($app['matcher']));
         $dispatcher->addSubscriber(new ResponseListener($app['charset']));
         return $dispatcher;
     };
     $this['kernel'] = function () use($app) {
         return new HttpKernel($app['dispatcher'], $app['resolver']);
     };
     //        $this['request.http_port']  = 80;
     //        $this['request.https_port'] = 443;
     $this['charset'] = 'UTF-8';
     parent::__construct($name, null, $params);
     $this->setApp($this);
 }
예제 #13
0
파일: Step.php 프로젝트: skymeyer/sugardev
 /**
  * {@inheritdoc}
  */
 public function execute(EventDispatcher $dispatcher)
 {
     $this->ticksRemaining = $this->units;
     $dispatcher->dispatch(Events::STEP_BEFORE_EXECUTE, new StepEvent($this));
     call_user_func($this->executer, $this);
     $dispatcher->dispatch(Events::STEP_AFTER_EXECUTE, new StepEvent($this));
 }
예제 #14
0
 public function testGlobalScore()
 {
     $dispatcher = new EventDispatcher();
     $testers = array('Activity', 'Composer', 'Followers', 'KnpBundles', 'Readme', 'Travis');
     foreach ($testers as $testerClass) {
         $fqcn = sprintf('\\Knp\\Bundle\\KnpBundlesBundle\\EventListener\\Scoring\\%sListener', $testerClass);
         $tester = new $fqcn();
         $dispatcher->addListener(BundleEvent::UPDATE_SCORE, array($tester, 'onScoreUpdate'));
     }
     $bundle = new Bundle();
     // activity (+4)
     $bundle->setLastCommitAt(new \DateTime('-10days'));
     // composer (+5)
     $bundle->setComposerName('bundle-composer-name');
     // followers (+10)
     $bundle->setNbFollowers(10);
     // recommendation (+5)
     $bundle->addRecommender(new Developer());
     // readme (+5)
     $bundle->setReadme(str_repeat('-', 500));
     // travis (+10)
     $bundle->setUsesTravisCi(true);
     $bundle->setTravisCiBuildStatus(true);
     $dispatcher->dispatch(BundleEvent::UPDATE_SCORE, new BundleEvent($bundle));
     $bundle->recalculateScore();
     $this->assertEquals(39, $bundle->getScore());
 }
예제 #15
0
파일: QueryTest.php 프로젝트: Dren-x/mobit
 /**
  * @test
  */
 function shouldSortSimpleDoctrineQuery()
 {
     $this->populate();
     $dispatcher = new EventDispatcher();
     $dispatcher->addSubscriber(new PaginationSubscriber());
     $dispatcher->addSubscriber(new Sortable());
     $p = new Paginator($dispatcher);
     $_GET['sort'] = 'title';
     $_GET['direction'] = 'asc';
     $qb = $this->dm->createQueryBuilder('Test\\Fixture\\Document\\Article');
     $query = $qb->getQuery();
     $view = $p->paginate($query, 1, 10);
     $items = array_values($view->getItems());
     $this->assertEquals(4, count($items));
     $this->assertEquals('autumn', $items[0]->getTitle());
     $this->assertEquals('spring', $items[1]->getTitle());
     $this->assertEquals('summer', $items[2]->getTitle());
     $this->assertEquals('winter', $items[3]->getTitle());
     $_GET['direction'] = 'desc';
     $view = $p->paginate($query, 1, 10);
     $items = array_values($view->getItems());
     $this->assertEquals(4, count($items));
     $this->assertEquals('winter', $items[0]->getTitle());
     $this->assertEquals('summer', $items[1]->getTitle());
     $this->assertEquals('spring', $items[2]->getTitle());
     $this->assertEquals('autumn', $items[3]->getTitle());
 }
 public function testCookieIsNotUpdatedWithFalseSetCookieOnChange()
 {
     $listener = $this->getLocaleUpdateListener(array('cookie'), false);
     $listener->onLocaleChange($this->getFilterLocaleSwitchEvent(false));
     $addedListeners = $this->dispatcher->getListeners(KernelEvents::RESPONSE);
     $this->assertSame(array(), $addedListeners);
 }
예제 #17
0
 /**
  * Use this method to build the container with the services that you need.
  * @param ContainerBuilder $container
  */
 protected function buildContainer(ContainerBuilder $container)
 {
     $eventDispatcher = new EventDispatcher();
     $eventDispatcher->addSubscriber(new Cache(new ArrayAdapter()));
     $container->set("event_dispatcher", $eventDispatcher);
     $container->setParameter("kernel.cache_dir", $this->cache_dir);
 }
예제 #18
0
 protected function getDispatcher()
 {
     $dispatcher = new EventDispatcher();
     $listener = new ResponseListener('UTF-8');
     $dispatcher->connect('core.response', array($listener, 'filter'));
     return $dispatcher;
 }
예제 #19
0
 public function testSwitchParameters()
 {
     $input = array('where' => array('foo' => 'bar'));
     $eventDispatcher = new EventDispatcher();
     $eventDispatcher->addListener(OperatorEvent::EVENT_NAME, function (OperatorEvent $event) {
         if ($event->getField() === 'foo') {
             $event->setField('pew-pew');
             if ($event->getValue() === 'bar') {
                 $value = [1, 2, 3, 4];
             } else {
                 $value = [5, 6, 7, 8];
             }
             $event->setValue($value);
         }
     });
     $builder = new Builder($eventDispatcher);
     $builder->build($input);
     $this->assertCount(1, $builder->getFilters());
     $filters = $builder->getFilters();
     $this->assertEquals('and', $filters[0]->getGroup());
     /* @var $expected ConditionInterface[] */
     $expected = array(FilterConditionBuilder::create(FilterCondition::CONDITION_IN, 'pew-pew', [1, 2, 3, 4], $eventDispatcher));
     foreach ($filters[0]->getConditions() as $key => $condition) {
         $this->assertEquals($expected[$key]->getValue(), $condition->getValue());
         $this->assertEquals($expected[$key]->getField(), $condition->getField());
         $this->assertEquals($expected[$key]->getOperator(), $condition->getOperator());
     }
 }
예제 #20
0
 public function __construct()
 {
     parent::__construct(self::NAME, self::VERSION);
     $dispatcher = new EventDispatcher();
     $dispatcher->addListener(ConsoleEvents::COMMAND, array($this, 'onCommand'));
     $this->setDispatcher($dispatcher);
     $this->loadConfig();
     $this->add(new Command\InitCommand());
     $this->add(new Command\ClearStashCacheCommand());
     $this->add(new Command\ClearCeCacheCommand());
     $this->add(new Command\ClearEECacheCommand());
     $this->add(new Command\GithubAddonInstallerCommand());
     $this->add(new Command\ReplCommand());
     $this->add(new Command\ShowConfigCommand());
     $this->add(new Command\UpdateAddonsCommand());
     $this->add(new Command\CreateChannelCommand());
     $this->add(new Command\CreateTemplateCommand());
     $this->add(new Command\CreateTemplateGroupCommand());
     $this->add(new Command\CreateSnippetCommand());
     $this->add(new Command\CreateGlobalVariableCommand());
     $this->add(new Command\GenerateCommandCommand());
     $this->add(new Command\GenerateAddonCommand());
     $this->add(new Command\GenerateHtaccessCommand());
     $this->add(new Command\DbDumpCommand());
     $this->add(new Command\DeleteTemplateCommand());
     $this->add(new Command\DeleteTemplateGroupCommand());
     $this->add(new Command\DeleteSnippetCommand());
     $this->add(new Command\DeleteGlobalVariableCommand());
     $this->add(new Command\SyncTemplatesCommand());
     $this->add(new Command\ShowTemplatesCommand());
 }
예제 #21
0
 /** @test */
 public function it_converts_exception_to_json()
 {
     $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
     $resolver->expects($this->once())->method('getController')->will($this->returnValue(function () {
         throw new NotFoundHttpException();
     }));
     $resolver->expects($this->once())->method('getArguments')->will($this->returnValue([]));
     $logger = $this->getMock('Psr\\Log\\LoggerInterface');
     $logger->expects($this->once())->method('error');
     $dispatcher = new EventDispatcher();
     $httpKernel = new HttpKernel($dispatcher, $resolver);
     $kernel = new KernelForTest('test', true);
     $kernel->boot();
     $kernel->getContainer()->set('http_kernel', $httpKernel);
     $dispatcher->addSubscriber(new RequestFormatNegotiationListener());
     $dispatcher->addSubscriber(new RequestFormatValidationListener());
     $dispatcher->addSubscriber(new ResponseConversionListener());
     $dispatcher->addSubscriber(new ExceptionConversionListener($logger));
     $request = Request::create('/exception', 'GET', [], [], [], ['HTTP_ACCEPT' => 'application/json']);
     $request->attributes->set('_format', 'json');
     $response = $kernel->handle($request)->prepare($request);
     $this->assertSame(404, $response->getStatusCode());
     $this->assertSame('application/vnd.error+json', $response->headers->get('Content-Type'));
     $this->assertJsonStringEqualsJsonString(json_encode(['message' => 'Not Found']), $response->getContent());
 }
예제 #22
0
 protected function fire($event, Event $eventType)
 {
     foreach ($this->scenario->getGroups() as $group) {
         $this->dispatcher->dispatch($event . '.' . $group, $eventType);
     }
     $this->dispatcher->dispatch($event, $eventType);
 }
예제 #23
0
 /**
  * Constructor.
  */
 public function __construct()
 {
     $app = $this;
     $this['autoloader'] = $this->share(function () {
         $loader = new UniversalClassLoader();
         $loader->register();
         return $loader;
     });
     $this['routes'] = $this->share(function () {
         return new RouteCollection();
     });
     $this['controllers'] = $this->share(function () use($app) {
         return new ControllerCollection($app['routes']);
     });
     $this['dispatcher'] = $this->share(function () use($app) {
         $dispatcher = new EventDispatcher();
         $dispatcher->addSubscriber($app);
         return $dispatcher;
     });
     $this['resolver'] = $this->share(function () {
         return new ControllerResolver();
     });
     $this['kernel'] = $this->share(function () use($app) {
         return new HttpKernel($app['dispatcher'], $app['resolver']);
     });
     $this['request.http_port'] = 80;
     $this['request.https_port'] = 443;
 }
 /**
  * Use this method to build the container with the services that you need.
  * @param ContainerBuilder $container
  */
 protected function buildContainer(ContainerBuilder $container)
 {
     $eventDispatcher = new EventDispatcher();
     $eventDispatcher->addSubscriber(new Module($container, $eventDispatcher));
     $container->set("event_dispatcher", $eventDispatcher);
     $container->setParameter('kernel.cache_dir', THELIA_CACHE_DIR . 'dev');
 }
예제 #25
0
 /**
  * @test
  * @expectedException RuntimeException
  */
 function shouldFailToPaginateUnsupportedValue()
 {
     $dispatcher = new EventDispatcher();
     $dispatcher->addSubscriber(new PaginationSubscriber());
     $p = new Paginator($dispatcher);
     $view = $p->paginate(null, 1, 10);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $codeLocation = $input->getArgument('code-location');
     $codeDestination = $input->getOption('code-destination');
     $createNamespace = $input->getOption('create-namespace');
     $offset = $input->getOption('offset');
     $length = $input->getOption('length');
     $classyfile = new ClassyFile();
     $dispatcher = new EventDispatcher();
     if ($input->getOption('constants-to-upper')) {
         $plugin = new ConstantNamesToUpper();
         $dispatcher->addSubscriber($plugin);
     }
     if ($input->getOption('psr-fix')) {
         $plugin = new PhpCsFixer($input, $output);
         $dispatcher->addSubscriber($plugin);
     }
     if ($input->getOption('remove-top-comment')) {
         $classyfile->setTemplate(new BasicClassTemplate(''), 'getTemplate');
     }
     $classyfile->setEventDispatcher($dispatcher);
     if ($createNamespace) {
         $classyfile->generateClassFiles($codeDestination, $codeLocation, $offset, $length);
     } else {
         $classyfile->generateClassFiles($codeDestination, $codeLocation);
     }
 }
예제 #27
0
 /**
  * Method to add the ResponseListener which sets the cookie. Should only be called once
  *
  * @see also http://slides.seld.be/?file=2011-10-20+High+Performance+Websites+with+Symfony2.html#45
  *
  * @return void
  */
 public function addCookieResponseListener()
 {
     if ($this->cookieListenerisAdded !== true) {
         $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onResponse'));
     }
     $this->cookieListenerisAdded = true;
 }
예제 #28
0
 /**
  * @inheritdoc
  */
 public function configureSingleState(EventDispatcher $dispatcher)
 {
     $dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
         /** @var ConsoleCommand $command */
         $command = $event->getCommand();
         if (!$command instanceof ConsoleCommand or $command->isSingleInstance() == false) {
             return;
         }
         $commandState = new CommandState($command);
         if ($commandState->isAlive()) {
             $event->getOutput()->writeln('Already running: ' . $command->getName() . ' Pid:' . $commandState->getPid());
             $event->disableCommand();
         } else {
             $commandState->setPid(getmypid());
         }
     });
     $dispatcher->addListener(ConsoleEvents::TERMINATE, function (ConsoleTerminateEvent $event) {
         /** @var ConsoleCommand $command */
         $command = $event->getCommand();
         if (!$command instanceof ConsoleCommand or $command->isSingleInstance() == false) {
             return;
         }
         if ($event->getExitCode() === 0) {
             (new CommandState($command))->unlink();
         }
     });
     return $dispatcher;
 }
예제 #29
0
 public function testConsoleEvent()
 {
     $dispatcher = new EventDispatcher();
     $listener = new DebugHandlersListener(null);
     $app = $this->getMock('Symfony\\Component\\Console\\Application');
     $app->expects($this->once())->method('getHelperSet')->will($this->returnValue(new HelperSet()));
     $command = new Command(__FUNCTION__);
     $command->setApplication($app);
     $event = new ConsoleEvent($command, new ArgvInput(), new ConsoleOutput());
     $dispatcher->addSubscriber($listener);
     $xListeners = array(KernelEvents::REQUEST => array(array($listener, 'configure')), ConsoleEvents::COMMAND => array(array($listener, 'configure')));
     $this->assertSame($xListeners, $dispatcher->getListeners());
     $exception = null;
     $eHandler = new ErrorHandler();
     set_error_handler(array($eHandler, 'handleError'));
     set_exception_handler(array($eHandler, 'handleException'));
     try {
         $dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
     } catch (\Exception $exception) {
     }
     restore_exception_handler();
     restore_error_handler();
     if (null !== $exception) {
         throw $exception;
     }
     $xHandler = $eHandler->setExceptionHandler('var_dump');
     $this->assertInstanceOf('Closure', $xHandler);
     $app->expects($this->once())->method('renderException');
     $xHandler(new \Exception());
 }
예제 #30
0
 /**
  * On dispatch event listener - called on any event
  *
  * @param Event $event
  * @param string $eventName
  * @param EventDispatcher $dispatcher
  * @return void
  */
 public function onRetry(Amqp\AmqpEvent $event, $eventName, EventDispatcher $dispatcher)
 {
     if ($ev = $this->getQueueEvent($event)) {
         $this->log("INFO", "", $ev);
         try {
             $dispatcher->dispatch($ev->getRoutingKey(), $ev);
             if ($ev->isConsumed()) {
                 $ev->ack();
             }
         } catch (\Exception $e) {
             $this->log("ERROR", "FAILED", $ev, ["message" => $e->getMessage(), "code" => $e->getCode(), "class" => get_class($e)]);
             $ev->reject();
         }
         if (!$ev->isConsumed()) {
             $this->log("ERROR", "NOT CONSUMED", $ev);
             $ev->reject();
         }
         if ($this->stopPropagation) {
             $event->stopPropagation();
         }
         $event->ack();
     } else {
         $this->log("NOTICE", "INVALID", $event);
     }
 }