/**
  * 
  * @see PHPUnit_Framework_TestCase::setUp()
  */
 public function setUp()
 {
     vfsStream::setup(self::TEST_LOGPATH);
     $this->destfile = vfsStream::url(self::TEST_LOGPATH . '/test.log');
     date_default_timezone_set('Asia/Shanghai');
     $logger = new Logger();
     $logger->addWriter('stream', null, array('stream' => $this->destfile));
     $this->events = new EventManager();
     $this->events->attach(new AuthLoggerListener($logger));
 }
 public function register(Slim $app)
 {
     $app->container->singleton('cache', function () {
         return new FilesystemCache('tmp/cache/db');
     });
     $app->container->singleton('connection', function () {
         $dbOptions = (require 'config/connection.config.php');
         $config = new Configuration();
         return DriverManager::getConnection($dbOptions, $config);
     });
     $app->container->singleton('log', function () {
         $logger = new Logger('echale-gas');
         $logger->pushHandler(new StreamHandler('tmp/logs/app.log', LogLevel::DEBUG));
         return $logger;
     });
     $app->container->singleton('paginator', function () use($app) {
         return new PagerfantaPaginator($app->config('defaultPageSize'));
     });
     $app->container->singleton('paginatorFactory', function () use($app) {
         return new PaginatorFactory($app->paginator);
     });
     $app->container->singleton('proxiesConfiguration', function () use($app) {
         $config = new ProxyConfiguration();
         $config->setProxiesTargetDir('tmp/cache/proxies');
         spl_autoload_register($config->getProxyAutoloader());
         return $config;
     });
     $app->urlHelper = new TwigExtension();
     $app->container->singleton('twig', function () use($app) {
         $twig = new Twig();
         $twig->parserOptions = ['charset' => 'utf-8', 'cache' => realpath('tmp/cache/twig'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true];
         $twig->parserExtensions = [$app->urlHelper, new HalRendererExtension()];
         return $twig;
     });
     $app->container->singleton('controllerEvents', function () use($app) {
         $eventManager = new EventManager();
         // Ensure rendering is performed at the end by assigning a very low priority
         $eventManager->attach('postDispatch', new RenderResourceListener($app->twig), -100);
         $eventManager->attach('renderErrors', new RenderErrorsListener($app->twig), -100);
         return $eventManager;
     });
     $app->container->singleton('controller', function () use($app) {
         $controller = new RestController($app->request(), $app->response());
         $factory = new RestControllerProxyFactory($app->proxiesConfiguration, $app->controllerEvents);
         $controller = $factory->createProxy($controller);
         $factory->addEventManagement($controller);
         return $controller;
     });
     $app->view($app->twig);
 }
Example #3
0
 /**
  * @param \Zend\EventManager\EventManager $eventManager
  */
 public function let($eventManager)
 {
     $eventManager->trigger(Argument::cetera())->willReturn(true);
     $eventManager->setIdentifiers(Argument::cetera())->willReturn(true);
     $eventManager->attach(Argument::cetera())->willReturn(true);
     $this->setEventManager($eventManager);
 }
 /**
  * 测试能正常注册身份验证过程中的事件监听器。
  */
 public function testEventManagerHasDefaultListeners()
 {
     $eventManager = new EventManager();
     $eventManager->attach($this->stub);
     $this->assertFalse($eventManager->getListeners(Event::EVENT_VERIFY_POST)->isEmpty());
     $this->assertFalse($eventManager->getListeners(Event::EVENT_TOKEN_POST)->isEmpty());
     $this->assertFalse($eventManager->getListeners(Event::EVENT_FAILURE)->isEmpty());
 }
 /**
  * {@inheritDoc}
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     /* @var $logger \OcraServiceManager\ServiceManager\Logger */
     $logger = $serviceLocator->get('OcraServiceManager\\ServiceManager\\Logger');
     $eventManager = new EventManager();
     $eventManager->attach($logger);
     return $eventManager;
 }
 public function setUp()
 {
     $resourceFactory = new UserRolesResourceFactory();
     /** @var \Zfegg\Admin\V1\Rest\UserRoles\UserRolesResource $resources */
     $resources = $resourceFactory($this->getServices());
     $events = new EventManager();
     $this->listener = $resources;
     $events->attach($this->listener);
 }
 public function testAttach()
 {
     $eventManager = new EventManager();
     $listener = new BodyClassListener(new BodyClass());
     $before = $eventManager->getListeners(\Zend\Mvc\MvcEvent::EVENT_DISPATCH);
     $this->assertCount(0, $before);
     $eventManager->attach($listener);
     $after = $eventManager->getListeners(\Zend\Mvc\MvcEvent::EVENT_DISPATCH);
     $this->assertCount(1, $after);
 }
