/**
  * 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?");
             }
         }
     }
 }
Пример #2
0
 public function onSiteAccessMatch(PostSiteAccessMatchEvent $event)
 {
     $rootLocationId = $this->configResolver->getParameter('content.tree_root.location_id');
     $this->urlAliasRouter->setRootLocationId($rootLocationId);
     $this->urlAliasGenerator->setRootLocationId($rootLocationId);
     $this->urlAliasGenerator->setExcludedUriPrefixes($this->configResolver->getParameter('content.tree_root.excluded_uri_prefixes'));
 }
Пример #3
0
 /**
  * @param string $route
  * @param array  $data
  *
  * @return RedirectResponse
  */
 public function redirectToRoute($route, array $data = array())
 {
     if ('referer' === $route) {
         return $this->redirectToReferer();
     }
     return $this->redirect($this->router->generate($route, $data));
 }
 /**
  * {@inheritDoc}
  */
 public function sendResettingEmailMessage(UserInterface $user)
 {
     $template = $this->parameters['resetting_password.template'];
     $url = $this->router->generate('fos_user_resetting_reset', array('token' => $user->getConfirmationToken()), true);
     $rendered = $this->templating->render($template, array('confirmationUrl' => $url, 'user' => $user));
     $this->sendEmailMessage($rendered, $user->getEmail());
 }
Пример #5
0
 public function serializeRouteArrayToJson(JsonSerializationVisitor $visitor, array $route, array $type, Context $context)
 {
     if (is_array($route)) {
         list($routeName, $routeParameters) = $route;
         return $this->router->generate($routeName, $routeParameters);
     }
 }
 /**
  * {@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());
 }
 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);
     }
 }
Пример #8
0
 public function onMainTopMenuTools(HookRenderBlockEvent $event)
 {
     $isGranted = $this->securityContext->isGranted(["ADMIN"], [], [BoSearch::getModuleCode()], [AccessManager::VIEW]);
     if ($isGranted) {
         $event->add(['title' => $this->trans('Search product', [], BoSearch::DOMAIN_NAME), 'url' => $this->router->generate('bosearch.product.view')]);
     }
 }
Пример #9
0
 /**
  * @param Request $request
  * @return Response
  * @throws \Exception
  */
 public function __invoke(Request $request)
 {
     $walletId = $request->get('walletId');
     $walletDto = $this->walletServiceFacade->getWallet($walletId);
     $this->checkAuthorizationForWallet($walletDto);
     $createTransactionCommand = $this->createCreateTransactionCommand($walletId);
     $user = $this->getUser();
     $createTransactionForm = $this->transactionFormFactory->createCreateForm($createTransactionCommand, $user->getId()->getValue());
     $createTransactionForm->handleRequest($request);
     if (!$createTransactionForm->isValid()) {
         $validationMsg = $this->getAllFormErrorMessagesAsString($createTransactionForm);
         $this->addFlash('error', $this->trans('create_transaction_form.flash.invalid_form') . ' ' . $validationMsg);
     } else {
         /** @var CreateTransactionCommand $createTransactionCommand */
         $createTransactionCommand = $createTransactionForm->getData();
         try {
             $commandValidator = new CreateTransactionCommandValidator();
             $commandValidator->validate($createTransactionCommand);
             $this->commandBus->handle($createTransactionCommand);
             $this->addFlash('success', $this->trans('transaction.flash.create_successfully'));
             $url = $this->router->generate('bc_app_wallet_transaction.index', array('walletId' => $createTransactionCommand->getWalletId()));
             return new RedirectResponse($url);
         } catch (\Exception $e) {
             $this->addFlash('error', $e->getMessage());
         }
     }
     $walletDto = $this->walletServiceFacade->getWallet($walletId);
     return $this->renderTransactionShowNew($request, $createTransactionForm->createView(), $walletDto);
 }
 /**
  * @param BreadcrumbItem $item
  * @param array          $variables
  * @return ProcessedBreadcrumbItem
  */
 public function process(BreadcrumbItem $item, $variables)
 {
     // Process the label
     if ($item->getLabel()[0] === '$') {
         $processedLabel = $this->parseValue($item->getLabel(), $variables);
     } else {
         $processedLabel = $this->translator->trans($item->getLabel());
     }
     // Process the route
     // TODO: cache parameters extracted from current request
     $params = [];
     foreach ($this->requestStack->getCurrentRequest()->attributes as $key => $value) {
         if ($key[0] !== '_') {
             $params[$key] = $value;
         }
     }
     foreach ($item->getRouteParams() ?: [] as $key => $value) {
         if ($value[0] === '$') {
             $params[$key] = $this->parseValue($value, $variables);
         } else {
             $params[$key] = $value;
         }
     }
     if ($item->getRoute() !== null) {
         $processedUrl = $this->router->generate($item->getRoute(), $params);
     } else {
         $processedUrl = null;
     }
     return new ProcessedBreadcrumbItem($processedLabel, $processedUrl);
 }
