public function onDispatch(Event $event)
 {
     $controller = $event->getTarget();
     if (!$controller instanceof AbstractController) {
         return;
     }
     $entity = $controller->getEntity();
     if (!$entity) {
         return;
     }
     $terms = $entity->getTaxonomyTerms();
     if ($terms->isEmpty()) {
         foreach ($entity->getParents('link') as $parent) {
             $terms = $parent->getTaxonomyTerms();
             if (!$terms->isEmpty()) {
                 break;
             }
         }
     }
     $term = $this->strategy->findBranch($terms);
     if ($term) {
         /* @var $navigationFactory DefaultNavigationFactory */
         $navigationFactory = $controller->getServiceLocator()->get('Navigation\\Factory\\DefaultNavigationFactory');
         $params = ['term' => $term->getId(), 'controller' => 'Taxonomy\\Controller\\GetController', 'action' => 'index'];
         $routeMatch = new RouteMatch($params);
         $routeMatch->setMatchedRouteName('taxonomy/term/get');
         $navigationFactory->setRouteMatch($routeMatch);
     }
 }
Ejemplo n.º 2
0
    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');
    }
Ejemplo n.º 3
0
 public function testIsActiveReturnsFalseWhenMatchingRouteButNonMatchingParams()
 {
     $page = new Page\Mvc(array('label' => 'foo', 'route' => 'bar', 'action' => 'baz'));
     $routeMatch = new RouteMatch(array());
     $routeMatch->setMatchedRouteName('bar');
     $routeMatch->setParam('action', 'qux');
     $page->setRouteMatch($routeMatch);
     $this->assertFalse($page->isActive());
 }
Ejemplo n.º 4
0
 public function testIsActiveReturnsTrueWhenMatchingRoute()
 {
     $page = new Page\Mvc(array('label' => 'spiffyjrwashere', 'route' => 'lolfish'));
     $route = new LiteralRoute('/lolfish');
     $router = new TreeRouteStack();
     $router->addRoute('lolfish', $route);
     $routeMatch = new RouteMatch(array());
     $routeMatch->setMatchedRouteName('lolfish');
     $page->setRouter($router);
     $page->setRouteMatch($routeMatch);
     $this->assertEquals(true, $page->isActive());
 }
 public function testSetsActiveFlagOnPagesProvidingTheActiveOnOption()
 {
     $pages = ['page1' => ['active_on' => 'matchedRouteName'], 'page2' => ['active_on' => 'notMatchedRoute'], 'page3' => ['active_on' => ['matchedRouteName', 'anotherRoute']], 'page4' => []];
     $routeMatch = new RouteMatch([]);
     $routeMatch->setMatchedRouteName('matchedRouteName');
     $expect = $pages;
     $expect['page1']['active'] = true;
     $expect['page3']['active'] = true;
     $m = new \ReflectionMethod($this->target, 'injectComponents');
     $m->setAccessible(true);
     $actual = $m->invoke($this->target, $pages, $routeMatch);
     $this->assertEquals($expect, $actual);
 }
Ejemplo n.º 6
0
 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');
 }