Example #8
0
 /**
  * Test if firewall is on
  */
 public function testFirewallOn()
 {
     self::setUpFirewallOn();
     $spyListener = new SpyingFirewallListener();
     $spyListener->setServiceLocator($this->getServiceManager());
     $eventManager = new EventManager();
     $eventManager->attach($spyListener);
     $eventManager->trigger(FirewallEvent::EVENT_FIREWALL_DISPATCH);
     $this->assertTrue($spyListener->isFirewallEnabled());
 }
Example #9
0
 public function testAttachesToRouteEventAtNegativePriority()
 {
     $events = new EventManager();
     $events->attach($this->listener);
     $listeners = $events->getListeners('route');
     $this->assertEquals(1, count($listeners));
     $this->assertTrue($listeners->hasPriority(-41));
     $callback = $listeners->getIterator()->current()->getCallback();
     $test     = array_shift($callback);
     $this->assertSame($this->listener, $test);
 }
 public function testGetDashboard()
 {
     $eventManager = new EventManager();
     $eventManager->attach(DashboardEvent::DASHBOARD_RENDER_EVENT, function (DashboardEvent $event) {
         $viewModel = $event->getDashboardViewModel();
         $viewModel->setVariable('foo', 'bar');
     });
     $controller = new DashboardController();
     $controller->setEventManager($eventManager);
     $result = $controller->indexAction();
     $this->assertInstanceOf('Zend\\View\\Model\\ModelInterface', $result);
     $this->assertEquals('bar', $result->getVariable('foo'));
 }
 public function indexAction()
 {
     $events = new EventManager();
     $events->attach('do', function ($e) {
         $event = $e->getName();
         $params = $e->getParams();
         printf('Handled event "%s" with parameter "%s"', $event, json_encode($params));
     });
     $params = array('foo' => 'bar', 'baz' => 'bat');
     $events->trigger('do', null, $params);
     //event, target, parameter
     //print : Handled event "do" with parameter "{"foo":"bar","baz":"bat"}"
 }
 public function testListenerAttached()
 {
     $events = new EventManager();
     $events->attach($this->listener);
     $listeners = $events->getListeners(MvcEvent::EVENT_DISPATCH_ERROR);
     $this->assertEquals(1, count($listeners));
     $listeners = $events->getListeners(MvcEvent::EVENT_RENDER_ERROR);
     $this->assertEquals(1, count($listeners));
     $events->detach($this->listener);
     $listeners = $events->getListeners(MvcEvent::EVENT_DISPATCH_ERROR);
     $this->assertEquals(0, count($listeners));
     $listeners = $events->getListeners(MvcEvent::EVENT_RENDER_ERROR);
     $this->assertEquals(0, count($listeners));
 }
 public function setDbAdapter(Adapter $adapter)
 {
     $this->adapter = $adapter;
     $this->resultSetPrototype = new HydratingResultSet(new ClassMethods(), new User());
     if (!$this->featureSet instanceof FeatureSet) {
         $this->featureSet = new FeatureSet();
     }
     $eventManager = new EventManager();
     $eventManager->attach(['preSelect', 'preUpdate', 'preDelete', 'preInsert'], function (EventInterface $event) {
         $sqlKey = strtolower(str_replace('pre', '', $event->getName()));
         echo $event->getParam($sqlKey)->getSqlString($event->getTarget()->getAdapter()->getPlatform()), '<br>';
     });
     $this->featureSet->addFeature(new EventFeature($eventManager));
     $this->initialize();
 }
