getRouteCollection() public method

public getRouteCollection ( )
 private function collectCrudRoutes()
 {
     /** @var $collection \Symfony\Component\Routing\RouteCollection */
     $collection = $this->router->getRouteCollection();
     $allRoutes = $collection->all();
     /** @var $route \Symfony\Component\Routing\Route */
     foreach ($allRoutes as $routeName => $route) {
         $defaults = $route->getDefaults();
         if (!isset($defaults[self::TAG_CRUD])) {
             continue;
         }
         if (!isset($defaults['_controller'])) {
             throw new GeneralException(sprintf('Route %s doesn\'t contain \'_controller\' argument.', $routeName));
         }
         $routeNameParts = $this->explodeRouteNameParts($defaults['_controller']);
         $crudRoute = new CrudRoute();
         $crudRoute->setRouteName($routeName);
         $crudRoute->setCrudName($defaults[self::TAG_CRUD]);
         $crudRoute->setControllerFullName($routeNameParts[0]);
         $crudRoute->setBundleName($routeNameParts[1] . $routeNameParts[2]);
         //TODO: check long namespaces
         $crudRoute->setControllerName($routeNameParts[3]);
         $crudRoute->setActionName($routeNameParts[4]);
         $this->crudRoutes[$crudRoute->getControllerFullName()] = $crudRoute;
     }
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (!$this->installed) {
         return;
     }
     $request = $event->getRequest();
     if ($request->attributes->has('_controller') || $event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
         return;
     }
     $slugUrl = $request->getPathInfo();
     if ($slugUrl !== '/') {
         $slugUrl = rtrim($slugUrl, '/');
     }
     /** @var EntityManager $em */
     $em = $this->registry->getManagerForClass('OroB2BRedirectBundle:Slug');
     $slug = $em->getRepository('OroB2BRedirectBundle:Slug')->findOneBy(['url' => $slugUrl]);
     if ($slug) {
         $routeName = $slug->getRouteName();
         $controller = $this->router->getRouteCollection()->get($routeName)->getDefault('_controller');
         $parameters = [];
         $parameters['_route'] = $routeName;
         $parameters['_controller'] = $controller;
         $redirectRouteParameters = $slug->getRouteParameters();
         $parameters = array_merge($parameters, $redirectRouteParameters);
         $parameters['_route_params'] = $redirectRouteParameters;
         $request->attributes->add($parameters);
     }
 }
示例#3
0
 /**
  * @return \Symfony\Component\Routing\RouteCollection
  */
 public function getRouteCollection()
 {
     if (null !== $this->parent) {
         return $this->parent->getRouteCollection();
     }
     return parent::getRouteCollection();
 }
