/** * Modifies the Request object to apply configuration information found in * controllers annotations like the template to render or HTTP caching * configuration. * * @param FilterControllerEvent $event A FilterControllerEvent instance */ public function onKernelController(FilterControllerEvent $event) { if (!is_array($controller = $event->getController())) { return; } $className = class_exists('Doctrine\\Common\\Util\\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]); $object = new \ReflectionClass($className); $method = $object->getMethod($controller[1]); $classConfigurations = $this->getConfigurations($this->reader->getClassAnnotations($object)); $methodConfigurations = $this->getConfigurations($this->reader->getMethodAnnotations($method)); $configurations = array(); foreach (array_merge(array_keys($classConfigurations), array_keys($methodConfigurations)) as $key) { if (!array_key_exists($key, $classConfigurations)) { $configurations[$key] = $methodConfigurations[$key]; } elseif (!array_key_exists($key, $methodConfigurations)) { $configurations[$key] = $classConfigurations[$key]; } else { if (is_array($classConfigurations[$key])) { if (!is_array($methodConfigurations[$key])) { throw new \UnexpectedValueException('Configurations should both be an array or both not be an array'); } $configurations[$key] = array_merge($classConfigurations[$key], $methodConfigurations[$key]); } else { // method configuration overrides class configuration $configurations[$key] = $methodConfigurations[$key]; } } } $request = $event->getRequest(); foreach ($configurations as $key => $attributes) { $request->attributes->set($key, $attributes); } }
public function onCoreController(FilterControllerEvent $event) { if (!is_array($controller = $event->getController())) { return; } $method = new \ReflectionMethod($controller[0], $controller[1]); if (!($annotations = $this->reader->getMethodAnnotations($method))) { return; } foreach ($annotations as $annotation) { if ($annotation instanceof LayoutAnnotation) { if ($annotation->getPosition()) { $root = $this->em->getRepository('TemplateDesignerLayoutBundle:Layout')->findLayoutWitOptions($annotation->getName(), $annotation->getPosition()); } else { $root = $this->em->getRepository('TemplateDesignerLayoutBundle:Layout')->findOneBy(array('name' => $annotation->getName())); } if (!$annotation->getPosition() && !$annotation->getName()) { throw new \Exception("Parameter missing in layout annotation", 1); } if (!$root) { throw new NotFoundHttpException('Layout not found'); } $route_params = $event->getRequest()->attributes->get('_route_params'); $route_params['rootLayout'] = $root; $event->getRequest()->attributes->set('_route_params', $route_params); } } }
public function onKernelController(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) { if ($event->getRequestType() == \Symfony\Component\HttpKernel\HttpKernelInterface::SUB_REQUEST) { return; } if ($event->getRequest()->isXmlHttpRequest()) { return; } if (null == $this->security->getToken()) { return; } $this->user = $this->security->getToken()->getUser(); if ($this->security->isGranted('ROLE_ADMIN')) { return; } $controller = $event->getController(); if (!preg_match('#FrontBundle#', get_class($controller[0]))) { return; } $this->request = $event->getRequest(); $this->trueSession = $this->request->getSession(); $this->route = $this->request->get('_route'); $this->routeParams = $this->request->get('_route_params'); if (preg_match('#admin#', $this->route) || preg_match('#tracking#', $this->route) || preg_match('#_wdt#', $this->route)) { return; } $this->initSession(); $this->initView(); }
/** * After a controller has been matched. We need to inject current * Kernel instance and main DI container. * * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event */ public function onControllerMatched(FilterControllerEvent $event) { $matchedCtrl = $event->getController()[0]; /* * Inject current Kernel to the matched Controller */ if ($matchedCtrl instanceof Controller) { $matchedCtrl->setKernel($this->kernel); $matchedCtrl->setContainer($this->kernel->getContainer()); } /* * Do not inject current theme when * Install mode is active. */ if (true !== $this->kernel->container['config']['install'] && $event->getRequest() instanceof RoadizRequest) { // No node controller matching in install mode $event->getRequest()->setTheme($matchedCtrl->getTheme()); } /* * Set request locale if _locale param * is present in Route. */ $routeParams = $event->getRequest()->get('_route_params'); if (!empty($routeParams["_locale"])) { $event->getRequest()->setLocale($routeParams["_locale"]); } /* * Prepare base assignation */ if ($matchedCtrl instanceof AppController) { $matchedCtrl->__init(); } }
public function onKernelController(FilterControllerEvent $event) { $controller = $event->getController(); /* * $controller passed can be either a class or a Closure. * This is not usual in Symfony but it may happen. * If it is a class, it comes in array format */ if (!is_array($controller)) { return; } if ($controller[0] instanceof TokenAuthenticatedController) { $this->session = $this->container->get('session'); $custom = json_decode($this->session->get('custom')); if (!$custom) { return; } $custom = $this->em->find('WoojinOrderBundle:Custom', $custom->id); if ($custom->getCsrf() !== $this->session->get('avenue_token')) { $this->session->clear(); $url = $this->container->get('router')->generate('front_custom_login', null, true); throw new AccessDeniedHttpException('憑證失效,請前往' . $url . '重新登入會員'); } // mark the request as having passed token authentication $event->getRequest()->attributes->set('auth_token', true); } else { $event->getRequest()->attributes->set('auth_token', null); } }
public function apiFirewall(FilterControllerEvent $event) { $controller = $event->getController(); if ($controller[0] instanceof BaseApiController && $event->getRequest()->attributes->get('not-logged') != 1) { $apiAccount = $this->checkApiAccess($event->getRequest()); $controller[0]->setApiUser($apiAccount); } }
public function onKernelController(FilterControllerEvent $event) { $this->controllers[$event->getRequest()] = $event->getController(); if ($parentRequestAttributes = $event->getRequest()->attributes->get('_forwarded')) { if ($parentRequestAttributes instanceof ParameterBag) { $parentRequestAttributes->set('_forward_controller', $event->getController()); } } }
/** * On each request we want to update the user's last activity datetime * * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event * @return void */ public function onCoreController(FilterControllerEvent $event) { if (true === isset($this->context) && true === is_object($this->context)) { if (true === is_object($this->context->getToken()) && $this->context->getToken() != null) { $user = $this->context->getToken()->getUser(); } } if (false === isset($user) || false === is_object($user) || $user == null) { $user = null; } $route = $event->getRequest()->attributes->get('_route'); $request = $event->getRequest(); $session = $request->getSession(); $routeParams = $request->get('_route_params'); if ($route[0] == '_') { return; } $routeData = ['name' => $route, 'params' => $routeParams]; $thisRoute = $session->get('this_route', []); if (true === isset($_SERVER["REQUEST_URI"]) && trim($_SERVER["REQUEST_URI"]) != "") { if (true === isset($_COOKIE['LICO_URL_2']) && trim($_COOKIE['LICO_URL_2']) != "") { setcookie('LICO_URL_3', urldecode(trim($_COOKIE['LICO_URL_2'])), time() + 3600, '/'); } if (true === isset($_COOKIE['LICO_URL_1']) && trim($_COOKIE['LICO_URL_1']) != "") { setcookie('LICO_URL_2', urldecode(trim($_COOKIE['LICO_URL_1'])), time() + 3600, '/'); } if (true === isset($_COOKIE['LICO_URL_0']) && trim($_COOKIE['LICO_URL_0']) != "") { setcookie('LICO_URL_1', urldecode(trim($_COOKIE['LICO_URL_0'])), time() + 3600, '/'); } setcookie('LICO_URL_0', $_SERVER["REQUEST_URI"], time() + 3600, '/'); } $session->set('last_route', $thisRoute); $session->set('this_route', $routeData); if ($route == null || true === in_array($route, array('_wdt'))) { return true; } $ipaddress = $this->container->get('request')->server->get("REMOTE_ADDR"); if ($ipaddress == "127.0.0.1") { if (true === isset($_SERVER["REMOTE_ADDR"]) && trim($_SERVER["REMOTE_ADDR"]) != "") { $ipaddress = $_SERVER["REMOTE_ADDR"]; } else { $ipaddress = "N/A"; } } $useragent = $this->container->get('request')->server->get("HTTP_USER_AGENT"); $obj = new DetectBotFromUserAgent(); $isbot = $obj->licoIsBot($useragent, $ipaddress); $activity = new Activity(); $activity->setUser($user); $activity->setRoute($route); $activity->setIpAddress($ipaddress); $activity->setUserAgent($useragent); $activity->setIsBot($isbot); $activity->setCreatedAt(new \DateTime()); $this->em->persist($activity); $this->em->flush(); }
public function onKernelController(FilterControllerEvent $event) { $controller = $event->getController(); if (!is_array($controller)) { return; } if ($controller[0] instanceof ApiController) { $controller[0]->initialize($event->getRequest()); $controller[0]->checkApiKey($event->getRequest()); } }
public function onKernelController(FilterControllerEvent $event) { if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) { $controllers = $event->getController(); if (is_array($controllers)) { $controller = $controllers[0]; if (is_object($controller) && method_exists($controller, 'preExecute') && $event->getRequest()->getMethod() != 'OPTIONS') { $controller->preExecute($event->getRequest()); } } } }
/** * Listens when the annotation exists loading the resource of id given and if it is allowed. * * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event The filter controller event */ public function onResourceIfAllowedAnnotationMethod(FilterControllerEvent $event) { list($object, $method) = $event->getController(); $reflectionClass = new \ReflectionClass(get_class($object)); $reflectionMethod = $reflectionClass->getMethod($method); if ($annotation = $this->annotationReader->getMethodAnnotation($reflectionMethod, $this->annotationClass)) { $resourceId = $event->getRequest()->attributes->get(sprintf('%sId', $this->resource)); if (null !== $resourceId) { $event->getRequest()->attributes->set($this->resource, $this->getResourceIfAllowed($resourceId, $annotation->getGrant())); } } }
/** * Handle actions before the kernel loads the controller. * * @param FilterControllerEvent $event */ public function onKernelController(FilterControllerEvent $event) { if (null === ($module = $event->getRequest()->get('module'))) { return; } if (!$module instanceof ModuleInterface) { try { $module = $this->getModularRouter()->getModuleByRequest($event->getRequest()); } catch (Exception $e) { return; } } $this->getModuleManager()->setCurrentModule($module); }
public function onKernelController(FilterControllerEvent $event) { $controller = $event->getController(); if (!is_array($controller) || !$controller[0] instanceof RestController) { return; } $action = $controller[1]; $controller = $controller[0]; $reflection = new \ReflectionObject($controller); $reader = new AnnotationReader(); $authorize = $reader->getClassAnnotation($reflection, Authorize::class); $methodAuthorize = $reader->getMethodAnnotation($reflection->getMethod($action), Authorize::class); if ($methodAuthorize != null) { $authorize = $methodAuthorize; } $config = $this->container->getParameter("rest.config")["authentication"]; if ($authorize != null && $config["enabled"]) { $authHeader = $event->getRequest()->headers->get("authorization", "null null"); $explode = explode(" ", $authHeader); $type = $explode[0]; $token = $explode[1]; if ($authHeader == "null null") { $this->unauth(); } if (strtolower($type) != "bearer") { $this->unauth(); } $type = $config["oauth_type"]; if ($type == "own") { /** @var OAuthService $oauthService */ $oauthService = $this->container->get("rest.oauth_service"); $authToken = $oauthService->getAuthToken($token); if ($authToken == null) { $this->unauth(); } $session = new Session(new MockArraySessionStorage()); $session->set("token", $authToken); $session->set("consumer", $authToken->getConsumer()); $session->set("user", $authToken->getUser()); $event->getRequest()->setSession($session); } else { if ($type == "static") { $tokens = $config["oauth"]["static_tokens"]; if (!in_array($token, $tokens)) { $this->unauth(); } } } } }
/** * Searches for sluggable objects in the route parameters and checks slugs if necessary. * * If an invalid slug is detected, then the user will be redirected to the URLs with the valid slug. * * @param FilterControllerEvent $event */ public function onKernelController(FilterControllerEvent $event) { $attributes = $event->getRequest()->attributes; foreach ($attributes as $name => $value) { if ($this->hasValidSlug($attributes, $name)) { continue; } $event->stopPropagation(); // Invalid slug passed. Redirect to a URL with valid slug. $event->setController(function () use($event, $name) { return $this->createRedirectFor($event->getRequest(), $name); }); break; } }
public function controllerListener(FilterControllerEvent $event) { static $possibleMatches = ['product_id' => 'product', 'category_id' => 'category', 'content_id' => 'content', 'folder_id' => 'folder']; $request = $event->getRequest(); // Try to find a direct match. A view is defined for the object. foreach ($possibleMatches as $parameter => $objectType) { if (null !== ($objectId = $request->query->get($parameter))) { $findEvent = new FindViewEvent($objectId, $objectType); $event->getDispatcher()->dispatch('view.find', $findEvent); if ($findEvent->hasView()) { $event->getRequest()->query->set('view', $findEvent->getView()); } return; } } }
/** * @param FilterControllerEvent $event */ public function onKernelController(FilterControllerEvent $event) { if (HttpKernel::MASTER_REQUEST == $event->getRequestType()) { $this->linkProvider->setRequest($event->getRequest()); } return; }
public function onKernelController(FilterControllerEvent $event) { if (!is_array($controller = $event->getController())) { return; } $request = $event->getRequest(); if (!($configuration = $request->attributes->get('_acl_permission'))) { return; } $refl = new \ReflectionMethod($controller[0], $controller[1]); foreach ($refl->getParameters() as $param) { if (!$param->getClass() || $param->getClass()->isInstance($request)) { continue; } $name = $param->getName(); $object = $request->get($name); if (is_null($object)) { continue; } $mask = null; foreach ($configuration as $config) { if (!is_null($mask = $config->getEntry($name))) { continue; } } if (is_null($mask)) { continue; } if (!$this->manager->isGranted($mask, $object)) { throw new AccessDeniedException('Acl permission for this object is not granted.'); } } }
public function onKernelController(FilterControllerEvent $event) { $locale = null; $default_locale = null; $part_locale = Service::get('config')->get('app', 'local', null); if ($part_locale) { $part_locale = explode('_', $part_locale); $default_locale = $part_locale[0]; } $Request = $event->getRequest(); // Si en la sesion no existe _locale pregunta a la ruta encontrada si existe la opcion _locale if (!Service::get('session')->has('_locale')) { /** @var RouteCollection $RouteCollection */ $RouteCollection = Service::get('kernel.routes'); /** @var Route $Route */ $Route = $RouteCollection->get($Request->attributes->get('_route')); $locale = $Route->getOption('_locale'); // Si no la encuentra la optiene de la configuracion. if (!$locale) { $locale = $default_locale; } // Si no existe en la configuracion la obtiene de la peticion por defecto del componente. if (!$locale) { $locale = $Request->getDefaultLocale(); $default_locale = $Request->getDefaultLocale(); } // Asigna a la sesion la variable locale. Service::get('session')->set('_locale', $locale); Service::get('session')->set('_locale_default', $default_locale); } $Request->setLocale($locale); $Request->setDefaultLocale($default_locale); }
/** * Modifies the ParamConverterManager instance. * * @param FilterControllerEvent $event A FilterControllerEvent instance */ public function onKernelController(FilterControllerEvent $event) { $controller = $event->getController(); $request = $event->getRequest(); $configurations = array(); if ($configuration = $request->attributes->get('_converters')) { foreach (is_array($configuration) ? $configuration : array($configuration) as $configuration) { $configurations[$configuration->getName()] = $configuration; } } if (is_array($controller)) { $r = new \ReflectionMethod($controller[0], $controller[1]); } else { $r = new \ReflectionFunction($controller); } // automatically apply conversion for non-configured objects foreach ($r->getParameters() as $param) { if (!$param->getClass() || $param->getClass()->isInstance($request)) { continue; } $name = $param->getName(); if (!isset($configurations[$name])) { $configuration = new ParamConverter(array()); $configuration->setName($name); $configuration->setClass($param->getClass()->getName()); $configurations[$name] = $configuration; } elseif (null === $configurations[$name]->getClass()) { $configurations[$name]->setClass($param->getClass()->getName()); } $configurations[$name]->setIsOptional($param->isOptional()); } $this->manager->apply($request, $configurations); }
/** * Guesses the template name to render and its variables and adds them to * the request object. * * @param FilterControllerEvent $event A FilterControllerEvent instance */ public function onKernelController(FilterControllerEvent $event) { if (!is_array($controller = $event->getController())) { return; } $request = $event->getRequest(); if (!($configuration = $request->attributes->get('_template'))) { return; } if (!$configuration->getTemplate()) { $guesser = $this->container->get('sensio_framework_extra.view.guesser'); $configuration->setTemplate($guesser->guessTemplateName($controller, $request, $configuration->getEngine())); } $request->attributes->set('_template', $configuration->getTemplate()); $request->attributes->set('_template_vars', $configuration->getVars()); $request->attributes->set('_template_streamable', $configuration->isStreamable()); // all controller method arguments if (!$configuration->getVars()) { $r = new \ReflectionObject($controller[0]); $vars = array(); foreach ($r->getMethod($controller[1])->getParameters() as $param) { $vars[] = $param->getName(); } $request->attributes->set('_template_default_vars', $vars); } }
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); }); } }
/** * Handles HTTP validation headers. */ public function onKernelController(FilterControllerEvent $event) { $request = $event->getRequest(); if (!($configuration = $request->attributes->get('_cache'))) { return; } $response = new Response(); $lastModifiedDate = ''; if ($configuration->getLastModified()) { $lastModifiedDate = $this->getExpressionLanguage()->evaluate($configuration->getLastModified(), $request->attributes->all()); $response->setLastModified($lastModifiedDate); } $etag = ''; if ($configuration->getETag()) { $etag = hash('sha256', $this->getExpressionLanguage()->evaluate($configuration->getETag(), $request->attributes->all())); $response->setETag($etag); } if ($response->isNotModified($request)) { $event->setController(function () use($response) { return $response; }); } else { if ($etag) { $this->etags[$request] = $etag; } if ($lastModifiedDate) { $this->lastModifiedDates[$request] = $lastModifiedDate; } } }
/** * @param FilterControllerEvent $event */ public function onKernelController(FilterControllerEvent $event) { $request = $event->getRequest(); // Check if the event has a nodeTranslation, if not this method can be skipped if (!$request->attributes->has('_nodeTranslation')) { return; } $nodeTranslation = $request->attributes->get('_nodeTranslation'); if (!$nodeTranslation instanceof NodeTranslation) { $nodeTranslation = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation')->find($nodeTranslation); $request->attributes->set('_nodeTranslation', $nodeTranslation); } $entity = $nodeTranslation->getRef($this->em); // If the entity is an instance of the SlugActionInterface, change the controller if ($entity instanceof SlugActionInterface) { $request->attributes->set('_entity', $entity); // Do security check by firing an event that gets handled by the SlugSecurityListener $securityEvent = new SlugSecurityEvent(); $securityEvent->setNode($nodeTranslation->getNode())->setEntity($entity)->setRequest($request)->setNodeTranslation($nodeTranslation); $this->eventDispatcher->dispatch(Events::SLUG_SECURITY, $securityEvent); // Set the right controller $request->attributes->set('_controller', $entity->getControllerAction()); $event->setController($this->resolver->getController($request)); } }
public function onKernelController(FilterControllerEvent $event) { $request = $event->getRequest(); if (!$request->attributes->has('_api')) { return; } /** @var Api $apiCommand */ $apiCommand = $request->attributes->get('_api'); if (!($type = $apiCommand->getType())) { return; } $formOptions = ['csrf_protection' => false, 'validation_groups' => $apiCommand->getGroups(), 'allow_extra_fields' => true]; if (!count($apiCommand->getGroups()) !== 0) { $formOptions['validation_groups'] = $apiCommand->getGroups(); } $formData = null; if ($request->attributes->has($apiCommand->getName())) { $formData = $request->attributes->get($apiCommand->getName()); } $form = $this->formFactory->createNamed('', $type, $formData, $formOptions); // "Loose" form submission, POST => GET => FILES. // @todo: Throw exception on parameter collision. $form->submit(array_replace_recursive($request->request->all(), $request->query->all(), $request->files->all()), !$request->isMethod('PATCH')); if (!$form->isValid()) { throw new CommandInvalidException($type, $form); } $request->attributes->set($apiCommand->getName(), $form->getData()); }
/** * Detects if there is a custom controller to use to render a Block. * * @param FilterControllerEvent $event * * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException */ public function getController(FilterControllerEvent $event) { $request = $event->getRequest(); // Only taking page related controller (i.e. ez_page:viewBlock or ez_page:viewBlockById) if (strpos($request->attributes->get('_controller'), 'ez_page:') === false) { return; } try { if ($request->attributes->has('id')) { $valueObject = $this->pageService->loadBlock($request->attributes->get('id')); $request->attributes->set('block', $valueObject); } elseif ($request->attributes->get('block') instanceof Block) { $valueObject = $request->attributes->get('block'); $request->attributes->set('id', $valueObject->id); } } catch (UnauthorizedException $e) { throw new AccessDeniedException(); } if (!isset($valueObject)) { $this->logger->error('Could not resolve a page controller, invalid value object to match.'); return; } $controllerReference = $this->controllerManager->getControllerReference($valueObject, 'block'); if (!$controllerReference instanceof ControllerReference) { return; } $request->attributes->set('_controller', $controllerReference->controller); $event->setController($this->controllerResolver->getController($request)); }
public function apply(FilterControllerEvent $event) { $controller = $event->getController(); $request = $event->getRequest(); if (is_array($controller)) { $reflected = new ReflectionMethod($controller[0], $controller[1]); } elseif (is_object($controller) && is_callable($controller, '__invoke')) { $reflected = new ReflectionMethod($controller, '__invoke'); } else { $reflected = new ReflectionFunction($controller); } foreach ($reflected->getParameters() as $param) { // Ignore non-classes or the request instance if ($param->getClass() && !$param->getClass()->isInstance($request)) { $value = null; $class = $param->getClass()->getName(); if ($class === 'Backpack\\Controller\\Request\\FormRequestInterface') { $value = new FormRequest($request, $this->container->get('form.factory')); } if ($value !== null) { $request->attributes->set($param->getName(), $value); } } } }
/** * Sets the cache key on the alias manager cache decorator. * * KernelEvents::CONTROLLER is used in order to be executed after routing. * * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event * The Event to process. */ public function onKernelController(FilterControllerEvent $event) { // Set the cache key on the alias manager cache decorator. if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) { $this->aliasManager->setCacheKey(rtrim($this->currentPath->getPath($event->getRequest()), '/')); } }
public function onKernelController(FilterControllerEvent $event) { if (!$this->isTrackingEnabled) { return; } $controller = $event->getController(); /* * $controller passed can be either a class or a Closure. * This is not usual in Symfony but it may happen. * If it is a class, it comes in array format * @link http://symfony.com/doc/current/event_dispatcher/before_after_filters.html#creating-an-event-listener */ if (!is_array($controller)) { return; } $controller = $controller[0]; if ($controller instanceof Controller) { $request = $event->getRequest(); $path = $request->getRequestUri(); $host = $request->getHost(); $title = get_class($controller); $data = ['dh' => $host, 'dp' => $path, 'dt' => $title]; try { $this->tracker->send($data, 'pageview'); } catch (\Exception $e) { $this->logger->error('Failed to send tracking data.', ['exception' => $e]); } } }
public function onKernelRequest(FilterControllerEvent $event) { if (HttpKernel::MASTER_REQUEST != $event->getRequestType() || $this->securityContext->getToken() === null) { // don't do anything if it's not the master request return; } $controller = $event->getController()[0]; // We know we'll build the board list eventually so we get all of them $this->boardService->getBoards(); $board = null; if ($event->getRequest()->attributes->get('boardSlug') !== null && method_exists($controller, 'setBoard') === true) { $board = $this->pathService->getCurrentBoard(); if ($board === null) { throw $controller->createNotFoundException(); } } if ($event->getRequest()->attributes->get('topicSlug') !== null && method_exists($controller, 'setTopic') === true && $board !== null) { $topic = $this->pathService->getCurrentTopic(); if ($topic === null) { throw $controller->createNotFoundException(); } } if ($event->getRequest()->attributes->get('messageId') !== null && method_exists($controller, 'setMessage') === true) { $message = $this->pathService->getCurrentMessage(); if ($message === null) { throw $controller->createNotFoundException(); } } }
public function onKernelController(FilterControllerEvent $event) { $controller = $event->getController(); /* * $controller passed can be either a class or a Closure. * This is not usual in Symfony but it may happen. * If it is a class, it comes in array format */ if (!is_array($controller)) { return; } if ($controller[0] instanceof AccountAccessInterface) { $accountName = $event->getRequest()->attributes->get('accountName'); $accounts = $controller[0]->getUser()->getAccounts(); $hasAccount = false; foreach ($accounts as $account) { if ($account->getName() == $accountName) { $hasAccount = true; break; } } if (!$hasAccount) { throw new AccessDeniedHttpException('Access denied.'); } $filter = $this->entityManager->getFilters()->enable('account_check_filter'); $filter->setParameter('account', $account->getId()); $event->getRequest()->attributes->set('accountTitle', $account->getTitle()); $router = $controller[0]->get('router'); $routeCollection = $router->getRouteCollection(); foreach ($routeCollection as $route) { $route->setDefault('accountName', $accountName); } } }