Пример #11
0
 /**
  * {@inheritdoc}
  */
 protected function getUriFromNode(NodeInterface $node)
 {
     if ($node instanceof RouterNodeInterface && null !== $node->getRoute()) {
         return $this->router->generate($node->getRoute(), $node->getRouteParameters(), $node->isRouteAbsolute());
     }
     return $node->getUri();
 }
Пример #12
0
 /**
  * Intercept Exceptions and send valid ajax errors
  * The idea is to NOT send HTML response when an issue(i.e.session expired) is encountered
  * in an ajax request.
  * @param GetResponseForExceptionEvent $event
  */
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     // Get the exception object from the received event
     $exception = $event->getException();
     $request = $event->getRequest();
     $isAjaxRequest = $request->isXmlHttpRequest();
     if ($isAjaxRequest) {
         $headers = [];
         // handle session expired
         if ($exception instanceof AuthenticationException) {
             $loginUrl = $this->router->generate('fos_user_security_login');
             // add custom header to redirect to login page on the client
             $headers['relogin'] = true;
             $headers['login-url'] = $loginUrl;
             $response = new Response('Authentication Required', 200, $headers);
         } elseif ($exception instanceof AccessDeniedException) {
             $headers['not-authorized'] = true;
             $response = new Response('Not authorized', 403, $headers);
         } else {
             $responseData = ['status' => false, 'msg' => 'Unknown Issue Encountered', 'data' => ['exception' => ['message' => $exception->getMessage(), 'file' => "{$exception->getFile()}:{$exception->getLine()}", 'trace' => $exception->getTraceAsString()]]];
             $response = new Response(json_encode($responseData), 500, $headers);
         }
         $event->setResponse($response);
         $event->stopPropagation();
     }
 }
Пример #13
0
 public function lostPasswordMail(User $user)
 {
     $template = 'HomefinanceBundle:mailer:lost_password.txt.twig';
     $url = $this->router->generate('reset_password_check_token', array('token' => $user->getConfirmationToken()), true);
     $context = array('user' => $user, 'confirmationUrl' => $url);
     $this->sendMessage($template, $context, $user->getEmail());
 }
 /**
  * Sends the Hydra header on each response.
  *
  * @param FilterResponseEvent $event
  */
 public function onKernelResponse(FilterResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     $event->getResponse()->headers->set('Link', sprintf('<%s>; rel="%sapiDocumentation"', $this->router->generate('api_hydra_vocab', [], UrlGeneratorInterface::ABSOLUTE_URL), ContextBuilder::HYDRA_NS));
 }
 public function onKernelController(FilterControllerEvent $event)
 {
     $controller = $event->getController();
     if (!is_array($controller)) {
         return;
     }
     $session = $event->getRequest()->getSession();
     /** @var BaseController $ctrl */
     $ctrl = $controller[0];
     if (!is_object($ctrl) || !$ctrl instanceof BaseController) {
         return;
     }
     // no loop for you, also allow username checking
     if ($ctrl instanceof ProfileController && ($controller[1] == 'updateUsernameAction' || $controller[1] == 'checkUsernameAction')) {
         return;
     }
     /** @var User $user */
     $user = $ctrl->getUser();
     if ($user && $this->isGUID($user->getUsername())) {
         $session->getFlashBag()->add('error', "We recently changed our username restrictions. Your previous username is no longer valid. Please create a new one.");
         $url = $this->router->generate('reset_username');
         $event->setController(function () use($url) {
             return new RedirectResponse($url);
         });
     }
 }
