示例#1
0
 /**
  * {@inheritDoc}
  */
 public function switchInstance(InstanceInterface $instance)
 {
     $container = $this->getContainer();
     $container->offsetSet('instance', $instance->getId());
     $url = $this->router->assemble($this->routeMatch->getParams(), ['name' => $this->routeMatch->getMatchedRouteName()]);
     $this->redirect($url);
 }
示例#2
0
文件: Module.php 项目: jrodev/Yoson
 public function onBootstrap(MvcEvent $e)
 {
     $callback = function (MvcEvent $event) {
         $view = $event->getApplication()->getServiceManager()->get('ViewRenderer');
         $config = $event->getApplication()->getConfig();
         $controller = $event->getTarget();
         $rm = $event->getRouteMatch();
         if (!$rm instanceof RouteMatch) {
             $rm = new RouteMatch(array('module' => 'Application', '__NAMESPACE__' => 'Application\\Controller', '__CONTROLLER__' => 'index', 'controller' => 'Application\\Controller\\Index', 'action' => 'index'));
         }
         $params = $rm->getParams();
         $modulo = "";
         if (isset($params['__NAMESPACE__'])) {
             $paramsArray = explode("\\", $params['__NAMESPACE__']);
             $modulo = $paramsArray[0];
         }
         $controller = isset($params['__CONTROLLER__']) ? $params['__CONTROLLER__'] : "";
         $action = isset($params['action']) ? $params['action'] : null;
         $app = $event->getParam('application');
         $sm = $app->getServiceManager();
         $paramsConfig = ['modulo' => strtolower($modulo), 'controller' => strtolower($controller), 'action' => strtolower($action), 'baseHost' => $view->base_path("/"), 'cssStaticHost' => "", 'jsStaticHost' => "", 'statHost' => "", 'eHost' => "", 'statVers' => '?', 'min' => '', 'AppCore' => [], 'AppSandbox' => [], 'AppSchema' => ['modules' => [], 'requires' => []]];
         $view->inlineScript()->appendScript("var yOSON=" . json_encode($paramsConfig, JSON_FORCE_OBJECT));
     };
     $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\\Mvc\\Controller\\AbstractActionController', MvcEvent::EVENT_DISPATCH, $callback, 100);
     $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\\Mvc\\Application', MvcEvent::EVENT_DISPATCH_ERROR, $callback, 100);
 }
示例#3
0
 /**
  * Get the current action's name
  *
  * @return string|bool
  */
 public function __invoke()
 {
     if ($this->routeMatch) {
         return $this->routeMatch->getMatchedRouteName();
     }
     return false;
 }
示例#4
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');
    }
 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);
     }
 }
 public function testNoRolesAllowed()
 {
     $this->routeMatch->setParam('action', 'noRoles');
     $listener = new Authorized();
     $listener->onDispach($this->event);
     $this->assertNull($this->event->getParam('exception'));
 }
 /**
  * Retrieve the version from the route match.
  *
  * The route prototype sets "version", while the Content-Type listener sets
  * "zf_ver_version"; check both to obtain the version, giving priority to the
  * route prototype result.
  *
  * @param  RouteMatch $routeMatches
  * @return int|false
  */
 protected function getVersionFromRouteMatch(RouteMatch $routeMatches)
 {
     $version = $routeMatches->getParam('zf_ver_version', false);
     if ($version) {
         return $version;
     }
     return $routeMatches->getParam('version', false);
 }
示例#8
0
文件: MvcTest.php 项目: haoyanfei/zf2
 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());
 }
 public function testResizeActionFileNotFound()
 {
     $this->routeMatch->setParam('action', 'resize');
     $this->routeMatch->setParam('file', 'img/test/fileNotFound');
     $this->routeMatch->setParam('extension', 'jpg');
     $this->routeMatch->setParam('command', 'thumb,80,40');
     $result = $this->controller->dispatch($this->request);
     $response = $this->controller->getResponse();
     $this->assertEquals(404, $response->getStatusCode());
 }
示例#10
0
 protected function getAllowedRoles(RouteMatch $routeMatch)
 {
     $controller = strtolower($routeMatch->getParam('controller'));
     $action = strtolower($routeMatch->getParam('action'));
     $restAction = strtolower($routeMatch->getParam('restAction'));
     $rolesByAction = @$this->rules[$controller] ?: [];
     $roles = @$rolesByAction[$action] ?: @$rolesByAction[$restAction];
     $roles = $roles ?: @$rolesByAction['*'];
     return $roles;
 }
示例#11
0
 public function getResponse()
 {
     $response = $this->siteAccess->dispatch($this->routeMatch->getParam('path'))->getResponse();
     // Calc total run time
     $this->getServiceLocator()->get('accumulator')->start('Total', SCRIPT_START);
     $this->getServiceLocator()->get('accumulator')->stop('Total');
     $this->getServiceLocator()->get('accumulator')->memory_usage('Before sending response');
     $this->addDebugOutput($response);
     return $response;
 }