Example #14
0
 public function testAddExistingNotChangedEntity()
 {
     $id = 111;
     $data = ['id' => $id, 'name' => 'some name', 'status' => 1];
     $originalEntity = new SimpleEntity($data);
     $changedEntity = clone $originalEntity;
     $this->identityMapOriginalMock->offsetSet($id, $originalEntity);
     $this->identityMapMock->offsetSet($id, $originalEntity);
     $this->dbMapperMock->expects($this->never())->method('toTableRow');
     $this->tableGatewayMock->expects($this->never())->method('updateByPrimaryKey');
     $callbackMock = $this->getMock('stdClass', array('onChangeEntity'));
     $callbackMock->expects($this->never())->method('onChangeEntity')->will($this->returnValue(true));
     $this->eventManagerMock->attach('entity:T4webBaseTest\\Domain\\Assets\\SimpleEntity:changed', array($callbackMock, 'onChangeEntity'));
     $this->dbRepository->add($changedEntity);
 }
Example #15
0
 public function testPostDelete()
 {
     $closureHasRun = false;
     /** @var $event EventFeature\TableGatewayEvent */
     $event = null;
     $this->eventManager->attach('postDelete', function ($e) use(&$closureHasRun, &$event) {
         $event = $e;
         $closureHasRun = true;
     });
     $this->feature->postDelete($stmt = $this->getMock('Zend\\Db\\Adapter\\Driver\\StatementInterface'), $result = $this->getMock('Zend\\Db\\Adapter\\Driver\\ResultInterface'));
     $this->assertTrue($closureHasRun);
     $this->assertInstanceOf('Zend\\Db\\TableGateway\\TableGateway', $event->getTarget());
     $this->assertEquals('postDelete', $event->getName());
     $this->assertSame($stmt, $event->getParam('statement'));
     $this->assertSame($result, $event->getParam('result'));
 }
 /**
  * Verifies that `registerViaProvider` event is triggered during registration process with GitHub account
  * in ScnSocialAuth module as prevention against regression.
  *
  * @link https://github.com/zendframework/modules.zendframework.com/pull/286
  */
 public function testEventIsTriggered()
 {
     $triggered = false;
     $eventManager = new EventManager();
     $eventManager->attach('registerViaProvider', function () use(&$triggered) {
         $triggered = true;
     });
     $mapper = $this->getMockBuilder('ZfcUser\\Mapper\\UserInterface')->getMockForAbstractClass();
     $hybridAuth = new HybridAuth();
     $hybridAuth->setEventManager($eventManager);
     $hybridAuth->setServiceManager($this->serviceManager);
     $hybridAuth->setZfcUserMapper($mapper);
     $class = new ReflectionClass($hybridAuth);
     $method = $class->getMethod('githubToLocalUser');
     $method->setAccessible(true);
     $method->invokeArgs($hybridAuth, [new Hybrid_User_Profile()]);
     $this->assertTrue($triggered);
 }
 /**
  * @SWG\Property(name="station_id",type="integer",description="Unique identifier of the gas station")
  * @SWG\Property(name="name",type="string",description="Name of the gas station")
  * @SWG\Property(name="social_reason",type="string",description="Official name of the gas station")
  * @SWG\Property(name="address_line_1",type="string",description="Street name and number of the gas station")
  * @SWG\Property(name="address_line_2",type="string",description="Neighborhood name of the gas station")
  * @SWG\Property(name="location",type="string",description="State and city name where the gas station is located")
  * @SWG\Property(name="latitude",type="double",description="Latitude coordinate")
  * @SWG\Property(name="longitude",type="double",description="Longitude coordinate")
  * @SWG\Property(name="created_at",type="string",format="date-format",description="Registration date of the gas station")
  * @SWG\Property(name="last_updated_at",type="string",format="date-format",description="Most recent date in which the gas station was edited")
  */
 public function register(Slim $app)
 {
     $app->container->singleton('station', function () use($app) {
         return new Model($app->stationTable, $app->stationValidator, $app->paginatorFactory);
     });
     $app->container->singleton('stationFormatter', function () use($app) {
         return new ResourceFormatter($app->urlHelper, 'station', 'station_id');
     });
     $app->container->singleton('stationsFormatter', function () use($app) {
         return new CollectionFormatter($app->urlHelper, 'stations', $app->stationFormatter);
     });
     $app->container->singleton('stationEvents', function () use($app) {
         $eventManager = new EventManager();
         $specification = new ChainedSpecification();
         $specification->addSpecification(new PaginationSpecification($app->config('defaultPageSize')));
         $specification->addSpecification(new GeolocationSpecification());
         $eventManager->attach('postFindAll', new QuerySpecificationListener($specification));
         $eventManager->attachAggregate(new HasTimestampListener());
         $eventManager->attachAggregate(new CacheListener($app->cache, $app->request()->getPathInfo()));
         return $eventManager;
     });
     $app->container->singleton('stationTable', function () use($app) {
         $stationTable = new StationTable('stations', $app->connection);
         $factory = new TableProxyFactory($app->proxiesConfiguration, $app->stationEvents);
         $stationTable = $factory->createProxy($stationTable);
         $factory->addEventManagement($stationTable);
         return $stationTable;
     });
     $app->container->singleton('stationValidator', function () use($app) {
         return new ValitronValidator(require 'config/validations/stations.config.php');
     });
     $app->container->singleton('stationController', function () use($app) {
         $app->controller->setModel($app->station);
         $app->controllerEvents->attach('postDispatch', new FormatResourceListener($app->stationFormatter));
         return $app->controller;
     });
     $app->container->singleton('stationsController', function () use($app) {
         $app->controller->setModel($app->station);
         $app->controllerEvents->attach('postDispatch', new FormatResourceListener($app->stationsFormatter));
         return $app->controller;
     });
 }
