addListener() публичный Метод

См. также: EventDispatcherInterface::addListener
public addListener ( $eventName, $listener, $priority )
Пример #1
0
 public function __construct(EventDispatcher $dispatcher)
 {
     $this->stdErr = fopen('php://stderr', 'w');
     $this->output = new StreamOutput($this->stdErr);
     $this->eventDispatcher = $dispatcher;
     $this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, array($this, 'onFixerFileProcessed'));
 }
Пример #2
0
 public function __construct()
 {
     parent::__construct(Berk::NAME, Berk::VERSION);
     $time = time();
     $dispatcher = new EventDispatcher();
     $dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
         $output = $event->getOutput();
         $directory = Git::getWorkingDirectory();
         chdir($directory);
         $output->writeln('<info>Changed current directory to: ' . $directory . '</info>');
         $output->writeln('');
         $command = $event->getCommand();
         if ($command instanceof Command) {
             $command->setBerk(new Berk());
         }
     });
     $dispatcher->addListener(ConsoleEvents::TERMINATE, function (ConsoleTerminateEvent $event) use($time) {
         $output = $event->getOutput();
         $time = time() - $time;
         $output->writeln('');
         $output->writeln('<info>Command completed in ' . $time . ' seconds. Bye.</info>');
     });
     $this->setDispatcher($dispatcher);
     $this->add(new ServerCommand());
     $this->add(new ExportCommand());
     $this->add(new DeployCommand());
 }
Пример #3
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;
 }
 public function __construct()
 {
     $this->dispatcher = new EventDispatcher();
     $this->dispatcher->addListener(Events::TRANSFER_PRE, array(new Listener\Transfer\PreEventListener(), 'onPreAction'));
     $this->dispatcher->addListener(Events::TRANSFER_POST, array(new Listener\Transfer\PostEventListener(), 'onPostAction'));
     $this->dispatcher->addListener(Events::TRANSFER_TOTAL_TIMEOUT, array(new Listener\Transfer\TotalTimeoutEventListener(), 'onTimeoutAction'));
 }
Пример #5
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());
 }
 /**
  * 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;
 }
Пример #7
0
 public function test()
 {
     $eventDispatcher = new EventDispatcher();
     $eventDispatcher->addListener(ImportItemEvent::AFTER_READ, array($this, 'onAfterRead'));
     $eventDispatcher->addListener(ImportItemEvent::AFTER_FILTER, array($this, 'onAfterFilter'));
     $eventDispatcher->addListener(ImportItemEvent::AFTER_CONVERSION, array($this, 'onAfterConversion'));
     $eventDispatcher->addListener(ImportItemEvent::AFTER_CONVERSIONFILTER, array($this, 'onAfterConversionFilter'));
     $eventDispatcher->addListener(ImportItemEvent::AFTER_WRITE, array($this, 'onAfterWrite'));
     $fileDir = __DIR__ . '/../../../../../metadata/testfiles';
     $finder = Finder::create()->in($fileDir)->name('*');
     $lfsp = new FinderFileStorageProvider($finder);
     $lfsp->setStorageFactory(new FormatDiscoverLocalFileStorageFactory(new MimeTypeDiscoverStrategy(array('text/plain' => new CsvAutoDelimiterFormatFactory()))));
     $storageLocator = new StorageLocator();
     $storageLocator->register('defaultProvider', $lfsp);
     $array = array();
     $targetStorage = new ArrayStorage($array);
     $importer = Importer::build($targetStorage);
     $importRepository = new ImporterRepository();
     $importRepository->register('defaultImporter', $importer);
     $importRequest = new ImportRequest($fileDir . '/100.csv', 'defaultProvider', 'defaultImporter');
     $importBuilder = new ImportBuilder($importRepository, $storageLocator);
     $import = $importBuilder->buildFromRequest($importRequest);
     $import->mappings()->add('prefix', 'Anrede', 'upperCase')->add('name', 'Name', 'lowerCase');
     $importRunner = new ImportRunner(new DefaultWorkflowFactory($eventDispatcher));
     $expectedResult = array('Name' => 'jennie abernathy', 'Anrede' => 'MS.', 'street' => '866 Hyatt Isle Apt. 888', 'zip' => '65982', 'city' => 'East Laurie', 'phone' => '(551)436-0391', 'email' => '*****@*****.**');
     $previewResult = $importRunner->preview($import, 0);
     $this->assertEquals($expectedResult, $previewResult['to']);
 }
Пример #8
0
 /**
  * Add a callback to a channel which will get triggered when channel receives a message via a publisher.
  *
  * @param string   $channel
  * @param callable $callback
  * @param int      $priority  Default: 0
  *
  * @return PubSubManager
  * @throws InvalidArgumentException
  */
 public function addListener($channel, callable $callback, $priority = 0)
 {
     if (empty($channel)) {
         throw new InvalidArgumentException('Empty event channel name supplied.');
     }
     $this->event_dispatcher->addListener(static::generateEventName($channel), $callback, $priority);
     return $this;
 }
 /**
  * Subscribes the message handler to the bus.
  * @param MessageHandlerInterface $messageHandler The message handler.
  */
 public function subscribe(MessageHandlerInterface $messageHandler)
 {
     foreach ($messageHandler->getMessageSubscriptions() as $subscription) {
         $this->eventDispatcher->addListener($subscription, function (GenericEvent $event) use($messageHandler) {
             $messageHandler->handle($event->getSubject());
         });
     }
 }