示例#12
0
 public static function fromRoute(\Zend\Mvc\Router\RouteMatch $route)
 {
     $internalRoute = new self();
     $internalRoute->setRoute($route->getMatchedRouteName());
     $internalRoute->setParams($route->getParams());
     if ($_GET) {
         $internalRoute->setOptions(array('query' => $_GET));
     }
     return $internalRoute;
 }
示例#13
0
 public function onDispatchError(MvcEvent $e)
 {
     if ($e->getError() !== Zf2Application::ERROR_ROUTER_NO_MATCH) {
         return;
     }
     $routeMatch = new RouteMatch(array());
     $routeMatch->setParam('controller', 'Zf1Module\\DispatchController');
     $e->setError(null);
     $e->setRouteMatch($routeMatch);
     return $routeMatch;
 }
示例#14
0
 public static function resolveController(RouteMatch $routeMatch)
 {
     if ($routeMatch->getMatchedRouteName() != 'rest') {
         return;
     }
     if ($endpoint = $routeMatch->getParam('endpoint')) {
         $routeMatch->setParam('controller', 'shard.rest.' . $endpoint);
     } else {
         $routeMatch->setParam('controller', 'shard.rest');
     }
 }
示例#15
0
 /**
  * {@inheritDoc}
  */
 public function switchInstance(InstanceInterface $instance)
 {
     if (!array_key_exists('HTTP_HOST', (array) $_SERVER)) {
         throw new Exception\RuntimeException(sprintf('Host not set.'));
     }
     $url = $this->router->assemble($this->routeMatch->getParams(), ['name' => $this->routeMatch->getMatchedRouteName()]);
     $hostNames = explode('.', $_SERVER['HTTP_HOST']);
     $tld = $hostNames[count($hostNames) - 2] . "." . $hostNames[count($hostNames) - 1];
     $url = 'http://' . $instance->getSubdomain() . '.' . $tld . $url;
     $this->redirect($url);
 }
示例#16
0
 public function testInvoke()
 {
     $url = 'someUrl';
     $this->routeMatch->expects($this->once())->method('getMatchedRouteName')->will($this->returnValue('someRoute'));
     $headers = $this->getMock('Zend\\Http\\Headers');
     $headers->expects($this->once())->method('addHeaderLine')->with('Location', $url);
     $this->router->expects($this->any())->method('assemble')->with(array(), array('name' => 'zfcuser'))->will($this->returnValue($url));
     $this->response->expects($this->once())->method('getHeaders')->will($this->returnValue($headers));
     $this->response->expects($this->once())->method('setStatusCode')->with(302);
     $result = $this->redirectCallback->__invoke();
     $this->assertSame($this->response, $result);
 }
示例#17
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);
 }
示例#19
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));
 }
示例#20
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');
 }
 /**
  * {@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);
 }
 /**
  * Inject regex matches into the route matches
  *
  * @param  RouteMatch $routeMatches
  */
 protected function injectRouteMatches(RouteMatch $routeMatches, $matches)
 {
     if (!class_exists('\\ZF\\Apigility\\Admin\\Module', false)) {
         $vendor = $matches['zf_ver_vendor'];
         $version = $matches['zf_ver_version'];
         $controllerTest = $vendor . '\\V' . $version;
         if (strpos($routeMatches->getParam('controller'), $controllerTest) !== 0) {
             $controllerParts = explode('\\', $routeMatches->getParam('controller'));
             $controllerParts[0] = $vendor;
             $controllerParts[1] = 'V' . $version;
             $controller = implode('\\', $controllerParts);
             $routeMatches->setParam('controller', $controller);
         }
     }
 }
 /**
  * Create the modelResource that will be used in ACL checks
  * @param \Zend\Mvc\Router\RouteMatch $routeMatch
  * @param Request $request
  * @param type $resourceString
  * @return \Application\Authorization\ModelResource
  */
 private function getModelResource(\Zend\Mvc\Router\RouteMatch $routeMatch, Request $request, $resourceString)
 {
     $controller = $routeMatch->getParam('controller', false);
     $identifierName = $this->restControllers[$controller];
     $id = $this->getIdentifier($identifierName, $routeMatch, $request);
     $model = $this->config['zf-rest'][$controller]['entity_class'];
     // If we are trying to create a new relation object, then we need to get ACL
     // from the pre-existing objects in DB, so we adapt a few things
     if (array_key_exists($resourceString, $this->mapping)) {
         $mapping = $this->mapping[$resourceString];
         $model = $mapping['model'];
         $id = $this->getId($request, $mapping['id']);
     }
     return new ModelResource($resourceString, $model, $id);
 }
