When adding a route, it overrides existing routes with the same name defined in the instance or its children and parents.
Author: Fabien Potencier (fabien@symfony.com)
Inheritance: implements IteratorAggregate, implements Countable
Example #1
0
 public function __construct(Request $request, array $options)
 {
     parent::__construct($request, $options);
     $this->methods = new Map();
     // create routes from db
     $apis = ApiQuery::create()->joinAction()->useActionQuery()->joinModule()->endUse()->find();
     $routes = new RouteCollection();
     /* @var $api Api */
     foreach ($apis as $api) {
         $action = $api->getAction();
         $module = $action->getModule();
         $path = str_replace('//', '/', '/' . $api->getRoute());
         $required = $api->getRequiredParams();
         $required = is_array($required) ? explode(',', $required) : [];
         $name = $module->getName() . ':' . $action->getName() . '@' . $api->getMethod();
         $route = new Route($path, ['path' => $path, 'action' => $action], $required, [], null, [], [$api->getMethod(), 'options']);
         // debug: print routes
         // 			printf("%s: %s -> %s\n", $api->getMethod(), $path, $module->getName() . ':' . $action->getName());
         $routes->add($name, $route);
         // with params
         $paramRoute = clone $route;
         $paramRoute->setPath(sprintf('%s%s{params}', $path, $this->options['param-separator']));
         $paramRoute->setRequirement('params', '.+');
         $paramName = $name . 'WithParam';
         $routes->add($paramName, $paramRoute);
         if (!$this->methods->has($path)) {
             $this->methods->set($path, new ArrayList());
         }
         $this->methods->get($path)->add(strtoupper($api->getMethod()));
     }
     $this->init($routes);
 }
 /**
  * Tests the onAlterRoutes method.
  *
  * @see \Drupal\views\EventSubscriber\RouteSubscriber::onAlterRoutes()
  */
 public function testOnAlterRoutes()
 {
     $collection = new RouteCollection();
     // The first route will be overridden later.
     $collection->add('test_route', new Route('test_route', array('_controller' => 'Drupal\\Tests\\Core\\Controller\\TestController')));
     $route_2 = new Route('test_route/example', array('_controller' => 'Drupal\\Tests\\Core\\Controller\\TestController'));
     $collection->add('test_route_2', $route_2);
     $route_event = new RouteBuildEvent($collection, 'views');
     list($view, $executable, $display_1, $display_2) = $this->setupMocks();
     // The page_1 display overrides an existing route, so the dynamicRoutes
     // should only call the second display.
     $display_1->expects($this->once())->method('collectRoutes')->willReturnCallback(function () use($collection) {
         $collection->add('views.test_id.page_1', new Route('test_route', ['_content' => 'Drupal\\views\\Routing\\ViewPageController']));
         return ['test_id.page_1' => 'views.test_id.page_1'];
     });
     $display_1->expects($this->once())->method('alterRoutes')->willReturn(['test_id.page_1' => 'test_route']);
     $display_2->expects($this->once())->method('collectRoutes')->willReturnCallback(function () use($collection) {
         $collection->add('views.test_id.page_2', new Route('test_route', ['_content' => 'Drupal\\views\\Routing\\ViewPageController']));
         return ['test_id.page_2' => 'views.test_id.page_2'];
     });
     $display_2->expects($this->once())->method('alterRoutes')->willReturn([]);
     // Ensure that even both the collectRoutes() and alterRoutes() methods
     // are called on the displays, we ensure that the route first defined by
     // views is dropped.
     $this->routeSubscriber->routes();
     $this->assertNull($this->routeSubscriber->onAlterRoutes($route_event));
     $this->state->expects($this->once())->method('set')->with('views.view_route_names', array('test_id.page_1' => 'test_route', 'test_id.page_2' => 'views.test_id.page_2'));
     $collection = $route_event->getRouteCollection();
     $this->assertEquals(['test_route', 'test_route_2', 'views.test_id.page_2'], array_keys($collection->all()));
     $this->routeSubscriber->routeRebuildFinished();
 }
 /**
  * {@inheritdoc}
  */
 public function filter(RouteCollection $collection, Request $request)
 {
     // The Content-type header does not make sense on GET requests, because GET
     // requests do not carry any content. Nothing to filter in this case.
     if ($request->isMethod('GET')) {
         return $collection;
     }
     $format = $request->getContentType();
     foreach ($collection as $name => $route) {
         $supported_formats = array_filter(explode('|', $route->getRequirement('_content_type_format')));
         if (empty($supported_formats)) {
             // No restriction on the route, so we move the route to the end of the
             // collection by re-adding it. That way generic routes sink down in the
             // list and exact matching routes stay on top.
             $collection->add($name, $route);
         } elseif (!in_array($format, $supported_formats)) {
             $collection->remove($name);
         }
     }
     if (count($collection)) {
         return $collection;
     }
     // We do not throw a
     // \Symfony\Component\Routing\Exception\ResourceNotFoundException here
     // because we don't want to return a 404 status code, but rather a 415.
     throw new UnsupportedMediaTypeHttpException('No route found that matches "Content-Type: ' . $request->headers->get('Content-Type') . '"');
 }