Пример #10
0
 /**
  * Set all hooks
  *
  * @return  void
  */
 protected function addHooks()
 {
     $dispatcher = new EventDispatcher();
     $dispatcher->addListener(ConsoleEvents::COMMAND, new Header());
     $dispatcher->addListener(ConsoleEvents::COMMAND, new ValidateDependencies());
     $dispatcher->addListener(ConsoleEvents::TERMINATE, new TotalTime($this->timeStart));
     $this->setDispatcher($dispatcher);
 }
Пример #11
0
 public function __construct()
 {
     $this->repository = new InMemoryExpenseListRepository();
     $dispatcher = new EventDispatcher();
     $this->createExpenseListCase = new CreateExpenseList($this->repository, $dispatcher);
     $dispatcher->addListener(CreateExpenseList::SUCCESS, [$this, 'recordNotification']);
     $dispatcher->addListener(CreateExpenseList::FAILURE, [$this, 'recordNotification']);
 }
Пример #12
0
 public function testTearDown()
 {
     $events = array();
     $this->dispatcher->addListener('test.after', function ($e) use(&$events) {
         $events[] = $e->getName();
     });
     $this->testcase->tearDown();
     $this->assertEquals($events, array('test.after'));
 }
Пример #13
0
 /**
  * Add listeners to $this->dispatcher which record each invocation of $monitoredEvents
  * in $this->actualEventSequence.
  *
  * @param array $monitoredEvents
  *   List of event names.
  *
  */
 public function monitorEvents($monitoredEvents)
 {
     foreach ($monitoredEvents as $monitoredEvent) {
         $test = $this;
         $this->dispatcher->addListener($monitoredEvent, function ($event) use($monitoredEvent, &$test) {
             $test->actualEventSequence[] = array('name' => $monitoredEvent, 'class' => get_class($event));
         }, 2 * Events::W_EARLY);
     }
 }
 /**
  * Attach all event listeners to the $eventDispatcher.
  */
 private function attachListeners()
 {
     // Create the listeners.
     $logReferralReasonsListener = new LogReferralReasonsListener(new Datasource_Insurance_PolicyNotes());
     $dispatchReferralEmailListener = new DispatchReferralEmailListener($this->getContainer()->get('twig'), $this->_params, new Application_Core_Mail());
     // The above two listeners are both listening for the RRPEvents::POLICY_REFERRED event to be fired.
     $this->eventDispatcher->addListener(RRPEvents::POLICY_REFERRED, array($logReferralReasonsListener, 'onReferral'));
     $this->eventDispatcher->addListener(RRPEvents::POLICY_REFERRED, array($dispatchReferralEmailListener, 'onReferral'));
 }
Пример #15
0
 public function setUp()
 {
     $this->dispatcher = new EventDispatcher('UTF-8');
     $listener = new RequestListener($this->dispatcher);
     $this->dispatcher->addListener(KernelEvents::REQUEST, [$listener, 'onKernelRequest']);
     $this->dispatcher->addListener(QPushEvents::Notification('ironmq-test'), [$this, 'IronMqOnNotificationReceived']);
     $this->dispatcher->addListener(QPushEvents::Notification('aws-test'), [$this, 'AwsOnNotificationReceived']);
     $this->kernel = $this->getMock('Symfony\\Component\\HttpKernel\\HttpKernelInterface');
 }
 /**
  * {@inheritdoc}
  */
 public function subscribe(SubscriberInterface $subscriber)
 {
     foreach ($subscriber->getSubscriptions() as $subscription) {
         $this->eventDispatcher->addListener($subscription[0], function (GenericEvent $event) use($subscription) {
             call_user_func($subscription[1], $event->getSubject());
         }, isset($subscription[2]) ? $subscription[2] : 0);
     }
     return $this;
 }