示例#4
0
 /**
  * Check request to decide if user has access to specific route
  *
  * @param GetResponseEvent $event
  * @throws AccessDeniedException
  * @throws InvalidRouteException
  * @throws UserNotFoundException
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $routeName = $event->getRequest()->get("_route");
     if (strpos($routeName, "app_default_") === 0) {
         throw new InvalidRouteException();
     }
     $routeCollection = $this->router->getRouteCollection();
     $route = $routeCollection->get($routeName);
     if ($route instanceof Route) {
         //Check if need to validate route
         //Sometime we want to allow access without validation: index page, login page
         $accessValidation = $route->getOption('access_validation');
         if ($accessValidation === false) {
             return;
         }
         //Validate current user access to route
         $this->authentication->setCurrentUser($this->request->get("token"));
         $user = $this->authentication->getCurrentUser();
         if (!$user instanceof User) {
             throw new UserNotFoundException();
         }
         $access = $this->accessService->checkPermissions($user, $routeName);
         if ($access === false) {
             throw new AccessDeniedException($user, $routeName);
         }
     }
 }
示例#5
0
 protected function generateDistantUrl($routeName, $parameters = [])
 {
     $url = $this->router->generate($routeName, $parameters, UrlGeneratorInterface::ABSOLUTE_PATH);
     //if (strpos($url, '/app_dev.php') === 0) {
     //    $url = '/app.php' . substr($url, 12);
     //}
     $url = 'http://' . $this->router->getRouteCollection()->get($routeName)->getDefault('_http_host') . $url;
     // TODO: manage SSL mode (HTTP/HTTPS), host by host
     return $url;
 }
 public function buildForForward(Request $request)
 {
     $currentRoute = $this->router->getRouteCollection()->get($request->attributes->get('_route'));
     $forwardRoute = $this->router->getRouteCollection()->get($currentRoute->getOption('forward_http_route'));
     $rmqClientConnection = $currentRoute->getOption('forward_rmq_producer');
     // Localhost case
     if ($forwardRoute->getDefault('_http_host') === $request->getHttpHost()) {
         $this->logger->info("InternalForwarder built for forward: Localhost forwarder.", ['host' => $request->getHttpHost()]);
         return $this->container->get('prestashop.public_writer.protocol.internal_forwarder.localhost');
     }
     // Error case: localhost case was not matching, but there is no other forwarder available.
     $this->logger->error("InternalForwarder built for forward: NO forwarder found to reach distant host.", ['host' => $request->getHttpHost()]);
     throw new \ErrorException("InternalForwarder building for forward: NO forwarder found to reach distant host: " . $request->getHttpHost());
 }
示例#7
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'));
 }
 /**
  * Get label
  *
  * @param $path
  * @param $parent
  * @param $name
  *
  * @return string
  */
 private function getLabel($path, $parent, $name)
 {
     $route = $this->router->getRouteCollection()->get($name);
     // get label through settings
     $label = $route->getDefault('breadcrumbs_label');
     if (empty($label)) {
         // get label through path
         $compiledRoute = $route->compile();
         $vars = $compiledRoute->getVariables();
         if (empty($vars)) {
             $label = substr($path, strlen($parent));
         } elseif (preg_match($compiledRoute->getRegex(), $path, $match)) {
             $label = $match[end($vars)];
         }
         $label = trim(preg_replace('[\\W|_]', ' ', $label));
         if (is_numeric($label)) {
             $label = null;
         }
     }
     if (empty($label)) {
         // get label through route name
         $label = 'breadcrumbs.' . $name;
         return $label;
     }
     return $label;
 }
示例#9
0
文件: Permission.php 项目: ephp/acl
 public function onKernelRequest(FilterControllerEvent $event)
 {
     $this->event = $event;
     $this->request = $event->getRequest();
     $rc = $this->router->getRouteCollection();
     /* @var $rc \Symfony\Component\Routing\RouteCollection */
     $route = $rc->get($this->request->get('_route'));
     if (!$route) {
         return false;
     }
     $acl = $route->getOption('ACL');
     try {
         // Verifico che sia stata richiesta la memorizzazione delle statistiche
         if ($acl && is_array($acl)) {
             if (!is_object($this->user)) {
                 throw new \Exception('User not logged');
             }
             // Opzioni default in caso di assenza
             $options = array_merge(array('in_role' => array(), 'out_role' => array()), $acl);
             // Trasformo i parametri in un array
             if (!is_array($options['in_role'])) {
                 $options['in_role'] = array($options['in_role']);
             }
             if (!is_array($options['out_role'])) {
                 $options['out_role'] = array($options['out_role']);
             }
             // Verifico che l'utente abbia il ruolo necessario per visualizzare la pagina
             $test_in = count($options['in_role']) == 0;
             foreach ($options['in_role'] as $role) {
                 $test_in |= $this->user->hasRole($role);
             }
             if (!$test_in) {
                 throw new \Exception("User doesn't have permission");
             }
             $test_out = true;
             foreach ($options['out_role'] as $role) {
                 $test_out &= !$this->user->hasRole($role);
             }
             if (!$test_out) {
                 throw new \Exception("User doesn't have permission");
             }
         }
     } catch (\Exception $e) {
         throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException($e->getMessage());
     }
 }
示例#10
0
 public function getRouteCollection()
 {
     $collection = parent::getRouteCollection();
     // Remove any page controller routes
     if (!$this->stored) {
         $this->storeRoutes($collection);
     }
     return $collection;
 }