Example #4
0
 function run()
 {
     $routes = new RouteCollection();
     foreach ($this->serviceManager->get('ConfigManager')->getConfig('routes') as $rota => $values) {
         $routes->add($rota, new Route($values['route'], array('controller' => $values['controller'], 'action' => $values['action'])));
     }
     $context = $this->serviceManager->get('RequestManager')->getContext();
     $matcher = new UrlMatcher($routes, $context);
     $errorController = $this->getServiceManager()->get('ErrorController');
     try {
         $parameters = $matcher->match($context->getPathInfo());
         $controller = $this->getServiceManager()->get($parameters['controller']);
         $action = $this->getNomeAction($parameters['action']);
         if (false == method_exists($controller, $action)) {
             throw new Exception(sprintf('O Controller %s não possui o método %s', get_class($controller), $action));
         }
         $actionParameters = $this->getActionParameters($parameters);
         if (true == method_exists($controller, 'beforeDispatch')) {
             call_user_func(array($controller, 'beforeDispatch'));
         }
         return call_user_func_array(array($controller, $action), $actionParameters);
     } catch (ResourceNotFoundException $ex) {
         return $errorController->actionError404();
     } catch (MethodNotAllowedException $ex) {
         return $errorController->actionError500($ex);
     } catch (Exception $ex) {
         return $errorController->actionError500($ex);
     }
 }
  /**
   * Tests altering and finished event.
   *
   * @covers ::onRouteAlter
   * @covers ::onRouteFinished
   */
  public function testSubscribing() {

    // Ensure that onRouteFinished can be called without throwing notices
    // when no path roots got set.
    $this->pathRootsSubscriber->onRouteFinished();

    $route_collection = new RouteCollection();
    $route_collection->add('test_route1', new Route('/test/bar'));
    $route_collection->add('test_route2', new Route('/test/baz'));
    $route_collection->add('test_route3', new Route('/test2/bar/baz'));

    $event = new RouteBuildEvent($route_collection, 'provider');
    $this->pathRootsSubscriber->onRouteAlter($event);

    $route_collection = new RouteCollection();
    $route_collection->add('test_route4', new Route('/test1/bar'));
    $route_collection->add('test_route5', new Route('/test2/baz'));
    $route_collection->add('test_route6', new Route('/test2/bar/baz'));

    $event = new RouteBuildEvent($route_collection, 'provider');
    $this->pathRootsSubscriber->onRouteAlter($event);

    $this->state->expects($this->once())
      ->method('set')
      ->with('router.path_roots', array('test', 'test2', 'test1'));

    $this->pathRootsSubscriber->onRouteFinished();
  }
 protected function loadRoutes()
 {
     $this->routes->add('dynamic_route_' . ($this->routes->count() + 1), new Route('pup/image/upload/service', $defaults = array('_controller' => 'pupBundle:Process:upload'), $requirements = array()));
     //add another
     //or execute a db query and add multiple routes
     //etc.
 }