示例#24
0
 protected function setUp()
 {
     $serviceManagerGrabber = new ServiceManagerGrabber();
     $this->serviceManager = $serviceManagerGrabber->getServiceManager();
     $this->serviceManager->setAllowOverride(true);
     $this->serviceManager->setService('doctrine.entitymanager.orm_default', $this->getEntityManagerMock());
     $config = $this->serviceManager->get('Config');
     $this->request = new PhpEnviromentRequest();
     $this->router = HttpRouter::factory(isset($config['router']) ? $config['router'] : array());
     $this->routeMatch = new RouteMatch(array('controller' => 'index'));
     $this->routeMatch->setParam('lang', 'it');
     $this->event = new MvcEvent();
     $this->event->setRouter($this->router);
     $this->event->setRouteMatch($this->routeMatch);
 }
示例#25
0
 /**
  * Mimics zf1 Request::getParam behavior
  *
  * Route match -> GET -> POST
  */
 public static function staticGetParam(RouteMatch $routeMatch, Request $request, $param = null, $default = null)
 {
     if ($param === null) {
         $params = (array) $routeMatch->getParams();
         if ($request instanceof ConsoleRequest) {
             return $params + (array) $request->getParams();
         }
         return $params + $request->getQuery()->toArray() + $request->getPost()->toArray();
     }
     if ($request instanceof ConsoleRequest) {
         $default = $request->getParam($param, $default);
     } else {
         $default = $request->getQuery($param, $request->getPost($param, $default));
     }
     return $routeMatch->getParam($param, $default);
 }
示例#26
0
文件: Mvc.php 项目: ranxin1022/zf2
 /**
  * Returns whether page should be considered active or not
  *
  * This method will compare the page properties against the route matches
  * composed in the object.
  *
  * @param  bool $recursive  [optional] whether page should be considered
  *                          active if any child pages are active. Default is
  *                          false.
  * @return bool             whether page should be considered active or not
  */
 public function isActive($recursive = false)
 {
     if (!$this->active) {
         $reqParams = array();
         if ($this->routeMatch instanceof RouteMatch) {
             $reqParams = $this->routeMatch->getParams();
             if ($this->routeMatch->getMatchedRouteName() === $this->getRoute()) {
                 $this->active = true;
                 return true;
             }
         }
         $myParams = $this->params;
         if (null !== $this->controller) {
             $myParams['controller'] = $this->controller;
         } else {
             /**
              * @todo In ZF1, this was configurable and pulled from the front controller
              */
             $myParams['controller'] = 'index';
         }
         if (null !== $this->action) {
             $myParams['action'] = $this->action;
         } else {
             /**
              * @todo In ZF1, this was configurable and pulled from the front controller
              */
             $myParams['action'] = 'action';
         }
         if (count(array_intersect_assoc($reqParams, $myParams)) == count($myParams)) {
             $this->active = true;
             return true;
         }
     }
     return parent::isActive($recursive);
 }
示例#27
0
 /**
  * @depends testGetCategory
  * @param int $id
  */
 public function testDeleteCategory($id)
 {
     $this->getRequest()->setMethod(Request::METHOD_DELETE);
     $this->routeMatch->setParam('id', $id);
     $jsonModel = $this->dispatchRequest();
     $this->assertEquals(200, $this->controller->getResponse()->getStatusCode());
     $this->assertEquals('success', $jsonModel->getVariable('message')['type']);
 }
示例#28
0
 /**
  * @covers \Project\Controller\ProjectController::searchAction
  */
 public function testCanSearchProjects()
 {
     $this->routeMatch->setParam('action', 'search');
     $queryParams = new Parameters(['search_item' => 'test', 'max_rows' => 12]);
     $this->request->setQuery($queryParams);
     $this->controller->dispatch($this->request, $this->response);
     $this->assertEquals(200, $this->controller->getResponse()->getStatusCode());
 }
示例#29
0
 /**
  * @covers \Project\Controller\IdeaController::updateDescriptionAction
  */
 public function testUpdateWrongIdeaDescriptionGives404()
 {
     $this->routeMatch->setParam('action', 'update-description');
     $queryParams = new Parameters(['id' => 'description-0', 'value' => 'This is the new description']);
     $this->request->setPost($queryParams);
     $this->controller->dispatch($this->request, $this->response);
     $this->assertEquals(404, $this->controller->getResponse()->getStatusCode());
 }
示例#30
0
 /**
  * Check if we should cache the request based on the params in the routematch
  *
  * @param  RouteMatch $match
  * @param  array      $routeConfig
  * @return bool
  */
 protected function checkParams(RouteMatch $match, $routeConfig)
 {
     if (!isset($routeConfig['params'])) {
         return true;
     }
     $params = (array) $routeConfig['params'];
     foreach ($params as $name => $value) {
         $param = $match->getParam($name, null);
         if (null === $param) {
             continue;
         }
         if (!$this->checkParam($param, $value)) {
             return false;
         }
     }
     return true;
 }