Ejemplo n.º 7
0
 /**
  * @param array   $routes
  * @param string  $route
  * @param boolean $expectedResult
  * @param array   $params
  * @param string  $httpMethod
  * @dataProvider shouldCacheProvider
  */
 public function testShouldCache($routes, $route, $expectedResult, $params = array(), $httpMethod = null)
 {
     $this->strategy->setRoutes($routes);
     $routeMatch = new RouteMatch($params);
     $routeMatch->setMatchedRouteName($route);
     $request = new Request();
     if ($httpMethod !== null) {
         $request->setMethod($httpMethod);
     }
     $mvcEvent = new MvcEvent();
     $mvcEvent->setRouteMatch($routeMatch);
     $mvcEvent->setRequest($request);
     $this->assertEquals($expectedResult, $this->strategy->shouldCache($mvcEvent));
 }
 /**
  * @dataProvider dataForheckDeactivatedUser
  */
 public function testCheckDeactivatedUser($routeName, $hasIdentity, $isActive, $expectedTriggerCalled)
 {
     $this->routeMatch->setMatchedRouteName($routeName);
     $this->auth->expects($this->any())->method('hasIdentity')->willReturn($hasIdentity);
     $this->user->expects($this->any())->method('isActive')->willReturn($isActive);
     $this->event->expects($expectedTriggerCalled ? $this->once() : $this->never())->method('setError');
     if ($expectedTriggerCalled) {
         $eventManager = $this->getMockBuilder(EventManager::class)->getMock();
         $eventManager->expects($this->once())->method('trigger')->willReturn(new \Zend\EventManager\ResponseCollection())->with($this->equalTo(MvcEvent::EVENT_DISPATCH_ERROR));
         $target = $this->getMockBuilder(\stdClass::class)->setMethods(['getEventManager'])->getMock();
         $target->expects($this->any())->method('getEventManager')->willReturn($eventManager);
         $this->event->expects($this->once())->method('getTarget')->willReturn($target);
     }
     $this->listener->checkDeactivatedUser($this->event);
 }
 /**
  * {@inheritDoc}
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     /* @var $serviceLocator AbstractPluginManager */
     $serviceManager = $serviceLocator->getServiceLocator();
     $response = $serviceManager->get('Response');
     $request = $serviceManager->get('Request');
     $router = $serviceManager->get('Router');
     $routeMatch = $router->match($request);
     $class = $this->getClass();
     if (null === $routeMatch) {
         $routeMatch = new RouteMatch([]);
         $routeMatch->setMatchedRouteName('home');
     }
     return new $class($response, $router, $routeMatch);
 }
 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 configureControllerForAGivenRoute($controller, $routeName)
 {
     //CONFIGURE ROUTING
     $event = new MvcEvent();
     //build the router and set it as event's router.
     $routeStack = new SimpleRouteStack();
     $route = new Literal('/' . $routeName);
     $routeStack->addRoute($routeName, $route);
     //so that "route >home< not found" error did not show up - add home route.
     $routeHome = new Literal('/');
     $routeStack->addRoute('home', $routeHome);
     $event->setRouter($routeStack);
     //set route match for the event
     $routeMatch = new RouteMatch(['controller' => 'Index', 'action' => $routeName]);
     $routeMatch->setMatchedRouteName($routeName);
     $event->setRouteMatch($routeMatch);
     //finish configuring controller
     $controller->setEvent($event);
     return $controller;
 }
Ejemplo n.º 12
0
 public function testProperlySetUnauthorizedAndTriggerEventOnUnauthorization()
 {
     $whip = $this->createMock(Whip::class);
     $whip->expects($this->once())->method('getValidIpAddress')->will($this->returnValue(false));
     $event = new MvcEvent();
     $request = new HttpRequest();
     $response = new HttpResponse();
     $routeMatch = new RouteMatch([]);
     $application = $this->getMockBuilder(Application::class)->disableOriginalConstructor()->getMock();
     $eventManager = $this->createMock(EventManagerInterface::class);
     $application->expects($this->any())->method('getEventManager')->will($this->returnValue($eventManager));
     $routeMatch->setMatchedRouteName(Module::RECURLY_NOTIFICATION_ROUTE);
     $event->setRequest($request)->setResponse($response)->setRouteMatch($routeMatch)->setApplication($application);
     $listener = new IpListener($whip);
     $logger = $this->createMock(LoggerInterface::class);
     $logger->expects($this->once())->method('info');
     $listener->setLogger($logger);
     $listener->onResult($event);
     $this->assertNotEmpty($event->getError());
     $this->assertNotNull($event->getParam('exception'));
     $this->assertEquals(HttpResponse::STATUS_CODE_403, $response->getStatusCode());
 }