Example #7
0
 /**
  * {@inheritdoc}
  */
 protected function alterRoutes(RouteCollection $collection)
 {
     foreach ($this->entityStorage->loadMultiple() as $entity_id => $entity) {
         /** @var $entity \Drupal\page_manager\PageInterface */
         // If the page is disabled skip making a route for it.
         if (!$entity->status() || $entity->isFallbackPage()) {
             continue;
         }
         // Prepare a route name to use if this is a custom page.
         $route_name = "page_manager.page_view_{$entity_id}";
         // Prepare the values that need to be altered for an existing page.
         $path = $entity->getPath();
         $parameters = ['page_manager_page' => ['type' => 'entity:page']];
         // Loop through all existing routes to see if this is overriding a route.
         foreach ($collection->all() as $name => $collection_route) {
             // Find all paths which match the path of the current display.
             $route_path = RouteCompiler::getPathWithoutDefaults($collection_route);
             $route_path = RouteCompiler::getPatternOutline($route_path);
             if ($path == $route_path) {
                 // Adjust the path to translate %placeholders to {slugs}.
                 $path = $collection_route->getPath();
                 // Merge in any route parameter definitions.
                 $parameters += $collection_route->getOption('parameters') ?: [];
                 // Update the route name this will be added to.
                 $route_name = $name;
                 // Remove the existing route.
                 $collection->remove($route_name);
                 break;
             }
         }
         // Construct an add a new route.
         $route = new Route($path, ['_entity_view' => 'page_manager_page', 'page_manager_page' => $entity_id, '_title' => $entity->label()], ['_entity_access' => 'page_manager_page.view'], ['parameters' => $parameters, '_admin_route' => $entity->usesAdminTheme()]);
         $collection->add($route_name, $route);
     }
 }
Example #8
0
 /**
  * {@inheritdoc}
  */
 protected function alterRoutes(RouteCollection $collection) {
   foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
     if ($route = $this->getEntityCloneRoute($entity_type)) {
       $collection->add("entity.$entity_type_id.clone_form", $route);
     }
   }
 }
 /**
  * @inheritDoc
  */
 public function getRouteCollectionForRequest(Request $request)
 {
     if (!$this->manager) {
         throw new \Exception('Manager must be set to execute query to the elasticsearch');
     }
     $routeCollection = new RouteCollection();
     $requestPath = $request->getPathInfo();
     $search = new Search();
     $search->addQuery(new MatchQuery('url', $requestPath));
     $results = $this->manager->execute(array_keys($this->routeMap), $search, Result::RESULTS_OBJECT);
     try {
         foreach ($results as $document) {
             $type = $this->collector->getDocumentType(get_class($document));
             if (array_key_exists($type, $this->routeMap)) {
                 $route = new Route($document->url, ['_controller' => $this->routeMap[$type], 'document' => $document, 'type' => $type]);
                 $routeCollection->add('ongr_route_' . $route->getDefault('type'), $route);
             } else {
                 throw new RouteNotFoundException(sprintf('Route for type %s% cannot be generated.', $type));
             }
         }
     } catch (\Exception $e) {
         throw new RouteNotFoundException('Document is not correct or route cannot be generated.');
     }
     return $routeCollection;
 }
Example #10
0
 /**
  * @todo clean this
  */
 public function load($resource, $type = null)
 {
     if (true === $this->loaded) {
         throw new \RuntimeException('Do not add this loader twice');
     }
     $routes = new RouteCollection();
     $frontPageConfig = $this->container->get('system')->get('system.frontpage', 'blog');
     $frontPageProvider = $this->container->get('drafterbit_system.frontpage_provider');
     $reservedBaseUrl = [$this->container->getParameter('admin')];
     foreach ($frontPageProvider->all() as $prefix => $frontPage) {
         $frontRoutes = $frontPage->getRoutes();
         if ($prefix !== $frontPageConfig) {
             $frontRoutes->addPrefix($frontPage->getRoutePrefix());
             $reservedBaseUrl[] = $prefix;
         }
         $routes->addCollection($frontRoutes);
     }
     $defaults = array('_controller' => 'DrafterbitPageBundle:Frontend:view');
     // check if configured frontpage is not an app
     if (!array_key_exists($frontPageConfig, $frontPageProvider->all())) {
         // its page
         $defaults['slug'] = $frontPageConfig;
         $routes->add('_home', new Route('/', $defaults));
     }
     $reservedBaseUrl = implode('|', $reservedBaseUrl);
     // @link http://stackoverflow.com/questions/25496704/regex-match-slug-except-particular-start-words
     // @prototype  'slug' => "^(?!(?:backend|blog)(?:/|$)).*$"
     $requirements = array('slug' => "^(?!(?:%admin%|" . $reservedBaseUrl . "|)(?:/|\$)).*\$");
     $route2 = new Route('/{slug}', $defaults, $requirements);
     $routes->add('misc', $route2);
     return $routes;
 }
 public function testMatch()
 {
     // test the patterns are matched are parameters are returned
     $collection = new RouteCollection();
     $collection->add('foo', new Route('/foo/{bar}'));
     $matcher = new UrlMatcher($collection, array(), array());
     try {
         $matcher->match('/no-match');
         $this->fail();
     } catch (NotFoundException $e) {
     }
     $this->assertEquals(array('_route' => 'foo', 'bar' => 'baz'), $matcher->match('/foo/baz'));
     // test that defaults are merged
     $collection = new RouteCollection();
     $collection->add('foo', new Route('/foo/{bar}', array('def' => 'test')));
     $matcher = new UrlMatcher($collection, array(), array());
     $this->assertEquals(array('_route' => 'foo', 'bar' => 'baz', 'def' => 'test'), $matcher->match('/foo/baz'));
     // test that route "method" is ignored if no method is given in the context
     $collection = new RouteCollection();
     $collection->add('foo', new Route('/foo', array(), array('_method' => 'GET|head')));
     $matcher = new UrlMatcher($collection, array(), array());
     $this->assertInternalType('array', $matcher->match('/foo'));
     // route does not match with POST method context
     $matcher = new UrlMatcher($collection, array('method' => 'POST'), array());
     try {
         $matcher->match('/foo');
         $this->fail();
     } catch (MethodNotAllowedException $e) {
     }
     // route does match with GET or HEAD method context
     $matcher = new UrlMatcher($collection, array('method' => 'GET'), array());
     $this->assertInternalType('array', $matcher->match('/foo'));
     $matcher = new UrlMatcher($collection, array('method' => 'HEAD'), array());
     $this->assertInternalType('array', $matcher->match('/foo'));
 }
 public function testSchemeRedirect()
 {
     $coll = new RouteCollection();
     $coll->add('foo', new Route('/foo', array(), array('_scheme' => 'https')));
     $matcher = new RedirectableUrlMatcher($coll, $context = new RequestContext());
     $this->assertEquals(array('_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction', 'path' => '/foo', 'permanent' => true, 'scheme' => 'https', 'httpPort' => $context->getHttpPort(), 'httpsPort' => $context->getHttpsPort(), '_route' => 'foo'), $matcher->match('/foo'));
 }