Пример #17
0
 protected function setUp()
 {
     $this->useTransaction(TRUE);
     parent::setUp();
     $this->dispatcher = new EventDispatcher();
     $this->dispatcher->addListener(Events::TOKEN_REGISTER, array($this, 'onListTokens'));
     $this->dispatcher->addListener(Events::TOKEN_EVALUATE, array($this, 'onEvalTokens'));
     $this->counts = array('onListTokens' => 0, 'onEvalTokens' => 0);
 }
 /**
  * Registers the collector through warden's event dispatcher
  *
  * @param \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher
  * @return void
  */
 public function register($eventDispatcher)
 {
     $this->stack = new DebugStack();
     $eventDispatcher->addListener(WardenEvents::WARDEN_START, function (StartEvent $event) {
         $this->registerStack();
     });
     $eventDispatcher->addListener(WardenEvents::WARDEN_END, function (StopEvent $event) {
         $event->params->setValue('query_limit', $this->stack->currentQuery);
     });
 }
Пример #19
0
 public static function getEventDispatchers()
 {
     $eventDispatcher = new EventDispatcher();
     $eventDispatcher->addListener('event1', 'global_function');
     $eventDispatcher->addListener('event1', function () {
         return 'Closure';
     });
     $eventDispatcher->addListener('event2', new CallableClass());
     return array('event_dispatcher_1' => $eventDispatcher);
 }
 /**
  * @param $event
  * @param $listener
  */
 public function listen($event, $listener)
 {
     if (is_string($listener)) {
         if (class_exists($listener)) {
             $this->dispatcher->addListener($event, [new $listener(), 'handle']);
         }
     } else {
         $this->dispatcher->addListener($event, [$listener, 'handle']);
     }
 }
Пример #21
0
 /**
  * Makes this field to a multiple.
  *
  * @param Field $field The field object
  *
  * @return Field
  */
 public function multiple(Field $proto)
 {
     $resizer = new MultipleResizeListener();
     $name = $proto->getInternalName();
     $disp = new EventDispatcher();
     $field = new Field($name, $disp, $proto->getExtensions());
     $field->setOption('prototype', $proto);
     $disp->addListener(Events::BIND, [$resizer, 'bind']);
     $disp->addListener(Events::FILL, [$resizer, 'fill']);
     return $field;
 }
Пример #22
0
 public function setUp()
 {
     $this->manager = $this->getContainer()->get('rc_servired.transaction.manager');
     $this->listener = $this->getMock('RC\\ServiredBundle\\Tests\\Resources\\Event\\TransactionListenerTest');
     $this->dispatcher = $this->getContainer()->get('event_dispatcher');
     $this->dispatcher->addListener(ServiredEvent::PRE_PAYMENT_SUCCESS, array($this->listener, 'prePaymentSuccess'));
     $this->dispatcher->addListener(ServiredEvent::PRE_PAYMENT_FAILED, array($this->listener, 'prePaymentFailed'));
     $this->dispatcher->addListener(ServiredEvent::POST_PAYMENT_SUCCESS, array($this->listener, 'postPaymentSuccess'));
     $this->dispatcher->addListener(ServiredEvent::POST_PAYMENT_FAILED, array($this->listener, 'postPaymentFailed'));
     $this->transaction = new Transaction(time());
 }
Пример #23
0
 public function __construct($options = array())
 {
     $this->optionable = new Optionable($options, $this);
     $this->setupDefaults();
     $this->poc = $this->optionable[PocLogsParams::PARAM_POC];
     $this->logger = $this->poc->getLogger();
     $this->pocDispatcher = $this->poc->getPocDispatcher();
     $this->pocDispatcher->addListener(ROIProtectorEventNames::CONSULT_STARTED, array($this, 'consultLogger'));
     $this->pocDispatcher->addListener(ROIProtectorEventNames::CONSULT_STARTED_NOT_FIRST, array($this, 'consultFirstLogger'));
     $this->pocDispatcher->addListener(ROIProtectorEventNames::CONSULT_STARTED_FIRST, array($this, 'consultNotFirstLogger'));
     $this->pocDispatcher->addListener(ROIProtectorEventNames::CONSULT_SLEEP, array($this, 'consultSleep'));
     // 'I am sleeping '.$sentinelCnt);
 }
Пример #24
0
 /**
  * @group core
  */
 public function testRunStepEvents()
 {
     $events = array();
     $this->dispatcher->addListener('step.before', function () use(&$events) {
         $events[] = 'step.before';
     });
     $this->dispatcher->addListener('step.after', function () use(&$events) {
         $events[] = 'step.after';
     });
     $step = new \Codeception\Step\Action('seeEquals', array(5, 5));
     $this->testcase->runStep($step);
     $this->assertEquals($events, array('step.before', 'step.after'));
 }