Пример #16
0
 /**
  * Creates a Response object to send upon a successful logout.
  *
  * @param Request $request
  *
  * @return Response never null
  */
 public function onLogoutSuccess(Request $request)
 {
     if ($request->isXmlHttpRequest() or 'json' == $request->getRequestFormat()) {
         return new JsonResponse(true);
     }
     return new RedirectResponse($this->router->generate('homepage'));
 }
 /**
  * @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);
     }
 }
Пример #18
0
 /**
  * @param array $workshops
  * @return array
  */
 public function decorate(array $workshops = [])
 {
     $workshops = array_map(function (Workshop $workshop) {
         return ["id" => $workshop->getSlug(), "start" => $workshop->getStartDate()->format(DateTime::ISO8601), "end" => $workshop->getEndDate()->format(DateTime::ISO8601), "title" => sprintf("%s: %s", $workshop->getCity(), $workshop->getTitle()), "editable" => false, "backgroundColor" => '', "url" => $this->router->generate("evento_show", ["slug" => $workshop->getSlug()])];
     }, $workshops);
     return $workshops;
 }
Пример #19
0
 /**
  * @param array $lessons
  * @return array
  */
 public function decorate(array $lessons = [])
 {
     $lessons = array_map(function (Lesson $lesson) {
         return ["id" => sprintf("%s#%s", $lesson->getWorkshop()->getSlug(), $lesson->getId()), "start" => $lesson->getStartDate()->format("Y-m-d H:i:s"), "end" => $lesson->getEndDate()->format("Y-m-d H:i:s"), "editable" => false, "url" => sprintf("%s#%s", $this->router->generate("evento_show", ["slug" => $lesson->getWorkshop()->getSlug()]), $lesson->getId())];
     }, $lessons);
     return $lessons;
 }
 public function getRouteDebugMessage($name, array $parameters = array())
 {
     if ($this->router instanceof VersatileGeneratorInterface) {
         return $this->router->getRouteDebugMessage($name, $parameters);
     }
     return "Route '{$name}' not found";
 }
 /**
  * Tests path.
  *
  * @param array $parameters
  * @param int   $page
  *
  * @dataProvider testPathDataProvider
  */
 public function testPath(array $parameters, $page)
 {
     $route = 'route_name';
     $this->router->expects($this->once())->method('generate')->will($this->returnValue('/'));
     $result = $this->pagerExtension->path($route, $page, $parameters);
     $this->assertEquals('/', $result);
 }
Пример #22
0
 public function createCollection(QueryBuilder $qb, Request $request, $route, array $routeParams = array())
 {
     $page = $request->query->get(self::PARAMETER_NAME_PAGE_NUMBER, 1);
     $count = $request->query->get(self::PARAMETER_NAME_PAGE_SIZE, self::PAGE_DEFAULT_COUNT);
     if ($count > self::MAX_PAGE_COUNT) {
         $count = self::MAX_PAGE_COUNT;
     }
     if ($count <= 0) {
         $count = self::PAGE_DEFAULT_COUNT;
     }
     $adapter = new DoctrineORMAdapter($qb);
     $pagerfanta = new Pagerfanta($adapter);
     $pagerfanta->setMaxPerPage($count);
     $pagerfanta->setCurrentPage($page);
     $players = [];
     foreach ($pagerfanta->getCurrentPageResults() as $result) {
         $players[] = $result;
     }
     $paginatedCollection = new PaginatedCollection($players, $pagerfanta->getNbResults());
     // make sure query parameters are included in pagination links
     $routeParams = array_merge($routeParams, $request->query->all());
     $createLinkUrl = function ($targetPage) use($route, $routeParams) {
         return $this->router->generate($route, array_merge($routeParams, array(self::PARAMETER_NAME_PAGE_NUMBER => $targetPage)));
     };
     $paginatedCollection->addLink('self', $createLinkUrl($page));
     $paginatedCollection->addLink('first', $createLinkUrl(1));
     $paginatedCollection->addLink('last', $createLinkUrl($pagerfanta->getNbPages()));
     if ($pagerfanta->hasNextPage()) {
         $paginatedCollection->addLink('next', $createLinkUrl($pagerfanta->getNextPage()));
     }
     if ($pagerfanta->hasPreviousPage()) {
         $paginatedCollection->addLink('prev', $createLinkUrl($pagerfanta->getPreviousPage()));
     }
     return $paginatedCollection;
 }