Example #13
0
 public function testMatch()
 {
     // test the patterns are matched are parameters are returned
     $collection = new RouteCollection();
     $collection->add('foo', new Route('/foo/{bar}'));
     $matcher = new UrlMatcher($collection, array(), array());
     $this->assertEquals(false, $matcher->match('/no-match'));
     $this->assertEquals(array('_route' => 'foo', 'bar' => 'baz'), $matcher->match('/foo/baz'));
     // test that defaults are merged
     $collection = new RouteCollection();
     $collection->add('foo', new Route('/foo/{bar}', array('def' => 'test')));
     $matcher = new UrlMatcher($collection, array(), array());
     $this->assertEquals(array('_route' => 'foo', 'bar' => 'baz', 'def' => 'test'), $matcher->match('/foo/baz'));
     // test that route "metod" is ignore if no method is given in the context
     $collection = new RouteCollection();
     $collection->add('foo', new Route('/foo', array(), array('_method' => 'GET|head')));
     // route matches with no context
     $matcher = new UrlMatcher($collection, array(), array());
     $this->assertNotEquals(false, $matcher->match('/foo'));
     // route does not match with POST method context
     $matcher = new UrlMatcher($collection, array('method' => 'POST'), array());
     $this->assertEquals(false, $matcher->match('/foo'));
     // route does match with GET or HEAD method context
     $matcher = new UrlMatcher($collection, array('method' => 'GET'), array());
     $this->assertNotEquals(false, $matcher->match('/foo'));
     $matcher = new UrlMatcher($collection, array('method' => 'HEAD'), array());
     $this->assertNotEquals(false, $matcher->match('/foo'));
 }
