public function logVisitor(UserEvent $userEvent) { // call another method? dump($this->router->getRouteCollection()); dump($userEvent->getUserId()); die; }
/** * {@inheritdoc} */ public function warmUp($cacheDir) { $processedRoutes = array(); $routeCollection = $this->router->getRouteCollection(); foreach ($routeCollection->all() as $name => $route) { if (!isset($processedRoutes[$route->getPattern()])) { $processedRoutes[$route->getPattern()] = array('methods' => array(), 'names' => array()); } $processedRoutes[$route->getPattern()]['names'][] = $name; $requirements = $route->getRequirements(); if (isset($requirements['_method'])) { $methods = explode('|', $requirements['_method']); $processedRoutes[$route->getPattern()]['methods'] = array_merge($processedRoutes[$route->getPattern()]['methods'], $methods); } } $allowedMethods = array(); foreach ($processedRoutes as $processedRoute) { if (count($processedRoute['methods']) > 0) { foreach ($processedRoute['names'] as $name) { $allowedMethods[$name] = array_unique($processedRoute['methods']); } } } $this->cache->write(sprintf('<?php return %s;', var_export($allowedMethods, true)), $routeCollection->getResources()); }
/** * Dumps all translation files. * * @param string $targetDir Target directory. * @param boolean $symlink True if generate symlink * * @return null */ public function dump($targetDir = 'web', $symlink = false, $directory = null) { $route = $this->router->getRouteCollection()->get('bazinga_exposetranslation_js'); $directory = null === $directory ? $this->kernel->getRootDir() . '/../' : $directory; $requirements = $route->getRequirements(); $formats = explode('|', $requirements['_format']); $routeDefaults = $route->getDefaults(); $defaultFormat = $routeDefaults['_format']; $parts = array_filter(explode('/', $route->getPattern())); $this->filesystem->remove($directory . $targetDir . "/" . current($parts)); foreach ($this->getTranslationMessages() as $locale => $domains) { foreach ($domains as $domain => $messageList) { foreach ($formats as $format) { $content = $this->engine->render('BazingaExposeTranslationBundle::exposeTranslation.' . $format . '.twig', array('messages' => array($domain => $messageList), 'locale' => $locale, 'defaultDomains' => $domain)); $path[$format] = $directory . $targetDir . strtr($route->getPattern(), array('{domain_name}' => $domain, '{_locale}' => $locale, '{_format}' => $format)); $this->filesystem->mkdir(dirname($path[$format]), 0777); if (file_exists($path[$format])) { $this->filesystem->remove($path[$format]); } file_put_contents($path[$format], $content); } $targetFile = $directory . $targetDir; $targetFile .= strtr($route->getPattern(), array('{domain_name}' => $domain, '{_locale}' => $locale, '.{_format}' => '')); if (true === $symlink) { $this->filesystem->symlink($path[$defaultFormat], $targetFile); } else { $this->filesystem->copy($path[$defaultFormat], $targetFile); } } } }
public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); $routes = $this->router->getRouteCollection(); $route = $routes->get($request->attributes->get('_route')); if (!$route->getOption('requires_license')) { return; } if ('active' != $request->get('lic') && $this->kernel->getEnvironment() == 'prod') { // Checking for whitelisted users try { $user = $this->tokenStorage->getToken()->getUser(); $today = date('Y-m-d'); if ($user instanceof UserInterface) { $whitelist = $this->kernel->getContainer()->getParameter('license_whitelist'); foreach ($whitelist as $allowed) { if ($allowed['client_key'] == $user->getClientKey() && $today <= $allowed['valid_till']) { return; } } } } catch (\Exception $e) { // Do nothing } $url = $this->router->generate('atlassian_connect_unlicensed'); $response = new RedirectResponse($url); $event->setResponse($response); } }
/** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { $format = null; if (is_string($this->forceFormat)) { $format = $this->forceFormat; } else { $request = $event->getRequest(); if ($this->router instanceof I18nRouter) { $collection = $this->router->getOriginalRouteCollection(); } else { $collection = $this->router->getRouteCollection(); } $route = $collection->get($request->get('_route')); if (!empty($route)) { $defaultFormat = is_null($route->getDefault('_format')) ? 'html' : $route->getDefault('_format'); } else { $defaultFormat = 'html'; } $format = !is_null($request->attributes->get('_format')) ? $request->attributes->get('_format') : $defaultFormat; } if (!is_null($format)) { $serviceName = 'vsymfo_core.service.' . strtolower($format) . '_document'; if ($this->container->has($serviceName) && $this->container->get($serviceName) instanceof DocumentFactoryInterface) { $service = $this->container->get($serviceName); } else { $service = $this->container->get('vsymfo_core.service.txt_document'); } $doc = $service->createDocument(); $this->container->get('vsymfo_core.service.document')->setDefaultsToDocument($doc); $this->container->set($this->serviceName, $doc); } }
/** * @param array $documentation * * @return array */ public function create(array $documentation) { $apiDoc = new ApiDoc($documentation); if (array_key_exists('route', $documentation) === true) { $apiDoc->setRoute($this->router->getRouteCollection()->get($documentation['route'])); } return array(self::KEY_ANNOTATION => $apiDoc, self::KEY_RESOURCE => $documentation[self::KEY_RESOURCE]); }
/** * {@inheritdoc} */ public function redirectToResource(RequestConfiguration $configuration, ResourceInterface $resource) { $routes = $this->router->getRouteCollection(); $redirectRouteName = $configuration->getRedirectRoute(ResourceActions::SHOW); if (null === $routes->get($redirectRouteName)) { $redirectRouteName = $configuration->getRedirectRoute(ResourceActions::INDEX); } return $this->redirectToRoute($configuration, $redirectRouteName, $configuration->getRedirectParameters($resource)); }
/** * @param Request $request * @param ParamConverter $configuration * * @return bool * * @throws \LogicException * @throws NotFoundHttpException * @throws \Exception */ public function apply(Request $request, ParamConverter $configuration) { $classQuery = $configuration->getClass() . 'Query'; $classPeer = $configuration->getClass() . 'Peer'; $this->filters = array(); $this->exclude = array(); if (!class_exists($classQuery)) { throw new \Exception(sprintf('The %s Query class does not exist', $classQuery)); } $tableMap = $classPeer::getTableMap(); $pkColumns = $tableMap->getPrimaryKeyColumns(); if (count($pkColumns) == 1) { $this->pk = strtolower($pkColumns[0]->getName()); } $options = $configuration->getOptions(); // Check route options for converter options, if there are non provided. if (empty($options) && $request->attributes->has('_route') && $this->router && $configuration instanceof ParamConverter) { $converterOption = $this->router->getRouteCollection()->get($request->attributes->get('_route'))->getOption('propel_converter'); if (!empty($converterOption[$configuration->getName()])) { $options = $converterOption[$configuration->getName()]; } } if (isset($options['mapping'])) { // We use the mapping for calling findPk or filterBy foreach ($options['mapping'] as $routeParam => $column) { if ($request->attributes->has($routeParam)) { if ($this->pk === $column) { $this->pk = $routeParam; } else { $this->filters[$column] = $request->attributes->get($routeParam); } } } } else { $this->exclude = isset($options['exclude']) ? $options['exclude'] : array(); $this->filters = $request->attributes->all(); } $this->withs = isset($options['with']) ? is_array($options['with']) ? $options['with'] : array($options['with']) : array(); // find by Pk if (false === ($object = $this->findPk($classQuery, $request))) { // find by criteria if (false === ($object = $this->findOneBy($classQuery, $request))) { if ($configuration->isOptional()) { //we find nothing but the object is optional $object = null; } else { throw new \LogicException('Unable to guess how to get a Propel object from the request information.'); } } } if (null === $object && false === $configuration->isOptional()) { throw new NotFoundHttpException(sprintf('%s object not found.', $configuration->getClass())); } $request->attributes->set($configuration->getName(), $object); return true; }
/** * @param object $resource * * @return RedirectResponse */ public function redirectTo($resource) { $parameters = $this->config->getRedirectParameters($resource); $routes = $this->router->getRouteCollection(); $route = $this->config->getRedirectRoute('show'); if (!$routes->get($route)) { $route = $this->config->getRedirectRoute('index'); } return $this->redirectToRoute($route, $parameters); }
/** * @return string */ public function getApiViews() { $apiViews = []; $allRoutes = $this->router->getRouteCollection()->all(); foreach ($allRoutes as $route) { $routeOptions = $route->getOptions(); if (isset($routeOptions['api_view'])) { if (!in_array($routeOptions['api_view'], $apiViews)) { $apiViews[] = $routeOptions['api_view']; } } } return $apiViews; }
/** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); if ($this->router instanceof I18nRouter) { $collection = $this->router->getOriginalRouteCollection(); } else { $collection = $this->router->getRouteCollection(); } $route = $collection->get($request->get('_route')); if (!empty($route) && $route->hasOption('theme_group')) { $group = $route->getOption('theme_group'); $this->theme->setName($group . '_' . $this->container->getParameter('vsymfo_core.theme_' . $group)); } }
/** * @param mixed $object * @param string $routeName #Route * @param string $separator * @param array $query * * @return string */ public function generateObjectUrl($object, $routeName, $separator = '_', array $query = array()) { $parameters = array(); $accessor = PropertyAccess::createPropertyAccessor(); $pattern = $this->router->getRouteCollection()->get($routeName)->getPath(); if (preg_match_all('/\\{([a-z]+)\\}/', $pattern, $matches)) { foreach ($matches[1] as $holder) { $value = $accessor->getValue($object, $holder); if (!is_numeric($value)) { $value = $this->slugify->slugify($value, $separator); } $parameters[$holder] = $value; } } return $this->router->generate($routeName, $parameters, $query); }
/** * @param string $route * @param \SimpleXMLElement $params * @param boolean $hidden * @param array $options */ protected function addRouteParameters($route, \SimpleXMLElement $params, $hidden, array &$options) { $options['routeParameters'] = []; $parameters = $params->xpath('param'); if (!empty($parameters)) { foreach ($parameters as $param) { if (isset($param['name'])) { $options['routeParameters'][(string) $param['name']] = (string) $param; } } } if ($hidden) { if ($this->router instanceof I18nRouter) { $collection = $this->router->getOriginalRouteCollection(); } else { $collection = $this->router->getRouteCollection(); } $route = $collection->get($route); $variables = []; preg_match_all('#\\{\\w+\\}#', $route->getPath(), $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); foreach ($matches as $match) { $variables[] = substr($match[0][0], 1, -1); } if (!empty($variables)) { $defaults = $route->getDefaults(); foreach ($variables as $variable) { if (!isset($options['routeParameters'][$variable]) && !isset($defaults[$variable])) { $value = $this->request->getCurrentRequest()->attributes->get($variable, '0'); $options['routeParameters'][$variable] = empty($value) ? '0' : $value; } } } } }
/** * return the extref from URL * * @param string $url Extref URL * @return ExtReference * @throws \InvalidArgumentException */ public function getExtReference($url) { $path = parse_url($url, PHP_URL_PATH); if ($path === false) { throw new \InvalidArgumentException(sprintf('URL %s', $url)); } $id = null; $collection = null; foreach ($this->router->getRouteCollection()->all() as $route) { list($collection, $id) = $this->getDataFromRoute($route, $path); if ($collection !== null && $id !== null) { return ExtReference::create($collection, $id); } } throw new \InvalidArgumentException(sprintf('Could not read URL %s', $url)); }
/** * Builds the pagetree * * @param RouterInterface $router * * @throws PageTree\InvalidPageTreeException */ private function buildPageTree(RouterInterface $router) { $this->pageTree = []; $this->directAccess = []; // collect all routes, which are configured to be in the page tree foreach ($router->getRouteCollection() as $routeName => $route) { /** @var Route $route */ $node = $this->transformRouteToNode($routeName, $route); if (!is_null($node)) { $this->directAccess[$routeName] = $node; } } // apply correct nesting of routes foreach ($this->directAccess as $node) { if ($node->isRootNode()) { $this->pageTree[] = $node; } else { if (array_key_exists($node->getParent(), $this->directAccess)) { $this->directAccess[$node->getParent()]->addChild($node); } else { throw new InvalidPageTreeException("Invalid pagetree at route „{$node->getRoute()}“: parent '{$node->getParent()}' requested, but route was not found. Did you forget to define the route „{$node->getRoute()}“ as root?"); } } } }
public function addRootRelations(Root $root, ClassMetadataInterface $classMetadata) { $prefix = $root->getPrefix(); $relations = array(); $self_args = $this->router->match($root->getPrefix()); $relations[] = new Hateoas\Relation('self', new Hateoas\Route($self_args['_route'], array(), false)); foreach ($root->getEntityNames() as $rel => $entityName) { /** @var ClassMetadata $metadata */ $metadata = $this->entityManager->getMetadataFactory()->getMetadataFor($entityName); $routeName = $this->routeResolver->resolveRouteName($metadata->getName(), 'cgetAction'); if ($routeName) { $arguments = array(); foreach (self::$COLLECTION_ARGUMENTS as $argument) { $arguments[$argument] = '{' . $argument . '}'; } $relations[] = new Hateoas\Relation(Inflector::pluralize($rel), new Hateoas\Route($routeName, $arguments, false)); } $routeName = $this->routeResolver->resolveRouteName($metadata->getName(), 'getAction'); if ($routeName) { $relations[] = new Hateoas\Relation($rel, new Hateoas\Route($routeName, array('id' => "{id}"), false)); } $routeName = $self_args['_route'] . '_schema'; if ($this->router->getRouteCollection()->get($routeName)) { $relations[] = new Hateoas\Relation('schema:' . $rel, new Hateoas\Route($routeName, array('rel' => $rel), false)); } } $user = $root->getCurrentUser(); if ($user instanceof User) { $routeName = $this->routeResolver->resolveRouteName(get_class($user), 'getAction'); if ($routeName) { $relations[] = new Hateoas\Relation('currentUser', new Hateoas\Route($routeName, array('id' => $user->getId()), false)); } } return $relations; }
/** * @param $path * @return array|null */ private function findResourceInformationFromRouter($path) { // store and reset the request method $requestMethod = $this->getRequestMethod(); $this->setRequestMethod(Request::METHOD_GET); try { $parameters = $this->router->match($path); $this->setRequestMethod($requestMethod); } catch (ResourceNotFoundException $e) { $this->setRequestMethod($requestMethod); return null; } catch (MethodNotAllowedException $e) { $this->setRequestMethod($requestMethod); return null; } if (!isset($parameters['_route'])) { return null; } $route = $this->router->getRouteCollection()->get($parameters['_route']); if (null === $route) { return null; } if (!$route->hasOption(self::RESOURCE_ENTITY_CLASS_OPTION) || !$route->hasOption(self::RESOURCE_ENTITY_ID_OPTION)) { return null; } if (!isset($parameters[$route->getOption(self::RESOURCE_ENTITY_ID_OPTION)])) { return null; } $converter = $this->defaultConverter; if ($route->hasOption(self::RESOURCE_CONVERTER_OPTION)) { $converter = $route->getOption(self::RESOURCE_CONVERTER_OPTION); } return [$route->getOption(self::RESOURCE_ENTITY_CLASS_OPTION), $parameters[$route->getOption(self::RESOURCE_ENTITY_ID_OPTION)], $converter]; }
/** * @param array $link * @param bool $absolute * @return string */ public function getLink($link, $absolute = true) { $url = '#'; if (isset($link['name'])) { $parameters = array(); $locale = $this->context->get('language'); $route = $link['name']; if ($this->router instanceof \BeSimple\I18nRoutingBundle\Routing\Router and $this->router->getRouteCollection()->get(sprintf('%s.%s', $route, $locale))) { $parameters['locale'] = $locale; $options = $this->router->getRouteCollection()->get($route . '.' . $locale)->getOptions(); } else { $options = $this->router->getRouteCollection()->get($route)->getOptions(); } $iParameters = isset($link['parameters']) ? $link['parameters'] : array(); if (isset($options['parameters'])) { foreach ($options['parameters'] as $parameter) { if (isset($parameter['type']) && preg_match('/Bundle/i', $parameter['type'])) { $entity = $this->entityManager->getRepository($parameter['type'])->find($iParameters[$parameter['name']]); $method = 'get' . ucfirst($parameter['field']); $parameters[$parameter['name']] = $entity->{$method}(); if (isset($parameter['children'])) { foreach ($parameter['children'] as $child) { $method = 'get' . ucfirst($child); $parameters[$child] = $entity->{$method}()->getSlug(); } } } else { if (isset($parameter['name']) && isset($parameters[$parameter['name']])) { $parameters[$parameter['name']] = $iParameters[$parameter['name']]; } } } } try { $url = $this->router->generate($route, $parameters, $absolute); } catch (\Exception $e) { $url = '#'; } } elseif (isset($link['externalLink']) and $link['externalLink']) { $url = $link['externalLink']; if (($httpPos = strpos($link['externalLink'], 'http')) === false or $httpPos != 0) { $url = sprintf('http://%s', $link['externalLink']); } } return $url; }
public function __construct(RouterInterface $router, $defaultLocale = 'en', array $supportedLocales = array('en'), $localeRouteParam = '_locale') { $this->router = $router; $this->routeCollection = $router->getRouteCollection(); $this->defaultLocale = $defaultLocale; $this->supportedLocales = $supportedLocales; $this->localeRouteParam = $localeRouteParam; }
/** * Get route info by route name * * @param $routeName * @return string|null */ protected function getRouteInfoByRouteName($routeName) { $route = $this->router->getRouteCollection()->get($routeName); if ($route) { return $route->getDefault(self::ROUTE_CONTROLLER_KEY); } return null; }
/** * @param RouterInterface $router */ public function __construct(RouterInterface $router) { $route = $router->getRouteCollection()->get('open_orchestra_front_node'); if (!is_null($route) && !is_null($route->getDefault('_controller'))) { $this->logicalName = $route->getDefault('_controller'); } else { throw new NoRenderingMethodForNodeException(); } }
/** * @param array $definedRoutes * * @return bool */ protected function validateRoutes(array $definedRoutes) { foreach ($definedRoutes as $name => $info) { if (!$this->router->getRouteCollection()->get($name)) { throw new \InvalidArgumentException(sprintf('The route "%s" does not exist.', $name)); } } return true; }
/** * @param $route * @param array $queryArgs * * @return array */ public function getDefaults($route) { $route = $this->router->getRouteCollection()->get($route); if ($route) { $defaults = $route->getDefaults(); return $defaults; } return array(); }
/** * {@inheritdoc} */ public function getCurrentRoute() { $routeName = $this->requestHelper->getAttributesBagParam('_route'); $route = $this->router->getRouteCollection()->get($routeName); if (null === $route) { throw new \RuntimeException('Cannot determine current route from request'); } return $this->router->getRouteCollection()->get($routeName); }
/** * Return a list of route to inspect for ApiDoc annotation * You can extend this method if you don't want all the routes * to be included. * * @return Route[] An array of routes */ public function getRoutes() { $routes = []; foreach ($this->router->getRouteCollection()->all() as $key => $route) { if (strpos($key, 'api_' . $this->versionApi) !== false) { $routes[$key] = $route; } } return $routes; }
/** * @param string $routeName * @return \Symfony\Component\Routing\Route|null */ protected function getRoute($routeName) { // Create cache directory $this->filesystem->mkdir($this->cacheDirectory); $route = null; try { $file = sprintf('%s/%s.data', $this->cacheDirectory, md5($routeName)); if (!$this->filesystem->exists($file)) { // Get route $route = $this->router->getRouteCollection()->get($routeName); // Serialize it file_put_contents($file, serialize($route)); } else { $route = unserialize(file_get_contents($file)); } } catch (\Exception $e) { } return $route; }
/** * Returns an ApiDoc annotation. * * @param string $controller * @param string $route *Â @return ApiDoc|null */ public function get($controller, $route) { if ($method = $this->getReflectionMethod($controller)) { if ($annotation = $this->reader->getMethodAnnotation($method, self::ANNOTATION_CLASS)) { if ($route = $this->router->getRouteCollection()->get($route)) { return $this->extractData($annotation, $route, $method); } } } return null; }
function it_redirects_to_resource($config, RouterInterface $router, RouteCollection $routes, Route $route) { $router->getRouteCollection()->willReturn($routes); $routes->get('my_route')->willReturn($route); $config->getRedirectParameters('resource')->willReturn(array()); $config->getRedirectRoute('show')->willReturn('my_route'); $router->generate('my_route', array())->willReturn('http://myurl.com'); $config->getRedirectHash()->willReturn(null); $config->isHeaderRedirection()->willReturn(false); $this->redirectTo('resource')->shouldHaveType(RedirectResponse::class); }
/** * @param $action * @param $parameters * * @return array */ public function handleParameters($action, $parameters) { if ($action) { $variables = $this->router->getRouteCollection()->get($action)->compile()->getVariables(); $nParameters = array(); foreach ($variables as $variable) { $nParameters[$variable] = $parameters[$variable]; } return $nParameters; } }
/** * Dump all translation files. * * @param string $target Target directory. */ public function dump($target = 'web/js') { $route = $this->router->getRouteCollection()->get('bazinga_jstranslation_js'); $requirements = $route->getRequirements(); $formats = explode('|', $requirements['_format']); $routeDefaults = $route->getDefaults(); $defaultFormat = $routeDefaults['_format']; $parts = array_filter(explode('/', $route->getPattern())); $this->filesystem->remove($target . '/' . current($parts)); $this->dumpConfig($route, $formats, $target); $this->dumpTranslations($route, $formats, $target); }