Пример #25
0
 public function testRun()
 {
     $events = array();
     $this->dispatcher->addListener('suite.before', function ($e) use(&$events) {
         $events[] = $e->getName();
     });
     $this->dispatcher->addListener('suite.after', function ($e) use(&$events) {
         $events[] = $e->getName();
     });
     $runner = $this->suiteman->run(new PHPUnit_Framework_TestResult(), array('colors' => false, 'steps' => true, 'debug' => false));
     $this->assertEquals($events, array('suite.before', 'suite.after'));
     $this->assertInstanceOf('\\Codeception\\PHPUnit\\Runner', $runner);
 }
 /**
  * @param string $loginId
  * @param string $apiKey
  *
  * @return CurrencyCloud
  */
 protected function getClient($loginId = '*****@*****.**', $apiKey = 'ef0fd50fca1fb14c1fab3a8436b9ecb65f02f129fd87eafa45ded8ae257528f0')
 {
     //We do not use static method in CurrencyCloud because we are not testing it
     $session = new Session(Session::ENVIRONMENT_DEMONSTRATION, $loginId, $apiKey);
     $eventDispatcher = new EventDispatcher();
     $client = new Client($session, new \GuzzleHttp\Client(['sync' => true, 'handler' => HandlerStack::create(new CurlHandler(['handle_factory' => new CurlFactory(0)]))]), $eventDispatcher);
     $authenticateEntryPoint = new AuthenticateEntryPoint($session, $client);
     $eventDispatcher->addListener(ClientHttpErrorEvent::NAME, [new ClientHttpErrorListener(), 'onClientHttpErrorEvent'], -255);
     $eventDispatcher->addListener(ClientHttpErrorEvent::NAME, [new SessionTimeoutListener($client, $authenticateEntryPoint), 'onClientHttpErrorEvent'], -254);
     $eventDispatcher->addListener(BeforeClientRequestEvent::NAME, [new BeforeClientRequestListener($session, $authenticateEntryPoint), 'onBeforeClientRequestEvent'], -255);
     $entityManager = new SimpleEntityManager();
     return new CurrencyCloud($session, $authenticateEntryPoint, new AccountsEntryPoint($entityManager, $client), new BalancesEntryPoint($client), new BeneficiariesEntryPoint($entityManager, $client), new ContactsEntryPoint($entityManager, $client), new ConversionsEntryPoint($client), new PayersEntryPoint($client), new PaymentsEntryPoint($entityManager, $client), new ReferenceEntryPoint($client), new RatesEntryPoint($client), new SettlementsEntryPoint($entityManager, $client), new TransactionsEntryPoint($client));
 }
Пример #27
0
 /**
  * Run the application
  */
 public function run()
 {
     $request = Request::createFromGlobals();
     $context = new RequestContext();
     $context->fromRequest($request);
     if (!$this->isRoutesDefined) {
         $this->defineRoutes();
     }
     $this->matcher = new UrlMatcher($this->routes, $context);
     $this->resolver = new ControllerResolver();
     $this->dispatcher->addListener('post.controller', array($this->container->get('listener.post_controller'), 'onPostController'));
     $response = $this->handle($request);
     $response->send();
 }
Пример #28
0
 public function init()
 {
     $this->dispatcher = new EventDispatcher();
     foreach ($this->events as $event => $listeners) {
         foreach ($listeners as $listener) {
             $this->dispatcher->addListener($event, $listener);
         }
     }
     foreach ($this->subscribers as $event => $subscribers) {
         foreach ($subscribers as $subscriber) {
             $this->dispatcher->addSubscriber($subscriber);
         }
     }
     parent::init();
 }
 /**
  * Create a new cookie driver.
  *
  * @param EventDispatcher $dispatcher
  * @param  string|array $options
  */
 public function __construct(EventDispatcher $dispatcher, $options = array())
 {
     $this->dispatcher = $dispatcher;
     $this->request = Request::createFromGlobals();
     // for the earliest reasons
     if (is_array($options)) {
         $this->options = array_merge($this->options, $options);
     } else {
         $this->options['name'] = $options;
     }
     $this->dataOptions = array_merge($this->options, array('value' => $this->request->cookies->get($this->options['name'])));
     // cloning the array
     $this->dispatcher->addListener(KernelEvents::REQUEST, array($this, 'onKernelRequest'));
     $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
 }
Пример #30
0
 public function testGroupEventsAreFired()
 {
     $events = [];
     $eventListener = function ($event, $eventName) use(&$events) {
         $events[] = $eventName;
     };
     $this->dispatcher->addListener('test.before', $eventListener);
     $this->dispatcher->addListener('test.before.admin', $eventListener);
     $this->dispatcher->addListener('test.after', $eventListener);
     $this->dispatcher->addListener('test.after.admin', $eventListener);
     $this->suiteman->loadTests(codecept_data_dir() . 'SimpleAdminGroupCest.php');
     $this->suiteman->run($this->runner, new \PHPUnit_Framework_TestResult(), ['silent' => true, 'colors' => false, 'steps' => true, 'debug' => false]);
     $this->assertContains('test.before', $events);
     $this->assertContains('test.before.admin', $events);
     $this->assertContains('test.after.admin', $events);
 }