Example #14
0
 /**
  * {@inheritdoc}
  */
 protected function alterRoutes(RouteCollection $collection)
 {
     if ($route = $collection->get('system.modules_list')) {
         $route->setDefault('_form', 'Drupal\\mmu\\Form\\ModulesListForm');
         $collection->add('system.modules_list', $route);
     }
 }
 private function addRoute(RouteCollection $routes, $filter, $pattern, $host = '')
 {
     $requirements = ['_methods' => 'GET', 'filter' => '[A-z0-9_\\-]*', 'path' => '.+'];
     $defaults = ['_controller' => 'imagine.controller:filterAction'];
     $routeSuffix = $host ? '_' . preg_replace('#[^a-z0-9]+#i', '_', $host) : '';
     $routes->add('_imagine_' . $filter . $routeSuffix, new Route($pattern, array_merge($defaults, ['filter' => $filter]), $requirements, [], $host));
 }
 /**
  * {@inheritdoc}
  */
 public function load($resource, $type = null)
 {
     if (true === $this->loaded) {
         throw new \RuntimeException('Do not add the "extra" loader twice');
     }
     $routes = new RouteCollection();
     // load all entites from NodeRoute-Repository
     // and add to RouteCollection
     $node_routes = $this->manager->getRepository($this->repositoryClass)->findAll();
     foreach ($node_routes as $node_route) {
         $path = $node_route->getRoute();
         // select the mapped controller for NodeRoute by discriminator value
         $defaults = array('_controller' => $this->controller[$this->manager->getClassMetadata(get_class($node_route))->discriminatorValue]);
         /**
          * @var Node $node
          */
         if (!is_null($node = $node_route->getNode())) {
             $route = new Route($path, $defaults, array(), array('route' => $node_route));
             $routeName = 'cmf_node_route_' . $node_route->getId();
             $routes->add($routeName, $route);
         }
     }
     $this->loaded = true;
     return $routes;
 }
 /**
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  *
  * @param mixed $resource
  * @param null  $type
  *
  * @return RouteCollection
  */
 public function load($resource, $type = null) : RouteCollection
 {
     $resource = (string) $resource;
     if (in_array($resource, $this->descriptions)) {
         throw new \RuntimeException("Resource '{$resource}' was already loaded");
     }
     $description = $this->repository->get($resource);
     $routes = new RouteCollection();
     $router = $description->getExtension('router') ?: 'swagger.controller';
     $routerController = $description->getExtension('router-controller');
     foreach ($description->getPaths() as $pathItem) {
         $relativePath = ltrim($pathItem->getPath(), '/');
         $resourceName = strpos($relativePath, '/') ? substr($relativePath, 0, strpos($relativePath, '/')) : $relativePath;
         $routerController = $pathItem->getExtension('router-controller') ?: $routerController;
         foreach ($pathItem->getOperations() as $operation) {
             $controllerKey = $this->resolveControllerKey($operation, $resourceName, $router, $routerController);
             $defaults = ['_controller' => $controllerKey, RequestMeta::ATTRIBUTE_URI => $resource, RequestMeta::ATTRIBUTE_PATH => $pathItem->getPath()];
             $route = new Route($pathItem->getPath(), $defaults, $this->resolveRequirements($operation));
             $route->setMethods($operation->getMethod());
             $routes->add($this->createRouteId($resource, $pathItem->getPath(), $controllerKey), $route);
         }
     }
     $this->descriptions[] = $resource;
     return $routes;
 }
Example #18
0
 /**
  * @expectedException \LogicException
  */
 public function testDumpWhenSchemeIsUsedWithoutAProperDumper()
 {
     $collection = new RouteCollection();
     $collection->add('secure', new Route('/secure', array(), array('_scheme' => 'https')));
     $dumper = new PhpMatcherDumper($collection, new RequestContext());
     $dumper->dump();
 }
Example #19
0
 public function testPlaceholders()
 {
     $routes = new RouteCollection();
     $routes->add('foo', new Route('/foo', array('foo' => '%foo%', 'bar' => '%bar%', 'foobar' => 'foobar', 'foo1' => '%foo', 'foo2' => 'foo%', 'foo3' => 'f%o%o'), array('foo' => '%foo%', 'bar' => '%bar%', 'foobar' => 'foobar', 'foo1' => '%foo', 'foo2' => 'foo%', 'foo3' => 'f%o%o')));
     $sc = $this->getServiceContainer($routes);
     $sc->expects($this->at(1))->method('hasParameter')->will($this->returnValue(false));
     $sc->expects($this->at(2))->method('hasParameter')->will($this->returnValue(true));
     $sc->expects($this->at(3))->method('getParameter')->will($this->returnValue('bar'));
     $sc->expects($this->at(4))->method('hasParameter')->will($this->returnValue(false));
     $sc->expects($this->at(5))->method('hasParameter')->will($this->returnValue(true));
     $sc->expects($this->at(6))->method('getParameter')->will($this->returnValue('bar'));
     $router = new Router($sc, 'foo');
     $route = $router->getRouteCollection()->get('foo');
     $this->assertEquals('%foo%', $route->getDefault('foo'));
     $this->assertEquals('bar', $route->getDefault('bar'));
     $this->assertEquals('foobar', $route->getDefault('foobar'));
     $this->assertEquals('%foo', $route->getDefault('foo1'));
     $this->assertEquals('foo%', $route->getDefault('foo2'));
     $this->assertEquals('f%o%o', $route->getDefault('foo3'));
     $this->assertEquals('%foo%', $route->getRequirement('foo'));
     $this->assertEquals('bar', $route->getRequirement('bar'));
     $this->assertEquals('foobar', $route->getRequirement('foobar'));
     $this->assertEquals('%foo', $route->getRequirement('foo1'));
     $this->assertEquals('foo%', $route->getRequirement('foo2'));
     $this->assertEquals('f%o%o', $route->getRequirement('foo3'));
 }