Ejemplo n.º 13
0
 /**
  * Dispatch another controller
  *
  * @param  string $name Controller name; either a class name or an alias used in the DI container or service locator
  * @param  null|array $params Parameters with which to seed a custom RouteMatch object for the new controller
  * @return mixed
  * @throws Exception\DomainException if composed controller does not define InjectApplicationEventInterface
  *         or Locator aware; or if the discovered controller is not dispatchable
  */
 public function dispatch($name, array $params = null)
 {
     $event = clone $this->getEvent();
     $locator = $this->getLocator();
     $scoped = false;
     // Use the controller loader when possible
     if ($locator->has('ControllerLoader')) {
         $locator = $locator->get('ControllerLoader');
         $scoped = true;
     }
     $controller = $locator->get($name);
     if (!$controller instanceof Dispatchable) {
         throw new Exception\DomainException('Can only forward to DispatchableInterface classes; class of type ' . get_class($controller) . ' received');
     }
     if ($controller instanceof InjectApplicationEventInterface) {
         $controller->setEvent($event);
     }
     if (!$scoped) {
         if ($controller instanceof ServiceLocatorAwareInterface) {
             $controller->setServiceLocator($locator);
         }
     }
     // Allow passing parameters to seed the RouteMatch with & copy matched route name
     if ($params !== null) {
         $routeMatch = new RouteMatch($params);
         $routeMatch->setMatchedRouteName($event->getRouteMatch()->getMatchedRouteName());
         $event->setRouteMatch($routeMatch);
     }
     if ($this->numNestedForwards > $this->maxNestedForwards) {
         throw new Exception\DomainException("Circular forwarding detected: greater than {$this->maxNestedForwards} nested forwards");
     }
     $this->numNestedForwards++;
     // Detach listeners that may cause problems during dispatch:
     $sharedEvents = $event->getApplication()->getEventManager()->getSharedManager();
     $listeners = $this->detachProblemListeners($sharedEvents);
     $return = $controller->dispatch($event->getRequest(), $event->getResponse());
     // If we detached any listeners, reattach them now:
     $this->reattachProblemListeners($sharedEvents, $listeners);
     $this->numNestedForwards--;
     return $return;
 }
Ejemplo n.º 14
0
 /**
  * Dispatch another controller
  *
  * @param  string $name Controller name; either a class name or an alias used in the controller manager
  * @param  null|array $params Parameters with which to seed a custom RouteMatch object for the new controller
  * @return mixed
  * @throws Exception\DomainException if composed controller does not define InjectApplicationEventInterface
  *         or Locator aware; or if the discovered controller is not dispatchable
  */
 public function dispatch($name, array $params = null)
 {
     $event = clone $this->getEvent();
     $controller = $this->controllers->get($name);
     if ($controller instanceof InjectApplicationEventInterface) {
         $controller->setEvent($event);
     }
     // Allow passing parameters to seed the RouteMatch with & copy matched route name
     if ($params !== null) {
         $routeMatch = new RouteMatch($params);
         $routeMatch->setMatchedRouteName($event->getRouteMatch()->getMatchedRouteName());
         $event->setRouteMatch($routeMatch);
     }
     if ($this->numNestedForwards > $this->maxNestedForwards) {
         throw new Exception\DomainException("Circular forwarding detected: greater than {$this->maxNestedForwards} nested forwards");
     }
     $this->numNestedForwards++;
     // Detach listeners that may cause problems during dispatch:
     $sharedEvents = $event->getApplication()->getEventManager()->getSharedManager();
     $listeners = $this->detachProblemListeners($sharedEvents);
     $return = $controller->dispatch($event->getRequest(), $event->getResponse());
     // If we detached any listeners, reattach them now:
     $this->reattachProblemListeners($sharedEvents, $listeners);
     $this->numNestedForwards--;
     return $return;
 }
 public function testRemoveInputFilter()
 {
     $request = new Request();
     $request->setMethod('delete');
     $request->getHeaders()->addHeaderLine('Accept', 'application/json');
     $request->getHeaders()->addHeaderLine('Content-Type', 'application/json');
     $module = 'InputFilter';
     $controller = 'InputFilter\\V1\\Rest\\Foo\\Controller';
     $validator = 'InputFilter\\V1\\Rest\\Foo\\Validator';
     $params = ['name' => $module, 'controller_service_name' => $controller, 'input_filter_name' => $validator];
     $routeMatch = new RouteMatch($params);
     $routeMatch->setMatchedRouteName('zf-apigility-admin/api/module/rest-service/rest_input_filter');
     $event = new MvcEvent();
     $event->setRouteMatch($routeMatch);
     $this->controller->setRequest($request);
     $this->controller->setEvent($event);
     $result = $this->controller->indexAction();
     $this->assertInstanceOf('Zend\\Http\\Response', $result);
     $this->assertEquals(204, $result->getStatusCode());
 }