示例#11
0
 /**
  * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
  * @expectedExceptionMessage  A string value must be composed of strings and/or numbers,but found parameter "object" of type object inside string value "/%object%".
  */
 public function testExceptionOnNonStringParameter()
 {
     $routes = new RouteCollection();
     $routes->add('foo', new Route('/%object%'));
     $sc = $this->getServiceContainer($routes);
     $sc->expects($this->at(1))->method('hasParameter')->with('object')->will($this->returnValue(true));
     $sc->expects($this->at(2))->method('getParameter')->with('object')->will($this->returnValue(new \stdClass()));
     $router = new Router($sc, 'foo');
     $router->getRouteCollection()->get('foo');
 }
示例#12
0
 /**
  * @param GetResponseEvent $event
  *
  * @throws RpcException
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $requestType = $request->headers->get('Content-Type');
     $responseType = $request->headers->get('Accept');
     if (!$this->factory->validate($requestType) or !$this->factory->validate($responseType)) {
         return;
     }
     $rpcRequest = $this->factory->createFrom($request);
     $rpcRoute = $this->getRouteName($rpcRequest);
     $route = $this->router->getRouteCollection()->get($rpcRoute);
     if (!$route) {
         $message = sprintf('Route %s not found', $rpcRoute);
         throw new RpcException($message);
     }
     $controller = $route->getDefault('_controller');
     $request->attributes->set('_controller', $controller);
     $request->attributes->set('_route', $rpcRoute);
     $request->attributes->set('rpcRequest', $rpcRequest);
 }
 /**
  * {@inheritdoc}
  */
 public function getRouteCollection()
 {
     $collection = parent::getRouteCollection();
     $routes = $collection->all();
     $newCollection = new RouteCollection();
     $routes = $this->sortRoutes($routes);
     foreach ($routes as $name => $route) {
         $newCollection->add($name, $route);
     }
     return $newCollection;
 }
示例#14
0
 /**
  * @param array         $locales
  *
  * @return bool
  * @throws \Symfony\Component\Filesystem\Exception\IOException
  * @throws \RuntimeException
  */
 public function dumpTranslations($locales = [])
 {
     if (empty($locales)) {
         $locales[] = $this->defaultLocale;
     }
     $targetPattern = realpath($this->kernelRootDir . '/../web') . $this->router->getRouteCollection()->get($this->jsTranslationRoute)->getPath();
     foreach ($locales as $locale) {
         $target = strtr($targetPattern, array('{_locale}' => $locale));
         $this->logger->info(sprintf('<comment>%s</comment> <info>[file+]</info> %s', date('H:i:s'), basename($target)));
         $content = $this->translationController->renderJsTranslationContent($this->translationDomains, $locale);
         $dirName = dirname($target);
         if (!is_dir($dirName) && true !== @mkdir($dirName, 0777, true)) {
             throw new IOException(sprintf('Failed to create %s', $dirName));
         }
         if (false === @file_put_contents($target, $content)) {
             throw new \RuntimeException('Unable to write file ' . $target);
         }
     }
     return true;
 }
示例#15
0
 /**
  * {@inheritdoc}
  */
 public function getRouteCollection()
 {
     $key = 'route_collection';
     if (null === $this->collection) {
         if ($this->cache->hasItem($key)) {
             $collection = $this->cache->getItem($key)->get();
             if ($collection !== null) {
                 $this->collection = $collection;
                 return $this->collection;
             }
         }
         $this->collection = parent::getRouteCollection();
         $item = $this->cache->getItem($key);
         $item->set($this->collection)->expiresAfter(self::CACHE_LIFETIME);
     }
     return $this->collection;
 }