Example #20
0
 public function load($routingResource, $type = null)
 {
     $routes = new RouteCollection();
     // resources
     foreach ($this->am->getResources() as $resources) {
         if (!$resources instanceof \Traversable) {
             $resources = array($resources);
         }
         foreach ($resources as $resource) {
             if (file_exists($path = (string) $resource)) {
                 $routes->addResource(new FileResource($path));
             }
         }
     }
     // routes
     foreach ($this->am->getNames() as $name) {
         $asset = $this->am->get($name);
         $defaults = array('_controller' => 'assetic.controller:render', 'name' => $name);
         if ($extension = pathinfo($asset->getTargetUrl(), PATHINFO_EXTENSION)) {
             $defaults['_format'] = $extension;
         }
         $routes->add('assetic_' . $name, new Route($asset->getTargetUrl(), $defaults));
     }
     return $routes;
 }
 public function load(RouteCollection $collection)
 {
     $i18nCollection = new RouteCollection();
     foreach ($collection->getResources() as $resource) {
         $i18nCollection->addResource($resource);
     }
     $this->patternGenerationStrategy->addResources($i18nCollection);
     foreach ($collection->all() as $name => $route) {
         if ($this->routeExclusionStrategy->shouldExcludeRoute($name, $route)) {
             $i18nCollection->add($name, $route);
             continue;
         }
         foreach ($this->patternGenerationStrategy->generateI18nPatterns($name, $route) as $pattern => $locales) {
             // If this pattern is used for more than one locale, we need to keep the original route.
             // We still add individual routes for each locale afterwards for faster generation.
             if (count($locales) > 1) {
                 $catchMultipleRoute = clone $route;
                 $catchMultipleRoute->getPath($pattern);
                 $catchMultipleRoute->setDefault('_locales', $locales);
                 $i18nCollection->add(implode('_', $locales) . I18nLoader::ROUTING_PREFIX . $name, $catchMultipleRoute);
             }
             foreach ($locales as $locale) {
                 $localeRoute = clone $route;
                 $localeRoute->getPath($pattern);
                 $localeRoute->setDefault('_locale', $locale);
                 $i18nCollection->add($locale . I18nLoader::ROUTING_PREFIX . $name, $localeRoute);
             }
         }
     }
     return $i18nCollection;
 }
 public function testSchemeRedirect()
 {
     $coll = new RouteCollection();
     $coll->add('foo', new Route('/foo', array(), array('_scheme' => 'https')));
     $matcher = new RedirectableUrlMatcher($coll, $context = new RequestContext());
     $this->assertEquals(array('_route' => 'foo'), $matcher->match('/foo'));
 }
 public function testDumpWithSchemeRequirement()
 {
     $this->routeCollection->add('Test1', new Route('/testing', array(), array(), array(), '', array('ftp', 'https')));
     $this->routeCollection->add('Test2', new Route('/testing_bc', array(), array('_scheme' => 'https')));
     // BC
     file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'SchemeUrlGenerator')));
     include $this->testTmpFilepath;
     $projectUrlGenerator = new \SchemeUrlGenerator(new RequestContext('/app.php'));
     $absoluteUrl = $projectUrlGenerator->generate('Test1', array(), true);
     $absoluteUrlBC = $projectUrlGenerator->generate('Test2', array(), true);
     $relativeUrl = $projectUrlGenerator->generate('Test1', array(), false);
     $relativeUrlBC = $projectUrlGenerator->generate('Test2', array(), false);
     $this->assertEquals($absoluteUrl, 'ftp://localhost/app.php/testing');
     $this->assertEquals($absoluteUrlBC, 'https://localhost/app.php/testing_bc');
     $this->assertEquals($relativeUrl, 'ftp://localhost/app.php/testing');
     $this->assertEquals($relativeUrlBC, 'https://localhost/app.php/testing_bc');
     $projectUrlGenerator = new \SchemeUrlGenerator(new RequestContext('/app.php', 'GET', 'localhost', 'https'));
     $absoluteUrl = $projectUrlGenerator->generate('Test1', array(), true);
     $absoluteUrlBC = $projectUrlGenerator->generate('Test2', array(), true);
     $relativeUrl = $projectUrlGenerator->generate('Test1', array(), false);
     $relativeUrlBC = $projectUrlGenerator->generate('Test2', array(), false);
     $this->assertEquals($absoluteUrl, 'https://localhost/app.php/testing');
     $this->assertEquals($absoluteUrlBC, 'https://localhost/app.php/testing_bc');
     $this->assertEquals($relativeUrl, '/app.php/testing');
     $this->assertEquals($relativeUrlBC, '/app.php/testing_bc');
 }
