本文整理汇总了PHP中Symfony\Component\Routing\RouteCollection类的典型用法代码示例。如果您正苦于以下问题:PHP RouteCollection类的具体用法?PHP RouteCollection怎么用?PHP RouteCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RouteCollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
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);
}
示例2: testOnAlterRoutes
/**
* 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();
}
示例3: filter
/**
* {@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') . '"');
}
示例4: run
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);
}
}
示例5: testSubscribing
/**
* 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();
}
示例6: alterRoutes
/**
* {@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);
}
}
示例7: alterRoutes
/**
* {@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);
}
}
}
示例8: getRouteCollectionForRequest
/**
* @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;
}
示例9: load
/**
* @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;
}
示例10: testMatch
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'));
}
示例11: testSchemeRedirect
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'));
}
示例12: testMatch
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'));
}
示例13: alterRoutes
/**
* {@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);
}
}
示例14: addRoute
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));
}
示例15: load
/**
* {@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;
}