作者:keek
项目:api-ap
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);
}
作者:anyforsof
项目:csua_d
/**
* 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();
}
作者:aWEBoLab
项目:tax
/**
* {@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') . '"');
}
作者:ricardofioran
项目:cupcake
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);
}
}
作者:Greg-Bogg
项目:electric-de
/**
* 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();
}
作者:pulibrar
项目:reca
/**
* {@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);
}
}
作者:eloi
项目:botafoc.ca
/**
* {@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);
}
}
}
作者:mva
项目:RouterBundl
/**
* @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;
}
作者:hikmahtiar
项目:drafterbi
/**
* @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;
}
作者:nickaggarwa
项目:sample-symfony
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'));
}
作者:TuxCoffeeCorne
项目:tc
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'));
}
作者:notbrai
项目:symfon
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'));
}
作者:dropdo
项目:pla
/**
* {@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);
}
}
作者:jmcclel
项目:AvalancheImagineBundl
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));
}
作者:Mandarin-Medie
项目:MMCmfRoutingBundl
/**
* {@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;
}
作者:kleijnwe
项目:swagger-bundl
/**
* @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;
}
作者:renegar
项目:symfon
/**
* @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();
}
作者:usefulthin
项目:symfon
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'));
}
作者:rooste
项目:symfon
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;
}
作者:AntoineLemair
项目:JMSI18nRoutingBundl
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;
}