Example #24
0
 /**
  * @param string $resource
  * @param null $type
  * @return \Symfony\Component\Routing\RouteCollection
  */
 public function load($resource, $type = null)
 {
     $routes = new RouteCollection();
     $logger = $this->container->get('logger');
     $logger->info('Загрузка рубрик для построения роутинга');
     $a = microtime(true);
     $rubrics = $this->em->getRepository('ApplicationIphpCoreBundle:Rubric')->createQueryBuilder('r')->orderBy('r.level', 'DESC')->getQuery()->getResult();
     foreach ($rubrics as $rubric) {
         $controller = $rubric->getControllerName();
         $rubricRoutes = null;
         //В контроллере можеть быть: Класс модуля
         if ($controller && substr($controller, -6) == 'Module') {
             $module = $this->moduleManager->getModuleFromRubric($rubric);
             if ($module) {
                 $rubricRoutes = $module->getRoutes();
             }
         }
         if ($rubricRoutes) {
             foreach ($rubricRoutes as $route) {
                 $route->setDefault('_rubric', $rubric->getFullPath());
             }
             $routes->addCollection($rubricRoutes, substr($rubric->getFullPath(), 0, -1));
         }
     }
     $b = microtime(true) - $a;
     $logger->info('Загрузили роуты за' . $b . ' с');
     return $routes;
 }
 public function load($resource, $type = null)
 {
     $collection = new RouteCollection();
     $resource = str_replace('\\', '/', $resource);
     $namespace = $this->getNamespaceFromResource($resource);
     $bundle_name = $this->getBundleNameFromResource($resource);
     foreach ($this->actions as $controller => $datas) {
         $action = 'index';
         if ($controller_folder = $this->getControllerFolder($resource)) {
             $route_name = str_replace(array('/', '\\'), '_', $namespace) . '_' . $bundle_name . '_' . $controller_folder . '_' . $controller;
         } else {
             $route_name = str_replace(array('/', '\\'), '_', $namespace) . '_' . $bundle_name . '_' . $controller;
         }
         if (isset($datas['controller'])) {
             $action = $controller;
             $controller = $datas['controller'];
         }
         if ($controller_folder) {
             $datas['defaults']['_controller'] = $namespace . '\\' . $bundle_name . '\\Controller\\' . $controller_folder . '\\' . ucfirst($controller) . 'Controller::' . $action . 'Action';
         } else {
             $datas['defaults']['_controller'] = str_replace(array('/', '\\'), '_', $namespace) . $bundle_name . ':' . ucfirst($controller) . ':' . $action;
         }
         $route = new Route($datas['pattern'], $datas['defaults'], $datas['requirements']);
         $collection->add($route_name, $route);
         $collection->addResource(new FileResource($resource . ucfirst($controller) . 'Controller.php'));
     }
     return $collection;
 }
Example #26
0
  /**
   * New and improved hook_menu_alter().
   */
  public function alterRoutes(RouteCollection $collection) {
    // admin/structure/taxonomy
    if ($route = $collection->get('entity.taxonomy_vocabulary.collection')) {
      $route->setRequirements(array(
        '_custom_access' => '\taxonomy_access_fix_route_access',
      ));
      $route->setOption('op', 'index');
    }

    // admin/structure/taxonomy/%vocabulary
    if ($route = $collection->get('entity.taxonomy_vocabulary.overview_form')) {
      $route->setRequirements(array(
        '_custom_access' => '\taxonomy_access_fix_route_access',
      ));
      $route->setOption('op', 'list terms');
    }

    // admin/structure/taxonomy/%vocabulary/add
    if ($route = $collection->get('entity.taxonomy_term.add_form')) {
      $route->setRequirements(array(
        '_custom_access' => '\taxonomy_access_fix_route_access',
      ));
      $route->setOption('op', 'add terms');
    }
  }