Example #18
0
 /**
  * Attach a listener to the session validator chain
  *
  * @param  string $event
  * @param  callable $callback
  * @param  int $priority
  * @return \Zend\Stdlib\CallbackHandler
  */
 public function attach($event, $callback = null, $priority = 1)
 {
     $context = null;
     if ($callback instanceof Validator) {
         $context = $callback;
     } elseif (is_array($callback)) {
         $test = array_shift($callback);
         if ($test instanceof Validator) {
             $context = $test;
         }
         array_unshift($callback, $test);
     }
     if ($context instanceof Validator) {
         $data = $context->getData();
         $name = $context->getName();
         $this->getStorage()->setMetadata('_VALID', array($name => $data));
     }
     $listener = parent::attach($event, $callback, $priority);
     return $listener;
 }
 public function testInvalidAuthentication()
 {
     $authenticationResultMock = $this->getMockBuilder('Zend\\Authentication\\Result', array('getIdentity', 'isValid'))->disableOriginalConstructor()->getMock();
     $authenticationResultMock->expects($this->never())->method('getIdentity');
     $authenticationResultMock->expects($this->once())->method('isValid')->will($this->returnValue(false));
     $authenticationAdapterMock = $this->getMockBuilder('Zend\\Authentication\\Adapter\\ValidatableAdapterInterface', array('authenticate'))->disableOriginalConstructor()->getMock();
     $authenticationAdapterMock->expects($this->once())->method('authenticate')->will($this->returnValue($authenticationResultMock));
     $storageMock = $this->getMockBuilder('Zend\\Authentication\\Storage\\StorageInterface', array('isEmpty', 'read', 'write', 'clear'))->disableOriginalConstructor()->getMock();
     $storageMock->expects($this->once())->method('isEmpty')->will($this->returnValue(true));
     $storageMock->expects($this->never())->method('write');
     $storageMock->expects($this->never())->method('read');
     $authFailEventTriggered = false;
     $eventManager = new EventManager();
     $eventManager->attach(AuthenticationEvent::AUTHENTICATION_FAILURE_EVENT, function () use(&$authFailEventTriggered) {
         $authFailEventTriggered = true;
     });
     $authenticationService = new AuthenticationService($storageMock, $authenticationAdapterMock);
     $authenticationService->setEventManager($eventManager);
     $authenticationService->authenticate();
     $this->assertTrue($authFailEventTriggered);
 }
 public function getClass()
 {
     $method = new ExponentialBackoff();
     $eventManager = new EventManager();
     $callback = function (Event $e) {
         $this->count++;
     };
     $eventManager->attach(ExponentialBackoff::EVENT_PRE_CALL, $callback);
     $eventManager->attach(ExponentialBackoff::EVENT_POST_CALL, $callback);
     $eventManager->attach(ExponentialBackoff::EVENT_EXCEPTION_CALL, $callback);
     $eventManager->attach(ExponentialBackoff::EVENT_SLEEP_CALL, $callback);
     $eventManager->attach(ExponentialBackoff::EVENT_RETRY_CALL, $callback);
     $eventManager->attach(ExponentialBackoff::EVENT_END_CALL, $callback);
     $method->setEventManager($eventManager);
     return $method;
 }