Ejemplo n.º 16
0
 /**
  * Dispatch another controller
  *
  * @param  string $name Controller name; either a class name or an alias used in the controller manager
  * @param  null|array $params Parameters with which to seed a custom RouteMatch object for the new controller
  * @return mixed
  * @throws Exception\DomainException if composed controller does not define InjectApplicationEventInterface
  *         or Locator aware; or if the discovered controller is not dispatchable
  */
 public function dispatch($name, array $params = null)
 {
     $event = clone $this->getEvent();
     if (is_array($params) && isset($params[ModuleRouteListener::MODULE_NAMESPACE])) {
         $module = $params[ModuleRouteListener::MODULE_NAMESPACE];
         if (strpos($name, $module) !== 0) {
             if (!isset($params[ModuleRouteListener::ORIGINAL_CONTROLLER])) {
                 $params[ModuleRouteListener::ORIGINAL_CONTROLLER] = $name;
             }
             $name = $module . '\\' . str_replace(' ', '', ucwords(str_replace('-', ' ', $name)));
         }
     }
     $controller = $this->controllers->get($name);
     if ($controller instanceof InjectApplicationEventInterface) {
         $controller->setEvent($event);
     }
     // Allow passing parameters to seed the RouteMatch with & copy matched route name
     if ($params !== null) {
         $routeMatch = new RouteMatch($params);
         $routeMatch->setMatchedRouteName($event->getRouteMatch()->getMatchedRouteName());
         $event->setRouteMatch($routeMatch);
     }
     if ($this->numNestedForwards > $this->maxNestedForwards) {
         throw new Exception\DomainException("Circular forwarding detected: greater than {$this->maxNestedForwards} nested forwards");
     }
     $this->numNestedForwards++;
     // Detach listeners that may cause problems during dispatch:
     $sharedEvents = $event->getApplication()->getEventManager()->getSharedManager();
     $listeners = $this->detachProblemListeners($sharedEvents);
     $return = $controller->dispatch($event->getRequest(), $event->getResponse());
     // If we detached any listeners, reattach them now:
     $this->reattachProblemListeners($sharedEvents, $listeners);
     $this->numNestedForwards--;
     return $return;
 }
    /**
     * @dataProvider getOldAuthConfig
     */
    public function testGetAuthenticationWithOldConfiguration($global, $local, $expected)
    {
        file_put_contents($this->globalFile, '<' . '?php return '. var_export($global, true) . ';');
        file_put_contents($this->localFile, '<' . '?php return '. var_export($local, true) . ';');

        $controller = $this->getController($this->localFile, $this->globalFile);

        $request = new Request();
        $request->setMethod('get');
        $request->getHeaders()->addHeaderLine('Accept', 'application/vnd.apigility.v2+json');
        $controller->setRequest($request);

        $routeMatch = new RouteMatch(array());
        $routeMatch->setMatchedRouteName('zf-apigility/api/authentication-type');
        $event = new MvcEvent();
        $event->setRouteMatch($routeMatch);
        $controller->setEvent($event);

        $result = $controller->authTypeAction();

        $this->assertInstanceOf('ZF\ContentNegotiation\ViewModel', $result);

        $types = $result->getVariable('auth-types');
        $this->assertEquals($expected, $types);
    }
