Set application instance
public setApplication ( Zend\Mvc\ApplicationInterface $application ) : |
||
$application | Zend\Mvc\ApplicationInterface | |
Результат |
public function bootstrap() { $event = new MvcEvent(); $event->setApplication($this); $event->setTarget($this); $this->getEventManager()->trigger(MvcEvent::EVENT_BOOTSTRAP, $event); }
public function testDoesNotLimitDispatchErrorEventToOnlyOneListener() { $eventManager = new EventManager(); $application = $this->prophesize(Application::class); $application->getEventManager()->willReturn($eventManager); $event = new MvcEvent(); $event->setApplication($application->reveal()); $guard = new DummyGuard(); $guard->attach($eventManager); $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function (MvcEvent $event) { $event->setParam('first-listener', true); }); $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function (MvcEvent $event) { $event->setParam('second-listener', true); }); // attach listener with lower priority than DummyGuard $eventManager->attach(MvcEvent::EVENT_ROUTE, function (MvcEvent $event) { $this->fail('should not be called, because guard should stop propagation'); }, DummyGuard::EVENT_PRIORITY - 1); $event->setName(MvcEvent::EVENT_ROUTE); $eventManager->triggerEvent($event); $this->assertTrue($event->getParam('first-listener')); $this->assertTrue($event->getParam('second-listener')); $this->assertTrue($event->propagationIsStopped()); }
public function setUp() { StaticEventManager::resetInstance(); $mockSharedEventManager = $this->getMock('Zend\EventManager\SharedEventManagerInterface'); $mockSharedEventManager->expects($this->any())->method('getListeners')->will($this->returnValue(array())); $mockEventManager = $this->getMock('Zend\EventManager\EventManagerInterface'); $mockEventManager->expects($this->any())->method('getSharedManager')->will($this->returnValue($mockSharedEventManager)); $mockApplication = $this->getMock('Zend\Mvc\ApplicationInterface'); $mockApplication->expects($this->any())->method('getEventManager')->will($this->returnValue($mockEventManager)); $event = new MvcEvent(); $event->setApplication($mockApplication); $event->setRequest(new Request()); $event->setResponse(new Response()); $routeMatch = new RouteMatch(array('action' => 'test')); $routeMatch->setMatchedRouteName('some-route'); $event->setRouteMatch($routeMatch); $locator = new Locator; $locator->add('forward', function () { return new ForwardController(); }); $this->controller = new SampleController(); $this->controller->setEvent($event); $this->controller->setServiceLocator($locator); $this->plugin = $this->controller->plugin('forward'); }
public function bootstrap() { $event = new MvcEvent(); $event->setApplication($this); $event->setTarget($this); $this->getEventManager()->trigger('bootstrap', $event); }
/** * @param EventManager $em * @return MvcEvent */ protected function getMvcEvent($em) { $event = new MvcEvent(); $serviceManager = new ServiceManager(); $serviceManager->setService('EventManager', $em)->setService('Request', new HttpRequest())->setService('Response', new HttpResponse()); $application = new Application(array(), $serviceManager); $event->setApplication($application); return $event; }
public function testCanStartSession() { $event = new MvcEvent(); $event->setApplication($this->getApplication()); $event->setRequest(new Request()); $sessionListener = new RouteListener(); $sessionListener->startSession($event); $this->assertArrayHasKey('__ZF', $_SESSION); }
public function setUpMvcEvent($app, $request, $response) { $event = new MvcEvent(); $event->setTarget($app); $event->setApplication($app)->setRequest($request)->setResponse($response); $r = new ReflectionProperty($app, 'event'); $r->setAccessible(true); $r->setValue($app, $event); return $app; }
public function testCurrentRouteNameViewModelVariableIsSetOnBootstrap() { $currentRouteName = self::class; $application = $this->setUpApplication($currentRouteName); $mvcEvent = new MvcEvent(); $mvcEvent->setApplication($application); $module = new Module(); $module->onBootstrap($mvcEvent); $viewModel = $mvcEvent->getViewModel(); $this->assertEquals($currentRouteName, $viewModel->getVariable('__currentRouteName')); }
public function testPluginManagers() { $sm = $this->getServiceManager(); $app = $sm->get('Application'); $event = new MvcEvent(); $event->setApplication($app); $module = new Module(); $module->onBootstrap($event); $connectionManager = $sm->get('HumusAmqpModule\\PluginManager\\Connection'); $this->assertInstanceOf('HumusAmqpModule\\PluginManager\\Connection', $connectionManager); }
public function testOnBootstrapListenersWithConsoleRequest() { $module = new Module(); $application = $this->createApplication(); $sm = $application->getServiceManager(); $sm->setAllowOverride(true); $sm->setService('Request', new ConsoleRequest()); $em = $application->getEventManager(); $event = new MvcEvent(); $event->setApplication($application); $module->onBootstrap($event); }
protected function setUp() { $serviceManager = Bootstrap::getServiceManager(); $this->controller = new IndexController(); $this->request = new Request(); $this->routeMatch = new RouteMatch(array('controller' => 'index')); $this->event = new MvcEvent(); $config = $serviceManager->get('Config'); $routerConfig = isset($config['router']) ? $config['router'] : array(); $router = HttpRouter::factory($routerConfig); $serviceManager->setAllowOverride(true); $serviceManager->setService('AuthService', new AuthenticationService(new Storage\NonPersistent(), new TestAdapter())); $albumTableMock = $this->getMockBuilder('Zend\\Mvc\\Controller\\ControllerManager')->disableOriginalConstructor()->getMock(); $albumTableMock->expects($this->any())->method('get')->will($this->returnValue($this->controller)); $serviceManager->setService('ControllerManager', $albumTableMock); $this->event->setApplication(new Application($config, $serviceManager)); $this->event->setRouter($router); $this->event->setRouteMatch($this->routeMatch); $this->controller->setEvent($this->event); $this->controller->setServiceLocator($serviceManager); }
public function setUp() { StaticEventManager::resetInstance(); $mockSharedEventManager = $this->getMock('Zend\\EventManager\\SharedEventManagerInterface'); $mockSharedEventManager->expects($this->any())->method('getListeners')->will($this->returnValue(array())); $mockEventManager = $this->getMock('Zend\\EventManager\\EventManagerInterface'); $mockEventManager->expects($this->any())->method('getSharedManager')->will($this->returnValue($mockSharedEventManager)); $mockApplication = $this->getMock('Zend\\Mvc\\ApplicationInterface'); $mockApplication->expects($this->any())->method('getEventManager')->will($this->returnValue($mockEventManager)); $event = new MvcEvent(); $event->setApplication($mockApplication); $event->setRequest(new Request()); $event->setResponse(new Response()); $routeMatch = new RouteMatch(array('action' => 'test')); $routeMatch->setMatchedRouteName('some-route'); $event->setRouteMatch($routeMatch); $services = new Locator(); $plugins = $this->plugins = new PluginManager(); $plugins->setServiceLocator($services); $controllers = $this->controllers = new ControllerManager(); $controllers->setFactory('forward', function () use($plugins) { $controller = new ForwardController(); $controller->setPluginManager($plugins); return $controller; }); $controllers->setInvokableClass('ZendTest\\Mvc\\Controller\\TestAsset\\ForwardFq', 'ZendTest\\Mvc\\Controller\\TestAsset\\ForwardFqController'); $controllers->setServiceLocator($services); $controllerLoader = function () use($controllers) { return $controllers; }; $services->add('ControllerLoader', $controllerLoader); $services->add('ControllerManager', $controllerLoader); $services->add('ControllerPluginManager', function () use($plugins) { return $plugins; }); $services->add('Zend\\ServiceManager\\ServiceLocatorInterface', function () use($services) { return $services; }); $services->add('EventManager', function () use($mockEventManager) { return $mockEventManager; }); $services->add('SharedEventManager', function () use($mockSharedEventManager) { return $mockSharedEventManager; }); $this->controller = new SampleController(); $this->controller->setEvent($event); $this->controller->setServiceLocator($services); $this->controller->setPluginManager($plugins); $this->plugin = $this->controller->plugin('forward'); }
public function testOnBootstrap() { $event = new MvcEvent(); $application = new Application([], Bootstrap::getServiceManager()); $em = new EventManager(); $application->setEventManager($em); $event->setApplication($application); $isConsole = Console::isConsole(); Console::overrideIsConsole(false); $this->module->onBootstrap($event); Console::overrideIsConsole($isConsole); $this->assertCount(1, $em->getListeners(MvcEvent::EVENT_DISPATCH)); $this->assertCount(1, $em->getListeners(MvcEvent::EVENT_RENDER)); }
public function __Construct() { $env = getenv("DB"); switch ($env) { case $env == "sqlite": $dbfilename = "schema.sqlite.sql"; $configFileName = "sqlite.config.php"; break; case $env == "mysql": $dbfilename = "schema.sql"; $configFileName = "mysql.config.php"; break; case $env == "pgsql": $dbfilename = "schema.pgsql.sql"; $configFileName = "pgsql.config.php"; break; } $configuration = (include __DIR__ . '/TestConfiguration.php'); if (isset($configuration['output_buffering']) && $configuration['output_buffering']) { ob_start(); // required to test sessions } $this->serviceManager = new ServiceManager(new ServiceManagerConfig(isset($configuration['service_manager']) ? $configuration['service_manager'] : array())); $this->serviceManager->setService('ApplicationConfig', $configuration); $this->serviceManager->setFactory('ServiceListener', 'Zend\\Mvc\\Service\\ServiceListenerFactory'); /** @var $moduleManager \Zend\ModuleManager\ModuleManager */ $moduleManager = $this->serviceManager->get('ModuleManager'); $moduleManager->loadModules(); $this->serviceManager->setAllowOverride(true); $application = $this->serviceManager->get('Application'); $event = new MvcEvent(); $event->setTarget($application); $event->setApplication($application)->setRequest($application->getRequest())->setResponse($application->getResponse())->setRouter($this->serviceManager->get('Router')); /// lets create user's table $em = $this->serviceManager->get("doctrine.entitymanager.orm_default"); $conn = $em->getConnection(); if (file_exists(__DIR__ . "/../vendor/zf-commons/zfc-user/data/{$dbfilename}")) { $sql = file_get_contents(__DIR__ . "/../vendor/zf-commons/zfc-user/data/{$dbfilename}"); } elseif (file_exists(__DIR__ . "/../../../../vendor/zf-commons/zfc-user/data/{$dbfilename}")) { $sql = file_get_contents(__DIR__ . "/../../../../vendor/zf-commons/zfc-user/data/{$dbfilename}"); } else { throw new \Exception("please check the zfc user sql file", 500); } $stmt = $conn->prepare($sql); try { $stmt->execute(); } catch (Exception $exc) { } }
public function testIgnoresNonConsoleModelNotContainingResultKeyWhenObtainingResult() { //Register console service $sm = new ServiceManager(); $sm->setService('console', new ConsoleAdapter()); $mockApplication = new MockApplication(); $mockApplication->setServiceManager($sm); $event = new MvcEvent(); $event->setApplication($mockApplication); $model = new Model\ViewModel(array('content' => 'Page not found')); $response = new Response(); $event->setResult($model); $event->setResponse($response); $this->strategy->render($event); $content = $response->getContent(); $this->assertNotContains('Page not found', $content); }
public function testCanAllowAccess() { $eventManager = $this->getMock('Zend\\EventManager\\EventManagerInterface'); $eventManager->expects($this->never())->method('trigger'); $application = $this->getMock('Zend\\Mvc\\Application', array(), array(), '', false); $application->expects($this->any())->method('getEventManager')->will($this->returnValue($eventManager)); $routeMatch = new RouteMatch(array()); $routeMatch->setMatchedRouteName('secure'); $event = new MvcEvent(); $event->setRouteMatch($routeMatch); $event->setApplication($application); $routeGuardMock = $this->getMockBuilder('UghAuthorization\\Guards\\Guard', array('isGranted'))->disableOriginalConstructor()->getMock(); $routeGuardMock->expects($this->any())->method('isGranted')->will($this->returnValue(true)); $routeGuardListener = new RouteGuardListener($routeGuardMock); $routeGuardListener->onGuard($event); $this->assertFalse($event->propagationIsStopped()); $this->assertEmpty($event->getError()); }
public function testUpdate() { $userArray = array('location' => 'there', 'groups' => array(array('name' => 'groupB')), 'profile' => array('firstname' => 'Toby')); $request = new Request(); $request->setMethod(Request::METHOD_PUT); $request->setQuery(new Parameters(array('id' => 'superdweebie'))); $request->setContent($userArray); $event = new MvcEvent(); $event->setRouteMatch(new RouteMatch(array())); $event->setApplication($this->serviceManager->get('application')); $response = null; $this->controller->setEvent($event); $consoleModel = $this->controller->dispatch($request, $response); $repository = $this->documentManager->getRepository('Sds\\DoctrineExtensionsModule\\Test\\TestAsset\\Document\\User'); $this->documentManager->clear(); $user = $repository->find($this->id); $this->assertEquals('superdweebie', $user->getId()); $this->assertEquals('there', $user->location()); $this->assertEquals('groupB', $user->getGroups()[0]); $this->assertEquals('Toby', $user->getProfile()->getFirstName()); }
public function expectedListeners() { $module = new Module(); $config = $module->getConfig(); $request = $this->prophesize(Request::class)->reveal(); $response = $this->prophesize(Response::class)->reveal(); $services = $this->createServiceManager($config); $services->setService('Request', $request); $services->setService('Response', $response); $services->setService('config', $config); $events = new EventManager(); $application = $this->createApplication($services, $events); $mvcEvent = new MvcEvent(MvcEvent::EVENT_BOOTSTRAP); $mvcEvent->setApplication($application); $mvcEvent->setRequest($request); $mvcEvent->setResponse($response); $module->onBootstrap($mvcEvent); // @codingStandardsIgnoreStart return ['mvc-route-authentication' => [[$module->getMvcRouteListener(), 'authentication'], -50, MvcEvent::EVENT_ROUTE, $events], 'mvc-route-authentication-post' => [[$module->getMvcRouteListener(), 'authenticationPost'], -51, MvcEvent::EVENT_ROUTE, $events], 'mvc-route-authorization' => [[$module->getMvcRouteListener(), 'authorization'], -600, MvcEvent::EVENT_ROUTE, $events], 'mvc-route-authorization-post' => [[$module->getMvcRouteListener(), 'authorizationPost'], -601, MvcEvent::EVENT_ROUTE, $events], 'authentication' => [$services->get(DefaultAuthenticationListener::class), 1, MvcAuthEvent::EVENT_AUTHENTICATION, $events], 'authentication-post' => [$services->get(DefaultAuthenticationPostListener::class), 1, MvcAuthEvent::EVENT_AUTHENTICATION_POST, $events], 'resource-resoolver-authorization' => [$services->get(DefaultResourceResolverListener::class), 1000, MvcAuthEvent::EVENT_AUTHORIZATION, $events], 'authorization' => [$services->get(DefaultAuthorizationListener::class), 1, MvcAuthEvent::EVENT_AUTHORIZATION, $events], 'authorization-post' => [$services->get(DefaultAuthorizationPostListener::class), 1, MvcAuthEvent::EVENT_AUTHORIZATION_POST, $events], 'module-authentication-post' => [[$module, 'onAuthenticationPost'], -1, MvcAuthEvent::EVENT_AUTHENTICATION_POST, $events]]; // @codingStandardsIgnoreEnd }
public function testCanCollect() { $dataToCollect = ['module_options' => ['guest_role' => 'guest', 'protection_policy' => GuardInterface::POLICY_ALLOW, 'guards' => ['ZfcRbac\\Guard\\RouteGuard' => ['admin*' => ['*']], 'ZfcRbac\\Guard\\ControllerGuard' => [['controller' => 'Foo', 'roles' => ['*']]]]], 'role_config' => ['member' => ['children' => ['guest'], 'permissions' => ['write', 'delete']], 'guest' => ['permissions' => ['read']]], 'identity_role' => 'member']; $serviceManager = $this->getMock('Zend\\ServiceManager\\ServiceLocatorInterface'); $application = $this->getMock('Zend\\Mvc\\Application', [], [], '', false); $application->expects($this->once())->method('getServiceManager')->will($this->returnValue($serviceManager)); $mvcEvent = new MvcEvent(); $mvcEvent->setApplication($application); $identity = $this->getMock('ZfcRbac\\Identity\\IdentityInterface'); $identity->expects($this->once())->method('getRoles')->will($this->returnValue($dataToCollect['identity_role'])); $identityProvider = $this->getMock('ZfcRbac\\Identity\\IdentityProviderInterface'); $identityProvider->expects($this->once())->method('getIdentity')->will($this->returnValue($identity)); $roleService = new RoleService($identityProvider, new InMemoryRoleProvider($dataToCollect['role_config']), new RecursiveRoleIteratorStrategy()); $serviceManager->expects($this->at(0))->method('get')->with('ZfcRbac\\Service\\RoleService')->will($this->returnValue($roleService)); $serviceManager->expects($this->at(1))->method('get')->with('ZfcRbac\\Options\\ModuleOptions')->will($this->returnValue(new ModuleOptions($dataToCollect['module_options']))); $collector = new RbacCollector(); $collector->collect($mvcEvent); $collector->unserialize($collector->serialize()); $collection = $collector->getCollection(); $expectedCollection = ['options' => ['guest_role' => 'guest', 'protection_policy' => 'allow'], 'guards' => ['ZfcRbac\\Guard\\RouteGuard' => ['admin*' => ['*']], 'ZfcRbac\\Guard\\ControllerGuard' => [['controller' => 'Foo', 'roles' => ['*']]]], 'roles' => ['member' => ['guest']], 'permissions' => ['member' => ['write', 'delete'], 'guest' => ['read']]]; $this->assertEquals($expectedCollection, $collection); }
public function testOnDispatchStatus200() { $resolver = $this->getMock(ResolverInterface::class); $assetManager = $this->getMock(AssetManager::class, array('resolvesToAsset', 'setAssetOnResponse'), array($resolver)); $assetManager->expects($this->once())->method('resolvesToAsset')->will($this->returnValue(true)); $amResponse = new Response(); $amResponse->setContent('bacon'); $assetManager->expects($this->once())->method('setAssetOnResponse')->will($this->returnValue($amResponse)); $serviceManager = $this->getMock(ServiceLocatorInterface::class); $serviceManager->expects($this->any())->method('get')->will($this->returnValue($assetManager)); $application = $this->getMock(ApplicationInterface::class); $application->expects($this->once())->method('getServiceManager')->will($this->returnValue($serviceManager)); $event = new MvcEvent(); $response = new Response(); $request = new Request(); $module = new Module(); $event->setApplication($application); $response->setStatusCode(404); $event->setResponse($response); $event->setRequest($request); $return = $module->onDispatch($event); $this->assertEquals(200, $return->getStatusCode()); }
public function testProperlySetUnauthorizedAndTriggerEventOnUnauthorization() { $event = new MvcEvent(); $routeMatch = new RouteMatch([]); $application = $this->getMock('Zend\\Mvc\\Application', [], [], '', false); $eventManager = $this->getMock('Zend\\EventManager\\EventManagerInterface'); $application->expects($this->once())->method('getEventManager')->will($this->returnValue($eventManager)); $eventManager->expects($this->once())->method('trigger')->with(MvcEvent::EVENT_DISPATCH_ERROR); $routeMatch->setParam('controller', 'MyController'); $routeMatch->setParam('action', 'delete'); $event->setRouteMatch($routeMatch); $event->setApplication($application); $identityProvider = $this->getMock('ZfjRbac\\Identity\\IdentityProviderInterface'); $identityProvider->expects($this->any())->method('getIdentityRoles')->will($this->returnValue('member')); $roleProvider = new InMemoryRoleProvider(['member']); $roleService = new RoleService($identityProvider, $roleProvider, new RecursiveRoleIteratorStrategy()); $routeGuard = new ControllerGuard($roleService, [['controller' => 'MyController', 'actions' => 'edit', 'roles' => 'member']]); $routeGuard->onResult($event); $this->assertTrue($event->propagationIsStopped()); $this->assertEquals(ControllerGuard::GUARD_UNAUTHORIZED, $event->getError()); $this->assertInstanceOf('ZfjRbac\\Exception\\UnauthorizedException', $event->getParam('exception')); }
public function testProperlyFillEventOnAuthorization() { $event = new MvcEvent(); $routeMatch = $this->createRouteMatch(); $application = $this->getMock('Zend\\Mvc\\Application', [], [], '', false); $eventManager = $this->getMock('Zend\\EventManager\\EventManagerInterface'); $application->expects($this->never())->method('getEventManager')->will($this->returnValue($eventManager)); $routeMatch->setMatchedRouteName('adminRoute'); $event->setRouteMatch($routeMatch); $event->setApplication($application); $identity = $this->getMock('ZfcRbac\\Identity\\IdentityInterface'); $identity->expects($this->any())->method('getRoles')->will($this->returnValue(['member'])); $identityProvider = $this->getMock('ZfcRbac\\Identity\\IdentityProviderInterface'); $identityProvider->expects($this->any())->method('getIdentity')->will($this->returnValue($identity)); $roleProvider = new InMemoryRoleProvider(['member']); $roleService = new RoleService($identityProvider, $roleProvider, new RecursiveRoleIteratorStrategy()); $routeGuard = new RouteGuard($roleService, ['adminRoute' => 'member']); $routeGuard->onResult($event); $this->assertEmpty($event->getError()); $this->assertNull($event->getParam('exception')); }
public function testInjectLayoutNegative() { $listener = new AccessListener(); $viewModel = new ViewModel(); $viewModel->setTemplate('layout/layout'); $access = new DenyAccess(); $event = new MvcEvent(); $event->setApplication($this->getMockApplication(true, $access)); $event->setViewModel($viewModel); $listener->injectLayoutMenu($event); $this->assertCount(0, $viewModel->getChildrenByCaptureTo('sporkToolsMenu')); }
/** * @author Fabian Köstring */ public function testOnDispatch() { $eventManager = new Common\EventManager(); $entityManager = $this->getMock('\\Doctrine\\ORM\\EntityManager', array('getEventManager'), array(), '', false); $entityManager->expects($this->any())->method('getEventManager')->will($this->returnValue($eventManager)); $serviceManager = $this->getMock('Zend\\ServiceManager\\ServiceLocatorInterface'); $serviceManager->expects($this->at(0))->method('get')->with(ORM\EntityManager::class)->will($this->returnValue($entityManager)); $serviceManager->expects($this->at(1))->method('get')->with('Config')->will($this->returnValue(['zf2-doctrine-elasticsearch-sync' => ['ASD']])); $application = $this->getMock('Zend\\Mvc\\ApplicationInterface'); $application->expects($this->once())->method('getServiceManager')->will($this->returnValue($serviceManager)); $event = new MvcEvent(); $event->setApplication($application); $this->assertEmpty($eventManager->getListeners()); $module = new Module(); $module->onDispatch($event); $this->assertArrayHasKey('onFlush', $eventManager->getListeners()); $this->assertArrayHasKey('postFlush', $eventManager->getListeners()); }
/** * Bootstrap the application * * Defines and binds the MvcEvent, and passes it the request, response, and * router. Attaches the ViewManager as a listener. Triggers the bootstrap * event. * * @param array $listeners List of listeners to attach. * @return Application */ public function bootstrap(array $listeners = array()) { $serviceManager = $this->serviceManager; $events = $this->events; $listeners = array_unique(array_merge($this->defaultListeners, $listeners)); foreach ($listeners as $listener) { $events->attach($serviceManager->get($listener)); } // Setup MVC Event $this->event = $event = new MvcEvent(); $event->setTarget($this); $event->setApplication($this)->setRequest($this->getRequest())->setResponse($this->getResponse())->setRouter($serviceManager->get('Router')); // Trigger bootstrap events $events->trigger(MvcEvent::EVENT_BOOTSTRAP, $event); return $this; }
protected function getEvent() { $event = new MvcEvent(); $event->setApplication(Application::init(array('modules' => array(), 'module_listener_options' => array()))); return $event; }
/** * Creates an MvcEvent object. * * @param null $lang * * @return MvcEvent */ protected function createMvcEvent($lang = null) { $e = new MvcEvent(); $e->setApplication($this->app); $e->setViewModel(new ViewModel()); $request = new Http\Request(); if (isset($lang)) { $request->setQuery(new Parameters(['lang' => $lang])); } $e->setRequest($request); return $e; }
public function testProperlySetUnauthorizedAndTriggerEventOnUnauthorization() { $eventManager = $this->getMock('Zend\\EventManager\\EventManagerInterface'); $eventManager->expects($this->once())->method('trigger')->with(MvcEvent::EVENT_DISPATCH_ERROR); $application = $this->getMock('Zend\\Mvc\\Application', [], [], '', false); $application->expects($this->once())->method('getEventManager')->will($this->returnValue($eventManager)); $routeMatch = new RouteMatch([]); $routeMatch->setMatchedRouteName('adminRoute'); $event = new MvcEvent(); $event->setRouteMatch($routeMatch); $event->setApplication($application); $authorizationService = $this->getMock('ZfcRbac\\Service\\AuthorizationServiceInterface', [], [], '', false); $authorizationService->expects($this->once())->method('isGranted')->with('post.edit')->will($this->returnValue(false)); $routeGuard = new RoutePermissionsGuard($authorizationService, ['adminRoute' => 'post.edit']); $routeGuard->onResult($event); $this->assertTrue($event->propagationIsStopped()); $this->assertEquals(RouteGuard::GUARD_UNAUTHORIZED, $event->getError()); $this->assertInstanceOf('ZfcRbac\\Exception\\UnauthorizedException', $event->getParam('exception')); }
/** * Bootstrap the application * * Defines and binds the MvcEvent, and passes it the request, response, and * router. Attaches the ViewManager as a listener. Triggers the bootstrap * event. * * @return Application */ public function bootstrap() { $serviceManager = $this->serviceManager; $events = $this->getEventManager(); $events->attach($serviceManager->get('RouteListener')); $events->attach($serviceManager->get('DispatchListener')); $events->attach($serviceManager->get('ViewManager')); $events->attach($serviceManager->get('SendResponseListener')); // Setup MVC Event $this->event = $event = new MvcEvent(); $event->setTarget($this); $event->setApplication($this)->setRequest($this->getRequest())->setResponse($this->getResponse())->setRouter($serviceManager->get('Router')); // Trigger bootstrap events $events->trigger(MvcEvent::EVENT_BOOTSTRAP, $event); return $this; }
public function test() { /* $viewConfigExample = [ 'some-view' => [ // view name 'template' => 'some-template', // html template //--- not required options 'viewModel' => 'some-view-model|\Some\ViewModel::class', // Instance of ViewModel 'extend' => 'parent-view', // extended view 'capture' => 'some-capture', // for grouping views 'children' => [ 'child-view'// array of views ], 'childrenDynamicLists' => [ // will be generated by list from one of child 'child-view' => 'listVar' // every entry in listVar will be setted to genereted child ], 'data' => [ // required data 'fromGlobal' => 'varName', // // will be set as variables from global data 'fromParent' => 'varName', // will be set as variables by calling getVariable('varName') from parent 'static' => [ // will be set as variables 'key' => 'value' ], ], ], ]; */ $renderer = new PhpRenderer(); $resolver = new Resolver\AggregateResolver(); $map = new Resolver\TemplateMapResolver(array('page' => __DIR__ . '/view/page.phtml', 'comments-list' => __DIR__ . '/view/comments-list.phtml', 'comment' => __DIR__ . '/view/comment.phtml', 'user' => __DIR__ . '/view/user.phtml')); $stack = new Resolver\TemplatePathStack(array('script_paths' => array(__DIR__ . '/view'))); $resolver->attach($map)->attach($stack)->attach(new Resolver\RelativeFallbackResolver($map))->attach(new Resolver\RelativeFallbackResolver($stack)); $renderer->setResolver($resolver); $view = new View(); $response = new Response(); $view->setResponse($response); $strategy = new PhpRendererStrategy($renderer); $strategy->attach($view->getEventManager()); $viewConfig = ['layouts' => ['layout' => ['template' => 'layout']], 'contents' => ['page' => ['layout' => 'layout', 'template' => 'page', 'children' => ['comments-list' => ['extend' => 'comments-list', 'template' => 'comments-list'], 'comment-create' => ['template' => 'comment-create', 'children' => ['myself-info' => ['viewModel' => \Sebaks\ViewTest\MyselfViewModel::class, 'template' => 'user'], 'comment-create-form' => ['template' => 'form', 'children' => ['form-element-textarea' => ['capture' => 'form-element', 'template' => 'form-element-textarea'], 'form-element-button' => ['capture' => 'form-element', 'template' => 'form-element-button']]]]], 'users-table' => ['template' => 'table', 'children' => ['table-head-rows' => ['template' => 'table-tr', 'data' => ['fromParent' => 'rows'], 'children' => ['table-th' => ['template' => 'table-th', 'capture' => 'table-td', 'data' => ['fromParent' => 'value']]], 'childrenDynamicLists' => ['table-th' => 'rows']], 'table-body-rows' => ['template' => 'table-tr', 'data' => ['fromParent' => 'rows'], 'children' => ['table-td' => ['template' => 'table-td', 'data' => ['fromParent' => 'value']]], 'childrenDynamicLists' => ['table-td' => 'rows']]], 'childrenDynamicLists' => ['table-body-rows' => 'bodyRows', 'table-head-rows' => 'headRows'], 'data' => ['static' => ['headRows' => [['Id', 'Name']], 'bodyRows' => [['1', 'John'], ['2', 'Helen']]]]]]]], 'blocks' => ['comments-list' => ['children' => ['comment' => ['viewModel' => \Sebaks\ViewTest\CommentViewModel::class, 'template' => 'comment', 'children' => ['user' => ['viewModel' => \Sebaks\ViewTest\UserViewModel::class, 'template' => 'user', 'data' => ['fromParent' => 'userId', 'static' => ['class' => 'user']], 'children' => ['location' => ['viewModel' => \Sebaks\ViewTest\LocationViewModel::class, 'template' => 'location', 'data' => ['fromParent' => 'countryId']]]]], 'data' => ['fromParent' => ['foo' => 'bar', 'comment' => 'comment']]]], 'childrenDynamicLists' => ['comment' => 'comments'], 'data' => ['fromGlobal' => ['foo' => 'bar', 'result' => 'comments']]]]]; $data = ['result' => [['id' => 'c1', 'userId' => 'u1', 'text' => 'text of c1'], ['id' => 'c2', 'userId' => 'u2', 'text' => 'text of c2']]]; $serviceLocator = new \Zend\ServiceManager\ServiceManager(); $serviceLocator->setInvokableClass(\Sebaks\ViewTest\CommentViewModel::class, \Sebaks\ViewTest\CommentViewModel::class, false); $serviceLocator->setInvokableClass(\Sebaks\ViewTest\UserViewModel::class, \Sebaks\ViewTest\UserViewModel::class, false); $serviceLocator->setInvokableClass(\Sebaks\ViewTest\LocationViewModel::class, \Sebaks\ViewTest\LocationViewModel::class, false); $serviceLocator->setInvokableClass(\Sebaks\ViewTest\MyselfViewModel::class, \Sebaks\ViewTest\MyselfViewModel::class, false); ///////////////////// $config = ['sebaks-view' => $viewConfig]; $serviceLocator->setService('config', $config); $serviceLocator->setService('EventManager', new EventManager()); $request = new Request(); $serviceLocator->setService('Request', $request); //$response = new Response(); $serviceLocator->setService('Response', $response); $e = new MvcEvent(); $e->setRequest($request); $e->setResponse($response); $dispatchResult = new ViewModel(); $dispatchResult->setVariables($data); $e->setResult($dispatchResult); $routeMatch = new RouteMatch([]); $routeMatch->setMatchedRouteName('page'); $e->setRouteMatch($routeMatch); $application = new Application([], $serviceLocator); $e->setApplication($application); ///////////////////// $viewBuilder = new BuildViewListener(); $viewBuilder->injectLayout($e); $pageViewModel = $e->getViewModel(); $view->render($pageViewModel); $result = $response->getBody(); $expected = '<body><ul><li>text of c1 <div class="user">John<span class="location">Ukraine</span></div></li><li>text of c2 <div class="user">Helen<span class="location">United States</span></div></li></ul> <div class="">Me</div><form><textarea></textarea><button type="submit">Submit</button></form><table> <thead> <tr><th>Id</th><th>Name</th></tr> </thead> <tbody> <tr><td>1</td><td>John</td></tr><tr><td>2</td><td>Helen</td></tr> </tbody> </table></body>'; $this->assertEquals($expected, $result); }