Example #21
0
 public function indexAction()
 {
     /*$foo = new SimpleEvent();
       $foo->getEventManager()->attach('echoHello_pre', function($e){
           echo "Wow! ";
       });
       $foo->getEventManager()->attach('echoHello_post', function($e){
           echo ". This example is very good! \n";
       });
       $foo->getEventManager()->attach('echoHello_post', function($e){
           echo "<br/>by gianarb92@gmail.com";
       }, -10);
       $foo->echoHello();*/
     $events = new EventManager();
     $events->attach('do', function ($e) {
         $event = $e->getName();
         $params = $e->getParams();
         printf('Handled event "%s" with parameter "%s"', $event, json_encode($params));
     });
     $params = array('foo' => 'bar', 'baz' => 'bat');
     $events->trigger('do', null, $params);
     //event, target, parameter
     //print : Handled event "do" with parameter "{"foo":"bar","baz":"bat"}"
 }
Example #22
0
 public function index01Action()
 {
     $eventManager = new \Zend\EventManager\EventManager();
     //        $eventManager->attach('oneEvent', function(){
     //            echo '<h3 style="color:red;">OneEvent</h3>';
     //        });
     $listenerA = $eventManager->attach('oneEvent', function () {
         echo '<h3 style="color:red;">OneEvent</h3>';
     });
     //$eventManager->trigger('oneEvent');
     $listenerB = $eventManager->attach('twoEvent', function () {
         echo '<h3 style="color:red;">TwoEvent</h3>';
     });
     //$eventManager->trigger('twoEvent');
     /** THÊM MỘT CÔNG VIỆC CHO SỰ KIỆN oneEvent */
     $eventManager->attach('oneEvent', function () {
         echo '<h3 style="color:red">EventOneContinue</h3>';
     });
     /** THÊM MỘT CÔNG VIỆC CHO CẢ 2 SỰ KIỆN => oneEvent và twoEvent */
     /** OneEvent => OneEvent, EventOneCon */
     /** TwoEvent => TwoEvent*/
     $eventManager->attach(array('oneEvent', 'twoEvent'), function () {
         echo '<h3 style="color:blue;">Event one Event and two Event</h3>';
     });
     //$eventManager->trigger('oneEvent');
     //$eventManager->trigger('twoEvent');
     /** THÊM MỘT CÔNG VIỆC CHO CẢ NHIỀU SỰ KIỆN => oneEvent và twoEvent */
     /** OneEvent => OneEvent, EventOneCon */
     /** TwoEvent => TwoEvent*/
     $eventManager->attach('treeEvent', function () {
         echo '<h3 style="color:blue;">Event Three - Doing</h3>';
     });
     $eventManager->attach('*', function () {
         echo '<h3 style="color:blue;">Doing</h3>';
     });
     $eventManager->trigger('oneEvent');
     return $this->response;
     /** Không cần layout và view */
 }