Ejemplo n.º 18
0
 /**
  * Test
  *
  * @return void
  */
 public function testOnDispatchWithIdentityAndAdminRole()
 {
     $userModel = UserModel::fromArray(array('lastname' => 'Test', 'firstname' => 'Test', 'email' => '*****@*****.**', 'login' => 'login-test', 'user_acl_role_id' => 1));
     $userModel->setPassword('password-test');
     $userModel->save();
     $userModel->authenticate('login-test', 'password-test');
     $routeMatch = new RouteMatch(array());
     $routeMatch->setMatchedRouteName('cms');
     $this->object->getEvent()->setRouteMatch($routeMatch);
     $this->assertInstanceOf('Zend\\View\\Model\\ViewModel', $this->object->dispatch(Registry::get('Application')->getRequest(), null));
     $userModel->delete();
 }
Ejemplo n.º 19
0
 public function testCanCreateViewProjectLink()
 {
     $routeMatch = new RouteMatch(['docRef' => 'testproject']);
     $routeMatch->setMatchedRouteName('route-project_entity_project');
     $this->projectLink->setRouteMatch($routeMatch);
     $link = $this->projectLink->__invoke($this->projectService, 'view');
     $this->assertContains('<a href', $link);
 }
Ejemplo n.º 20
0
 public function testIsActiveReturnsFalseWhenRequestHasLessParams()
 {
     $page = new Page\Mvc(array('label' => 'foo', 'action' => 'view', 'controller' => 'post', 'module' => 'blog', 'params' => array('id' => '1337')));
     $routeMatch = new RouteMatch(array('module' => 'blog', 'controller' => 'post', 'action' => 'view', 'id' => null));
     $routeMatch->setMatchedRouteName('default');
     $this->urlHelper->setRouteMatch($routeMatch);
     $page->setRouteMatch($routeMatch);
     $this->assertFalse($page->isActive());
 }
Ejemplo n.º 21
0
 public function testCanPassBooleanValueForThirdArgumentToAllowReusingRouteMatches()
 {
     $this->router->addRoute('replace', SegmentRoute::factory(array('route' => '/:controller/:action', 'defaults' => array('controller' => 'ZendTest\\Mvc\\Controller\\TestAsset\\SampleController'))));
     $routeMatch = new RouteMatch(array('controller' => 'foo'));
     $routeMatch->setMatchedRouteName('replace');
     $this->controller->getEvent()->setRouteMatch($routeMatch);
     $response = $this->plugin->toRoute('replace', array('action' => 'bar'), true);
     $headers = $response->getHeaders();
     $location = $headers->get('Location');
     $this->assertEquals('/foo/bar', $location->getFieldValue());
 }
Ejemplo n.º 22
0
 public function testRecursiveDetectIsActiveWhenRouteNameIsKnown()
 {
     $parentPage = new Page\Mvc(array('label' => 'some Label', 'route' => 'parentPageRoute'));
     $childPage = new Page\Mvc(array('label' => 'child', 'route' => 'childPageRoute'));
     $parentPage->addPage($childPage);
     $router = new TreeRouteStack();
     $router->addRoutes(array('parentPageRoute' => array('type' => 'literal', 'options' => array('route' => '/foo', 'defaults' => array('controller' => 'fooController', 'action' => 'fooAction'))), 'childPageRoute' => array('type' => 'literal', 'options' => array('route' => '/bar', 'defaults' => array('controller' => 'barController', 'action' => 'barAction')))));
     $routeMatch = new RouteMatch(array(ModuleRouteListener::MODULE_NAMESPACE => 'Application\\Controller', 'controller' => 'barController', 'action' => 'barAction'));
     $routeMatch->setMatchedRouteName('childPageRoute');
     $event = new MvcEvent();
     $event->setRouter($router)->setRouteMatch($routeMatch);
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->onRoute($event);
     $parentPage->setRouter($event->getRouter());
     $parentPage->setRouteMatch($event->getRouteMatch());
     $childPage->setRouter($event->getRouter());
     $childPage->setRouteMatch($event->getRouteMatch());
     $this->assertTrue($childPage->isActive(true));
     $this->assertTrue($parentPage->isActive(true));
 }
