public function testGetRouteCollectionWithRoutes() { $routes = new RouteCollection(); $controllers = new ControllerCollection($routes); $controllers->add(new Controller(new Route('/foo'))); $controllers->add(new Controller(new Route('/bar'))); $this->assertEquals(0, count($routes->all())); $controllers->flush(); $this->assertEquals(2, count($routes->all())); }
public function addCollection(RouteCollection $collection) { foreach ($collection->all() as $name => $route) { $this->add($name, $route); } // remove all the routes so that we have an empty collection when calling parent method // and we are not re-adding the routes again $collection->remove(array_keys($collection->all())); // call parent method with empty collection to merge the collection's resources parent::addCollection($collection); }
/** * {@inheritdoc} */ public function match($theClass, $theMethod) { $routes = $this->routes->all(); foreach ($routes as $name => $route) { $controller = $route->getDefault('_controller'); if (false !== strpos($controller, "::")) { list($class, $method) = explode('::', $controller, 2); if ($class === $theClass && $method === $theMethod) { return array($name, $route); return array('name' => $name, 'route' => $route); } } } throw new ResourceNotFoundException(); }
/** * {@inheritdoc} */ public function filter(RouteCollection $collection, Request $request) { $method = $request->getMethod(); $all_supported_methods = []; foreach ($collection->all() as $name => $route) { $supported_methods = $route->getMethods(); // A route not restricted to specific methods allows any method. If this // is the case, we'll also have at least one route left in the collection, // hence we don't need to calculate the set of all supported methods. if (empty($supported_methods)) { continue; } // If the GET method is allowed we also need to allow the HEAD method // since HEAD is a GET method that doesn't return the body. if (in_array('GET', $supported_methods, TRUE)) { $supported_methods[] = 'HEAD'; } if (!in_array($method, $supported_methods, TRUE)) { $all_supported_methods = array_merge($supported_methods, $all_supported_methods); $collection->remove($name); } } if (count($collection)) { return $collection; } throw new MethodNotAllowedException(array_unique($all_supported_methods)); }
/** * {@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(); } }
/** * {@inheritdoc} */ protected function describeRouteCollection(RouteCollection $routes, array $options = array()) { $showControllers = isset($options['show_controllers']) && $options['show_controllers']; $headers = array('Name', 'Method', 'Scheme', 'Host', 'Path'); $table = new TableHelper(); $table->setLayout(TableHelper::LAYOUT_COMPACT); $table->setHeaders($showControllers ? array_merge($headers, array('Controller')) : $headers); 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; } $table->addRow($row); } $this->writeText($this->formatSection('router', 'Current routes')."\n", $options); $this->renderTable($table, !(isset($options['raw_output']) && $options['raw_output'])); }
/** * {@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; }
/** * {@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); } }
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; }
/** * Tests \Drupal\Core\Access\AccessManager::check(). */ public function testCheck() { $route_matches = []; // Construct route match objects. foreach ($this->routeCollection->all() as $route_name => $route) { $route_matches[$route_name] = new RouteMatch($route_name, $route, [], []); } // Check route access without any access checker defined yet. foreach ($route_matches as $route_match) { $this->assertEquals(FALSE, $this->accessManager->check($route_match, $this->account)); $this->assertEquals(AccessResult::neutral(), $this->accessManager->check($route_match, $this->account, NULL, TRUE)); } $this->setupAccessChecker(); // An access checker got setup, but the routes haven't been setup using // setChecks. foreach ($route_matches as $route_match) { $this->assertEquals(FALSE, $this->accessManager->check($route_match, $this->account)); $this->assertEquals(AccessResult::neutral(), $this->accessManager->check($route_match, $this->account, NULL, TRUE)); } // Now applicable access checks have been saved on each route object. $this->checkProvider->setChecks($this->routeCollection); $this->setupAccessArgumentsResolverFactory(); $this->assertEquals(FALSE, $this->accessManager->check($route_matches['test_route_1'], $this->account)); $this->assertEquals(TRUE, $this->accessManager->check($route_matches['test_route_2'], $this->account)); $this->assertEquals(FALSE, $this->accessManager->check($route_matches['test_route_3'], $this->account)); $this->assertEquals(TRUE, $this->accessManager->check($route_matches['test_route_4'], $this->account)); $this->assertEquals(AccessResult::neutral(), $this->accessManager->check($route_matches['test_route_1'], $this->account, NULL, TRUE)); $this->assertEquals(AccessResult::allowed(), $this->accessManager->check($route_matches['test_route_2'], $this->account, NULL, TRUE)); $this->assertEquals(AccessResult::forbidden(), $this->accessManager->check($route_matches['test_route_3'], $this->account, NULL, TRUE)); $this->assertEquals(AccessResult::allowed(), $this->accessManager->check($route_matches['test_route_4'], $this->account, NULL, TRUE)); }
/** * {@inheritdoc} */ protected function describeRouteCollection(RouteCollection $routes, array $options = array()) { $data = array(); foreach ($routes->all() as $name => $route) { $data[$name] = $this->getRouteData($route); } $this->writeData($data, $options); }
function dump() { $stamp = new \DateTime(); $time = $stamp->format("r"); $result = <<<EOF <?php /** * * Route Dump * This is a generated file , do not edit * <timestamp>{$time}</timestamp> */ use Symfony\\Component\\Routing\\RouteCollection; use Symfony\\Component\\Routing\\Route; \$routeCollection = new RouteCollection(); EOF; $fields = array("Defaults", "Host", "Methods", "Options", "Path", "Requirements", "Schemes"); foreach ($this->routeCollection->all() as $name => $route) { $result .= <<<EOF /** * * route named {$name} * */ EOF; $route_name = "\$route" . preg_replace("/!\\W/im", "_", $name); $result .= "\n{$route_name} = new Route(" . var_export($route->getPath(), true) . ");"; /* @var $route Route */ foreach ($fields as $field) { if ($route->{"get{$field}"}() != null) { $result .= "\n{$route_name}->set{$field}(" . var_export($route->{"get{$field}"}(), true) . ");"; } } // echo $name; //print_r($route); $result .= "\n\$routeCollection->add('{$name}',{$route_name});"; } $result .= "\nreturn \$routeCollection;"; return $result; }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { foreach ($collection->all() as $route) { if (strpos($route->getPath(), '/admin') === 0 && !$route->hasOption('_admin_route')) { $route->setOption('_admin_route', TRUE); } } }
/** * Returns all routes in this collection. * * @return Route[] An array of routes */ public function all() { $routeCollectionAll = new RouteCollection(); foreach ($this->routeCollections as $routeCollection) { $routeCollectionAll->addCollection($routeCollection); } return $routeCollectionAll->all(); }
/** * Get the current route name. * * @return string|null */ public function currentRouteName() { foreach ($this->routes->all() as $name => $route) { if ($route === $this->currentRoute) { return $name; } } }
/** * Adds a route collection to the current set of routes (at the end of the current set). * * @param RouteCollection $collection A RouteCollection instance * @param string $prefix An optional prefix to add before each pattern of the route collection */ public function addCollection(RouteCollection $collection, $prefix = '') { $collection->addPrefix($prefix); foreach ($collection->getResources() as $resource) { $this->addResource($resource); } $this->routes = array_merge($this->routes, $collection->all()); }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { foreach ($collection->all() as $rn => $route) { // Hide taxonomy pages from unprivileged users. if (strpos($route->getPath(), '/taxonomy/term') === 0) { $route->setRequirement('_role', 'administrator'); } } }
private function verifyCollection(RouteCollection $collection) { $routes = $collection->all(); $this->assertCount(3, $routes, 'Three routes are loaded'); $this->assertContainsOnly('Symfony\\Component\\Routing\\Route', $routes); for ($i = 1; $i <= 3; ++$i) { $this->assertSame('/route/' . $i, $routes['route' . $i]->getPath()); } }
public static function dump(RouteCollection $collection) { $content = '<?php use Symfony\\Component\\Routing\\Route; use Symfony\\Component\\Routing\\RouteCollection; $r = new RouteCollection();' . PHP_EOL; foreach ($collection->all() as $name => $route) { $content .= sprintf('$z = new Route(""); $z->unserialize(\'%s\'); $r->add("%s", $z);', $route->serialize(), $name) . PHP_EOL; } $content .= 'return $r;'; return $content; }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { if ($this->configFactory->get('support_ticket.settings')->get('use_admin_theme')) { foreach ($collection->all() as $route) { if ($route->hasOption('_support_ticket_operation_route')) { $route->setOption('_admin_route', TRUE); } } } }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { $special_variables = array('system_path', '_legacy', '_raw_variables', RouteObjectInterface::ROUTE_OBJECT, RouteObjectInterface::ROUTE_NAME, '_content', '_controller', '_form'); foreach ($collection->all() as $name => $route) { if ($not_allowed_variables = array_intersect($route->compile()->getVariables(), $special_variables)) { $reserved = implode(', ', $not_allowed_variables); trigger_error(sprintf('Route %s uses reserved variable names: %s', $name, $reserved), E_USER_WARNING); } } }
/** * Returns routes sorted by custom HTTP methods first. * * @return array */ public function all() { $routes = parent::all(); $customMethodRoutes = array(); foreach ($routes as $routeName => $route) { if (!preg_match('/(_|^)(get|post|put|delete|patch|head|options)_/', $routeName)) { $customMethodRoutes[$routeName] = $route; unset($routes[$routeName]); } } return $customMethodRoutes + $routes; }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { if ($collection->get('tmgmt.admin_tmgmt')) { $route = $collection->get('tmgmt.admin_tmgmt'); $route->addRequirements(['_permission' => $collection->get('tmgmt.admin_tmgmt')->getRequirement('_permission') . '+administer translation tasks+provide translation services']); } foreach ($collection->all() as $route) { if (strpos($route->getPath(), '/translate') === 0 && $this->configFactory->get('tmgmt_local.settings')->get('use_admin_theme') || strpos($route->getPath(), '/manage-translate') === 0) { $route->setOption('_admin_route', TRUE); } } }
/** * {@inheritdoc} */ protected function describeRouteCollection(RouteCollection $routes, array $options = array()) { $first = true; foreach ($routes->all() as $name => $route) { if ($first) { $first = false; } else { $this->write("\n\n"); } $this->describeRoute($route, array('name' => $name)); } $this->write("\n"); }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { $special_variables = array('system_path', '_maintenance', '_legacy', '_authentication_provider', '_raw_variables', RouteObjectInterface::ROUTE_OBJECT, RouteObjectInterface::ROUTE_NAME, '_content', '_form'); foreach ($collection->all() as $route) { if ($not_allowed_variables = array_intersect($route->compile()->getVariables(), $special_variables)) { $placeholders = array('@variables' => implode(', ', $not_allowed_variables)); drupal_set_message(String::format('The following variables are reserved names by drupal: @variables', $placeholders)); watchdog('error', 'The following variables are reserved names by drupal: @variables', $placeholders); return FALSE; } } return TRUE; }
public function load(RouteCollection $collection) { $i18nCollection = new RouteCollection(); foreach ($collection->getResources() as $resource) { $i18nCollection->addResource($resource); } $this->patternGenerationStrategy->addResources($i18nCollection); $existedHomepage = []; foreach ($collection->all() as $name => $route) { if ($this->routeExclusionStrategy->shouldExcludeRoute($name, $route)) { $i18nCollection->add($name, $route); continue; } $patters = $this->patternGenerationStrategy->generateI18nPatterns($name, $route); foreach ($patters as $pattern => $hostLocales) { // 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. foreach ($hostLocales as $host => $locales) { if (count($locales) > 1) { $catchMultipleRoute = clone $route; $catchMultipleRoute->setPath($pattern); $catchMultipleRoute->setHost($host); $catchMultipleRoute->setRequirement('_locale', implode('|', $locales)); $catchMultipleRoute->setOption('original_name', $name)->setOption('locales', $locales); $i18nCollection->add(implode('_', $locales) . I18nLoader::ROUTING_PREFIX . $name, $catchMultipleRoute); } elseif (count($locales) == 1) { $catchRoute = clone $route; $catchRoute->setPath($pattern); $catchRoute->setHost($host); $catchRoute->setDefault('_locale', $locales[0]); $catchRoute->setRequirement('_locale', $locales[0]); $catchRoute->setOption('original_name', $name)->setOption('locales', $locales); $i18nCollection->add(implode('_', $locales) . I18nLoader::ROUTING_PREFIX . $name, $catchRoute); } if ($pattern == '/') { $existedHomepage[] = $host; } } } } $offices = $this->entityManager->getRepository('OctavaMuiBundle:Office')->getRoutingOffices(); foreach ($offices as $locale => $office) { if ($office->getIncludeLangInUrl() && !in_array($office->getHost(), $existedHomepage)) { $redirectRoute = new Route('/', ['_controller' => 'FrameworkBundle:Redirect:urlRedirect', 'path' => '/' . $locale . '/', 'permanent' => true]); $redirectRoute->setHost($office->getHost()); $i18nCollection->add($locale . I18nLoader::ROUTING_PREFIX . 'redirect_to_root', $redirectRoute); } } return $i18nCollection; }
/** * Dumps a set of routes to the router table in the database. * * Available options: * - provider: The route grouping that is being dumped. All existing * routes with this provider will be deleted on dump. * - base_class: The base class name. * * @param array $options * An array of options. */ public function dump(array $options = array()) { // Convert all of the routes into database records. // Accumulate the menu masks on top of any we found before. $masks = array_flip($this->state->get('routing.menu_masks.' . $this->tableName, array())); // Delete any old records first, then insert the new ones. That avoids // stale data. The transaction makes it atomic to avoid unstable router // states due to random failures. $transaction = $this->connection->startTransaction(); try { // We don't use truncate, because it is not guaranteed to be transaction // safe. try { $this->connection->delete($this->tableName)->execute(); } catch (\Exception $e) { $this->ensureTableExists(); } // Split the routes into chunks to avoid big INSERT queries. $route_chunks = array_chunk($this->routes->all(), 50, TRUE); foreach ($route_chunks as $routes) { $insert = $this->connection->insert($this->tableName)->fields(array('name', 'fit', 'path', 'pattern_outline', 'number_parts', 'route')); $names = array(); foreach ($routes as $name => $route) { /** @var \Symfony\Component\Routing\Route $route */ $route->setOption('compiler_class', '\\Drupal\\Core\\Routing\\RouteCompiler'); /** @var \Drupal\Core\Routing\CompiledRoute $compiled */ $compiled = $route->compile(); // The fit value is a binary number which has 1 at every fixed path // position and 0 where there is a wildcard. We keep track of all such // patterns that exist so that we can minimize the number of path // patterns we need to check in the RouteProvider. $masks[$compiled->getFit()] = 1; $names[] = $name; $values = array('name' => $name, 'fit' => $compiled->getFit(), 'path' => $route->getPath(), 'pattern_outline' => $compiled->getPatternOutline(), 'number_parts' => $compiled->getNumParts(), 'route' => serialize($route)); $insert->values($values); } // Insert all new routes. $insert->execute(); } } catch (\Exception $e) { $transaction->rollback(); watchdog_exception('Routing', $e); throw $e; } // Sort the masks so they are in order of descending fit. $masks = array_keys($masks); rsort($masks); $this->state->set('routing.menu_masks.' . $this->tableName, $masks); $this->routes = NULL; }
/** * Iterates over $restRouteCollection, and returns the corresponding RouteCollection of OPTIONS REST routes * * @param RouteCollection $restRouteCollection * @return RouteCollection */ public function mapCollection(RouteCollection $restRouteCollection) { $optionsRouteCollection = new RouteCollection(); foreach ($restRouteCollection->all() as $restRoute) { $optionsRouteName = $this->mapper->getOptionsRouteName($restRoute); $optionsRoute = $optionsRouteCollection->get($optionsRouteName); if ($optionsRoute === null) { $optionsRoute = $this->mapper->mapRoute($restRoute); } else { $optionsRoute = $this->mapper->mergeMethodsDefault($optionsRoute, $restRoute); } $optionsRouteCollection->add($optionsRouteName, $optionsRoute); } return $optionsRouteCollection; }
/** * {@inheritdoc} */ public function filter(RouteCollection $collection, Request $request) { $filter_ids = []; foreach ($collection->all() as $route) { $filter_ids = array_merge($filter_ids, $route->getOption('_route_filters') ?: []); } $filter_ids = array_unique($filter_ids); if (isset($filter_ids)) { foreach ($filter_ids as $filter_id) { if ($filter = $this->container->get($filter_id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) { $collection = $filter->filter($collection, $request); } } } return $collection; }
/** * Returns routes sorted by custom HTTP methods first. * * @return array */ public function all() { $regex = '/ (_|^) (get|post|put|delete|patch|head|options|mkcol|propfind|proppatch|lock|unlock|move|copy|link|unlink)_ # allowed http methods /i'; $routes = parent::all(); $customMethodRoutes = []; foreach ($routes as $routeName => $route) { if (!preg_match($regex, $routeName)) { $customMethodRoutes[$routeName] = $route; unset($routes[$routeName]); } } return $customMethodRoutes + $routes; }