Example #23
0
 /** \Zend\EventManager\EventInterface */
 public function index05Action()
 {
     $eventManager = new EventManager();
     $eventManager->attach('eventOne', function (\Zend\EventManager\EventInterface $e) {
     });
     $listener01 = function (\Zend\EventManager\EventInterface $e) {
         echo '<pre>';
         print_r($e);
         echo '</pre>';
         $name = $e->getName();
         $params = $e->getParams();
         $target = $e->getTarget();
         $e->setParam('course', 'default');
         echo $param_name = $e->getParam('course', 'default');
     };
     $eventManager->attach('eventOne', $listener01);
     $params = array('course' => 'Zend Framework 2', 'year' => '2015');
     $eventManager->trigger('eventOne', this, $params);
     return $this->response;
 }
Example #24
0
<?php

/**
 * Copyright (c) 2014 Keith Casey
 *
 * This code is designed to accompany the lynda.com video course "Design Patterns in PHP"
 *   by Keith Casey. If you've received this code without seeing the videos, go watch the
 *   videos. It will make way more sense and be more useful in general.
 */
require 'vendor/autoload.php';
use Zend\EventManager\EventManager;
$events = new EventManager();
$events->attach('load', function ($e) {
    $event = $e->getName();
    $params = $e->getParams();
    echo "Just captured event {$event} with these parameters: " . json_encode($params) . "\n";
});
$params = array('city' => 'Austin', 'state' => 'Texas');
$events->trigger('load', null, $params);
$events->trigger('test', null, $params);
 /**
  * @param \Zend\EventManager\EventManager $eventManager
  */
 public function it_should_attach_an_eventlistener($eventManager)
 {
     $eventManager->attach('create', Argument::containing('create'), 1000)->shouldBeCalled();
     $this->attach($eventManager);
 }
Example #26
0
 /**
  * Attach to the listeners.
  *
  * @param \Zend\EventManager\EventManager $events
  * @return void
  */
 public function attachListeners(EventManager $events)
 {
     $events->attach(Event::EVENT_LOAD_PERMISSIONS, array($this, 'loadPermissions'));
 }
 /**
  * {@inheritDoc}
  */
 public function addListener($eventName, $listener, $priority = 0)
 {
     return $this->eventManager->attach($eventName, $listener, $priority);
 }
Example #28
0
 /**
  * Attach to the listeners.
  *
  * @param \Zend\EventManager\EventManager $events
  * @return void
  */
 public function attachListeners(EventManager $events)
 {
     $events->attach(Event::EVENT_LOAD_ROLES, array($this, 'loadRoles'));
 }
Example #29
0
 public function setEventManager(Detector $detector, $event = null, $callback = null)
 {
     $events = new EventManager();
     if (null !== $event && null !== $callback) {
         $events->attach($event, $callback);
     }
     $detector->setEventManager($events);
     return $detector;
 }
Example #30
0
 public function index09Action()
 {
     $eventManagerOne = new EventManager();
     //$eventManagerOne = new EventManager(array("emOne","emTwo"));
     $eventManagerOne->setIdentifiers(array("emOne", "emTwo"));
     $listener1 = $eventManagerOne->attach("eventOne", function ($e) {
         echo "<h3 style='color:red;font-weight:bold'>eventManagerOne - eventOne - Do 1</h3>";
     });
     $eventManagerOne->trigger("eventOne");
     $ids = $eventManagerOne->getIdentifiers();
     echo "<pre style='font-weight:bold'>";
     print_r($ids);
     echo "</pre>";
     return false;
 }