Ejemplo n.º 23
0
 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->setMatchedRouteName('adminRoute');
     $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', 'guest']);
     $roleService = new RoleService($identityProvider, $roleProvider, new RecursiveRoleIteratorStrategy());
     $routeGuard = new RouteGuard($roleService, ['adminRoute' => 'guest']);
     $routeGuard->onResult($event);
     $this->assertTrue($event->propagationIsStopped());
     $this->assertEquals(RouteGuard::GUARD_UNAUTHORIZED, $event->getError());
     $this->assertInstanceOf('ZfjRbac\\Exception\\UnauthorizedException', $event->getParam('exception'));
 }
Ejemplo n.º 24
0
 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'));
 }
Ejemplo n.º 25
0
 public function testCanPassBooleanValueForThirdArgumentToAllowReusingRouteMatches()
 {
     $this->router->addRoute('replace', array('type' => 'Zend\\Mvc\\Router\\Http\\Segment', 'options' => array('route' => '/:controller/:action', 'defaults' => array('controller' => 'ZendTest\\Mvc\\Controller\\TestAsset\\SampleController'))));
     $routeMatch = new RouteMatch(array('controller' => 'foo'));
     $routeMatch->setMatchedRouteName('replace');
     $this->url->setRouteMatch($routeMatch);
     $url = $this->url->__invoke('replace', array('action' => 'bar'), true);
     $this->assertEquals('/foo/bar', $url);
 }
Ejemplo n.º 26
0
 public function testMatchedRouteNameIsSet()
 {
     $match = new RouteMatch(array());
     $match->setMatchedRouteName('foo');
     $this->assertEquals('foo', $match->getMatchedRouteName());
 }
Ejemplo n.º 27
0
 public function testInheritedRouteMatchParamsWorkWithModuleRouteListener()
 {
     $page = new Page\Mvc(array('label' => 'mpinkstonwashere', 'route' => 'lmaoplane'));
     $route = new SegmentRoute('/lmaoplane[/:controller]');
     $router = new TreeRouteStack();
     $router->addRoute('lmaoplane', $route);
     $routeMatch = new RouteMatch(array(ModuleRouteListener::MODULE_NAMESPACE => 'Application\\Controller', 'controller' => 'index'));
     $routeMatch->setMatchedRouteName('lmaoplane');
     $event = new MvcEvent();
     $event->setRouter($router)->setRouteMatch($routeMatch);
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->onRoute($event);
     $page->setRouter($event->getRouter());
     $page->setRouteMatch($event->getRouteMatch());
     $this->assertEquals('/lmaoplane', $page->getHref());
     $page->setUseRouteMatch(true);
     $this->assertEquals('/lmaoplane/index', $page->getHref());
 }
Ejemplo n.º 28
0
 public function testRemovesModuleRouteListenerParamsWhenReusingMatchedParameters()
 {
     $router = new \Zend\Mvc\Router\Http\TreeRouteStack();
     $router->addRoute('default', array('type' => 'Zend\\Mvc\\Router\\Http\\Segment', 'options' => array('route' => '/:controller/:action', 'defaults' => array(ModuleRouteListener::MODULE_NAMESPACE => 'ZendTest\\Mvc\\Controller\\TestAsset', 'controller' => 'SampleController', 'action' => 'Dash')), 'child_routes' => array('wildcard' => array('type' => 'Zend\\Mvc\\Router\\Http\\Wildcard', 'options' => array('param_delimiter' => '=', 'key_value_delimiter' => '%')))));
     $routeMatch = new RouteMatch(array(ModuleRouteListener::MODULE_NAMESPACE => 'ZendTest\\Mvc\\Controller\\TestAsset', 'controller' => 'Rainbow'));
     $routeMatch->setMatchedRouteName('default/wildcard');
     $event = new MvcEvent();
     $event->setRouter($router)->setRouteMatch($routeMatch);
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->onRoute($event);
     $controller = new SampleController();
     $controller->setEvent($event);
     $url = $controller->plugin('url')->fromRoute('default/wildcard', array('Twenty' => 'Cooler'), true);
     $this->assertEquals('/Rainbow/Dash=Twenty%Cooler', $url);
 }
Ejemplo n.º 29
0
    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);
    }