示例#16
0
 /**
  * return the mongodb representation from a php value
  *
  * @param string $value value of reference as URI
  *
  * @return array
  */
 public function convertToDatabaseValue($value)
 {
     if (empty($this->router)) {
         throw new \RuntimeException('no router injected into ' . __CLASS__);
     }
     if (empty($value)) {
         throw new \RuntimeException('Empty URL in ' . __CLASS__);
     }
     $path = $this->getPathFromUrl($value);
     foreach ($this->router->getRouteCollection()->all() as $route) {
         list($collection, $id) = $this->getDataFromRoute($route, $path);
         if (!empty($collection) && !empty($id)) {
             return \MongoDBRef::create($collection, $id);
         }
     }
     if (empty($collection) || empty($id)) {
         throw new \RuntimeException(sprintf('Could not read URL %s', $value));
     }
 }
 /**
  * @param Router $router
  * @param string $routeNameFromMappingFile
  *
  * @return mixed
  *
  * @throws \RuntimeException
  */
 private function getUrlPattern(Router $router, $routeNameFromMappingFile)
 {
     if (!empty($routeNameFromMappingFile)) {
         try {
             $route = $router->getRouteCollection()->get($routeNameFromMappingFile);
             if (empty($route)) {
                 throw new Exception();
             }
         } catch (\Exception $e) {
             throw new \RuntimeException(\sprintf('Route \'%s\' has not been defined as a Symfony route.', $routeNameFromMappingFile));
         }
         \preg_match_all('/{(.*?)}/', $route->getPath(), $matches);
         $pattern = [];
         if (!empty($matches)) {
             $pattern = \array_combine($matches[1], $matches[0]);
         }
         return \urldecode($router->generate($routeNameFromMappingFile, $pattern, true));
     }
     return (string) $routeNameFromMappingFile;
 }
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     foreach ($this->fc_form->getFieldsRecursively() as $fc_field) {
         $this->addField($builder, $fc_field);
     }
     $action = $this->fc_form->getAction();
     if ($this->router->getRouteCollection()->get($action) !== null) {
         $action = $this->router->generate($action);
     }
     if ($this->fc_form->getIsAjax()) {
         if (empty($action)) {
             $action = $this->router->generate('fc_from_ajax_handler', array('alias' => $this->fc_form->getAlias()));
         }
     }
     $builder->add('submit', 'submit', array('label' => $this->fc_form->getButton() ? $this->fc_form->getButton() : 'fc.label.button'))->add('_template', 'hidden')->setMethod($this->fc_form->getMethod())->setAction($action);
     $save_handler = new SaveRequestHandler($this->field_chain, $this->fc_form);
     $builder->addEventListener(FormEvents::POST_SUBMIT, array($save_handler, 'handle'));
     foreach ($this->fc_form->getListeners() as $fc_listener) {
         $this->addListener($builder, $fc_listener);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function getOriginalRouteCollection()
 {
     return parent::getRouteCollection();
 }
示例#20
0
 /**
  * @dataProvider getNonStringValues
  */
 public function testDefaultValuesAsNonStrings($value)
 {
     $routes = new RouteCollection();
     $routes->add('foo', new Route('foo', array('foo' => $value), array('foo' => '\\d+')));
     $sc = $this->getServiceContainer($routes);
     $router = new Router($sc, 'foo');
     $route = $router->getRouteCollection()->get('foo');
     $this->assertSame($value, $route->getDefault('foo'));
 }
示例#21
0
文件: Generator.php 项目: ephp/stats
 public function onKernelRequest(GetResponseEvent $event)
 {
     $this->event = $event;
     $this->request = $event->getRequest();
     $rc = $this->router->getRouteCollection();
     /* @var $rc \Symfony\Component\Routing\RouteCollection */
     $route = $rc->get($this->request->get('_route'));
     if (!$route) {
         return false;
     }
     $stats = $route->getOption('stats');
     // Verifico che sia stata richiesta la memorizzazione delle statistiche
     if ($stats && is_array($stats)) {
         // Opzioni default in caso di assenza
         $options = array_merge(array('area' => array('default')), $stats);
         // trasformo area in un array
         if (!is_array($options['area'])) {
             $options['area'] = array($options['area']);
         }
         // Verifico che non siano stati richieste aree "dinamiche" dipendenti da un parametro della route
         $route = $this->request->get('_route');
         $route_params = $this->request->get('_route_params');
         if (isset($options['area_from'])) {
             // L'area dinamica deve essere in un array, potrebbe avere anche
             // i parametri from e chars necessari a prendere una sotto stringa
             // del parametro richiesto
             if (!is_array($options['area_from'])) {
                 $options['area_from'] = array('param' => $options['area_from']);
             }
             // Se il parametro esiste, vado avanti e configuro la nuova area
             if (isset($route_params[$options['area_from']['param']])) {
                 $area = $route_params[$options['area_from']['param']];
                 if (isset($options['area_from']['from']) && isset($options['area_from']['chars'])) {
                     $area = substr($area, $options['area_from']['from'], $options['area_from']['chars']);
                 }
                 // Se c'è solo l'area default l'unica area che verrà memorizzata
                 // sarà quella dinamica, altrimenti aggiungo all'array delle aree
                 if (count($options['area']) == 1 && $options['area'][0] == 'default') {
                     $options['area'][0] = $area;
                 } else {
                     $options['area'][] = $area;
                 }
             }
         }
         if (isset($options['entity'])) {
             // Controllo e parametrizzo l'entity
             if (!is_array($options['entity'])) {
                 $options['entity'] = array('entity' => $options['entity'], 'prefix' => $options['entity'], 'column' => 'id', 'param' => 'id', 'output' => 'id');
             } else {
                 $options['entity'] = array_merge(array('entity' => $options['entity']['entity'], 'prefix' => $options['entity']['entity'], 'column' => 'id', 'param' => 'id', 'output' => 'id'), $options['entity']);
             }
             // Se il parametro esiste, vado avanti e configuro la nuova area
             if (isset($route_params[$options['entity']['param']])) {
                 $param = $route_params[$options['entity']['param']];
                 $_entity = $this->em->getRepository($options['entity']['entity']);
                 $entity = $_entity->findOneBy(array($options['entity']['column'] => $param));
                 $fx = \Doctrine\Common\Util\Inflector::camelize("get_" . $options['entity']['output']);
                 $area = $options['entity']['prefix'] . '-' . $entity->{$fx}();
                 // Se c'è solo l'area default l'unica area che verrà memorizzata
                 // sarà quella dinamica, altrimenti aggiungo all'array delle aree
                 if (count($options['area']) == 1 && $options['area'][0] == 'default') {
                     $options['area'][0] = $area;
                 } else {
                     $options['area'][] = $area;
                 }
             }
         }
         $_url = $this->router->generate($route, $route_params);
         $test = preg_match('/.(php|jsp|asp|aspx|html|jpg|jpeg|gif|png)$/', $_url);
         if ($test == 0) {
             try {
                 $this->em->beginTransaction();
                 $visita = new \Ephp\StatsBundle\Entity\Visita();
                 $visita->setUrl($_url);
                 $visita->setRoute($route);
                 $visita->setRouteParams($route_params);
                 $visita->setSession($this->request->getSession()->getId());
                 $visita->setIp($this->request->getClientIp());
                 $visita->setUserAgent($this->request->server->get('HTTP_USER_AGENT'));
                 $locale = $this->request->getLanguages();
                 $visita->setLocale(array_shift($locale));
                 foreach ($options['area'] as $_area) {
                     $area = $this->em->getRepository('EphpStatsBundle:Area')->findOneBy(array('area' => $_area));
                     if (!$area) {
                         $area = new \Ephp\StatsBundle\Entity\Area();
                         $area->setArea($_area);
                         $this->em->persist($area);
                         $this->em->flush();
                     }
                     $visita->addAree($area);
                 }
                 $this->em->persist($visita);
                 $this->em->flush();
                 $this->em->commit();
             } catch (\Exception $e) {
                 \Ephp\UtilityBundle\Utility\Debug::vd($e);
                 $this->em->rollback();
                 throw $e;
             }
         }
     }
 }
示例#22
0
 public function getRouteCollection()
 {
     $collection = parent::getRouteCollection();
     return $this->container->get($this->i18nLoaderId)->load($collection);
 }