Example #27
0
 /**
  * {@inheritdoc}
  */
 protected function describeRouteCollection(RouteCollection $routes, array $options = array())
 {
     $showControllers = isset($options['show_controllers']) && $options['show_controllers'];
     $tableHeaders = array('Name', 'Method', 'Scheme', 'Host', 'Path');
     if ($showControllers) {
         $tableHeaders[] = 'Controller';
     }
     $tableRows = array();
     foreach ($routes->all() as $name => $route) {
         $row = array($name, $route->getMethods() ? implode('|', $route->getMethods()) : 'ANY', $route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY', '' !== $route->getHost() ? $route->getHost() : 'ANY', $route->getPath());
         if ($showControllers) {
             $controller = $route->getDefault('_controller');
             if ($controller instanceof \Closure) {
                 $controller = 'Closure';
             } elseif (is_object($controller)) {
                 $controller = get_class($controller);
             }
             $row[] = $controller;
         }
         $tableRows[] = $row;
     }
     if (isset($options['output'])) {
         $options['output']->table($tableHeaders, $tableRows);
     } else {
         $table = new Table($this->getOutput());
         $table->setHeaders($tableHeaders)->setRows($tableRows);
         $table->render();
     }
 }
Example #28
0
 /**
  * Add routes to the router
  * @param Loader $loader
  * @return RouteCollection
  */
 public function addAdminRoutes(Loader $loader)
 {
     $collection = new RouteCollection();
     $route = new Route('/_test/admin/route');
     $collection->add('admin_test_route', $route);
     return $collection;
 }
 /**
  * {@inheritDoc}
  *
  * This will return any document found at the url or up the path to the
  * prefix. If any of the documents does not extend the symfony Route
  * object, it is filtered out. In the extreme case this can also lead to an
  * empty list being returned.
  */
 public function getRouteCollectionForRequest(Request $request)
 {
     $url = $request->getPathInfo();
     $candidates = $this->getCandidates($url);
     $collection = new RouteCollection();
     if (empty($candidates)) {
         return $collection;
     }
     try {
         $routes = $this->dm->findMany($this->className, $candidates);
         // filter for valid route objects
         // we can not search for a specific class as PHPCR does not know class inheritance
         // but optionally we could define a node type
         foreach ($routes as $key => $route) {
             if ($route instanceof SymfonyRoute) {
                 if (preg_match('/.+\\.([a-z]+)$/i', $url, $matches)) {
                     if ($route->getDefault('_format') === $matches[1]) {
                         continue;
                     }
                     $route->setDefault('_format', $matches[1]);
                 }
                 // SYMFONY 2.1 COMPATIBILITY: tweak route name
                 $key = trim(preg_replace('/[^a-z0-9A-Z_.]/', '_', $key), '_');
                 $collection->add($key, $route);
             }
         }
     } catch (RepositoryException $e) {
         // TODO: how to determine whether this is a relevant exception or not?
         // for example, getting /my//test (note the double /) is just an invalid path
         // and means another router might handle this.
         // but if the PHPCR backend is down for example, we want to alert the user
     }
     return $collection;
 }
 /**
  * {@inheritdoc}
  */
 public function getRouteCollection()
 {
     static $i18nCollection;
     if ($i18nCollection instanceof RouteCollection === false) {
         if (null === $this->collection) {
             $this->collection = $this->container->get('routing.loader')->load($this->resource, $this->options['resource_type']);
         }
         $i18nCollection = new RouteCollection();
         foreach ($this->collection->getResources() as $resource) {
             $i18nCollection->addResource($resource);
         }
         foreach ($this->collection->all() as $name => $route) {
             //do not add i18n routing prefix
             if ($this->shouldExcludeRoute($name, $route)) {
                 $i18nCollection->add($name, $route);
                 continue;
             }
             //add i18n routing prefix
             foreach ($this->generateI18nPatterns($name, $route) as $pattern => $locales) {
                 foreach ($locales as $locale) {
                     $localeRoute = clone $route;
                     $localeRoute->setPath($pattern);
                     $localeRoute->setDefault('_locale', $locale);
                     $i18nCollection->add($locale . self::ROUTING_PREFIX . $name, $localeRoute);
                 }
             }
         }
     }
     return $i18nCollection;
 }