Пример #23
0
 public function testGetUrl()
 {
     $this->router->expects($this->once())->method('generate')->with($this->equalTo('sonata_cache_opcode'), $this->equalTo(array('token' => 'token')))->will($this->returnValue('/sonata/cache/opcode/token'));
     $method = new \ReflectionMethod($this->cache, 'getUrl');
     $method->setAccessible(true);
     $this->assertEquals('/sonata/cache/opcode/token', $method->invoke($this->cache));
 }
 /**
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
         return;
     }
     // @todo make endpoint(s) customizable
     if ($event->getRequest()->getMethod() !== 'POST') {
         return;
     }
     if ($event->getRequest()->getPathInfo() != '/xmlrpc' && $event->getRequest()->getPathInfo() != '/xmlrpc.php') {
         return;
     }
     try {
         $request = $this->requestGenerator->generateFromRequest($event->getRequest());
         if (isset($this->logger)) {
             $this->logger->debug((string) $request);
         }
     } catch (UnexpectedValueException $e) {
         $event->setResponse(new Response("Invalid request XML\n" . $e->getMessage(), 400));
         return;
     }
     // @todo refactor to dynamically set follow-up events instead of testing (cors bundle like)
     $request->attributes->set('IsXmlRpcRequest', true);
     $requestContext = new RequestContext();
     $requestContext->fromRequest($request);
     $originalContext = $this->router->getContext();
     $this->router->setContext($requestContext);
     $response = $this->httpKernel->handle($request);
     $event->setResponse($response);
     $this->router->setContext($originalContext);
     if ($response instanceof Response) {
         $event->setResponse($response);
     }
 }
Пример #25
0
 /**
  * {@inheritdoc}
  */
 public function redirectToRoute(RequestConfiguration $configuration, $route, array $parameters = [])
 {
     if ('referer' === $route) {
         return $this->redirectToReferer($configuration);
     }
     return $this->redirect($configuration, $this->router->generate($route, $parameters));
 }
 public function onPostSerialize(ObjectEvent $event)
 {
     /**
      * @var JsonSerializationVisitor $visitor
      */
     $visitor = $event->getVisitor();
     $object = $event->getObject();
     $annotations = $this->annotationReader->getClassAnnotations(new \ReflectionObject($object));
     $links = array();
     foreach ($annotations as $annotation) {
         if ($annotation instanceof Link) {
             if ($annotation->url) {
                 $uri = $this->evaluate($annotation->url, $object);
             } else {
                 $uri = $this->router->generate($annotation->route, $this->resolveParams($annotation->params, $object));
             }
             // allow a blank URI to be an optional link
             if ($uri) {
                 $links[$annotation->name] = $uri;
             }
         }
     }
     if ($links) {
         $visitor->addData('_links', $links);
     }
 }
 public function action(RouterInterface $router, RequestContext $context)
 {
     $request = Request::createFromGlobals();
     $bPath = $context->getPathInfo();
     try {
         $parameters = $router->match($bPath);
         var_dump($parameters);
         $_controller = $parameters["_controller"];
         $_controller = explode(":", $_controller);
         $class = $_controller[0];
         $action = strtolower($_controller[1]) . "Action";
         $class = new $class();
         ob_start();
         if (method_exists($class, $action)) {
             $class->{$action}($request, new JsonResponse());
             $response = new Response(ob_get_clean());
         } else {
             $response = new Response('Not Found', 404);
         }
     } catch (ResourceNotFoundException $e) {
         $response = new Response('Not Found', 404);
     } catch (Exception $e) {
         $response = new Response('An error occurred', 500);
     }
     $response->send();
 }
 /**
  * {@inheritdoc}
  */
 public function matchRequest(Request $request)
 {
     if (!$this->router instanceof RequestMatcherInterface) {
         throw new \BadMethodCallException('Router has to implement the ' . RequestMatcherInterface::class);
     }
     return $this->router->matchRequest($request);
 }
Пример #29
0
 /**
  * return the URL from extref
  *
  * @param ExtReference $extReference Extref
  * @return string
  * @throws \InvalidArgumentException
  */
 public function getUrl(ExtReference $extReference)
 {
     if (!isset($this->mapping[$extReference->getRef()])) {
         throw new \InvalidArgumentException(sprintf('Could not create URL from extref "%s"', json_encode($extReference)));
     }
     return $this->router->generate($this->mapping[$extReference->getRef()] . '.get', ['id' => $extReference->getId()], true);
 }
Пример #30
0
 /**
  * @param array $urlParameters
  *
  * @return string
  */
 protected function getUrl(array $urlParameters = array())
 {
     if (null === $this->getRouteName()) {
         throw new \RuntimeException('You need to provide route name, null given');
     }
     return $this->router->generate($this->getRouteName(), $urlParameters, true);
 }