/** * Event handler that renders custom pages in case of a NotFoundHttpException (404) * or a AccessDeniedHttpException (403). * * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { if ('dev' == $this->kernel->getEnvironment()) { return; } $exception = $event->getException(); $this->request->setLocale($this->defaultLocale); $this->request->setDefaultLocale($this->defaultLocale); if ($exception instanceof NotFoundHttpException) { $section = $this->getExceptionSection(404, '404 Error'); $this->core->addNavigationElement($section); $unifikRequest = $this->generateUnifikRequest($section); $this->setUnifikRequestAttributes($unifikRequest); $this->request->setLocale($this->request->attributes->get('_locale', $this->defaultLocale)); $this->request->setDefaultLocale($this->request->attributes->get('_locale', $this->defaultLocale)); $this->entityManager->getRepository('UnifikSystemBundle:Section')->setLocale($this->request->attributes->get('_locale')); $response = $this->templating->renderResponse('UnifikSystemBundle:Frontend/Exception:404.html.twig', array('section' => $section)); $response->setStatusCode(404); $event->setResponse($response); } elseif ($exception instanceof AccessDeniedHttpException) { $section = $this->getExceptionSection(403, '403 Error'); $this->core->addNavigationElement($section); $unifikRequest = $this->generateUnifikRequest($section); $this->setUnifikRequestAttributes($unifikRequest); $response = $this->templating->renderResponse('UnifikSystemBundle:Frontend/Exception:403.html.twig', array('section' => $section)); $response->setStatusCode(403); $event->setResponse($response); } }
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $response = new JsonResponse(); $detail = sprintf("Message: %s\nFile: %s:%s", $exception->getMessage(), $exception->getFile(), $exception->getLine()); $data = ['type' => '#0', 'code' => 0, 'title' => 'Internal Server Error', 'status' => JsonResponse::HTTP_INTERNAL_SERVER_ERROR, 'detail' => $detail]; $response->setStatusCode(JsonResponse::HTTP_INTERNAL_SERVER_ERROR); $response->setData($data); if ($exception instanceof HttpExceptionInterface) { $response->headers->replace($exception->getHeaders()); } if ($exception instanceof HttpException) { $data = ['type' => '#' . $exception->getCode(), 'code' => $exception->getCode(), 'title' => $exception->getMessage(), 'status' => JsonResponse::HTTP_BAD_REQUEST, 'detail' => $exception->getDetails()]; $response->setStatusCode(JsonResponse::HTTP_BAD_REQUEST); $response->setData($data); } if ($exception instanceof AccessDeniedHttpException) { $event->setResponse(new Response("", 403)); } else { $event->setResponse($response); } if (!in_array($this->kernel->getEnvironment(), array('dev', 'test'))) { unset($data['detail']); } }
public function onKernelRequest(GetResponseEvent $event) { if ($this->kernel->getEnvironment() != "dev") { if (preg_match("/\\/api\\//", $event->getRequest()->getUri())) { $requestUri = $event->getRequest()->getUri(); $requestMethod = $event->getRequest()->getMethod(); if ($requestMethod !== "GET") { $token = $this->context->getToken(); if (isset($token)) { $user = $token->getUser(); if (!isset($user) || "anon." === $user) { if (!$event->getRequest()->query->has('api_key')) { $event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401)); } } } else { $event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401)); } } } } $request = $event->getRequest(); if (!count($request->request->all()) && in_array($request->getMethod(), array('POST', 'PUT', 'PATCH', 'DELETE'))) { $contentType = $request->headers->get('Content-Type'); $format = null === $contentType ? $request->getRequestFormat() : $request->getFormat($contentType); if (!$this->decoderProvider->supports($format)) { return; } $decoder = $this->decoderProvider->getDecoder($format); $data = $decoder->decode($request->getContent(), $format); if (is_array($data)) { $request->request = new ParameterBag($data); } } }
/** * @param GetResponseEvent $event */ public function onLateKernelRequest(GetResponseEvent $event) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType() or !in_array($this->kernel->getEnvironment(), array('admin', 'admin_dev'))) { return; } $this->translationListener->setTranslatableLocale($this->context->getDefaultFrontLocale()); }
public function onPreSerialize(PreSerializeEvent $event) { $person = $event->getObject(); if ($person instanceof PersonInterface) { $imgHelper = $this->uploaderHelper; $templateHelper = $this->templateHelper; $isDev = $this->kernel->getEnvironment() === 'dev'; $person->prepareAPISerialize($imgHelper, $templateHelper, $isDev, $this->request); } }
/** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event, RequestStack $requestStack) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType() or !in_array($this->kernel->getEnvironment(), array('admin', 'admin_dev'))) { dump($this); die; return; } $token = $this->securityTokenStorage->getToken(); if ($token and $user = $token->getUser() and $user instanceof User && $requestStack) { $requestStack->getCurrentRequest()->setLocale($user->getLocale()); } }
/** * @param string $channel * @param string $message * @param Attachment[] $attachments */ public function sendToChannel($channel, $message, $attachments = []) { if ('prod' !== $this->kernel->getEnvironment()) { $channel = "#website-nl"; } $payload = new ChatPostMessagePayload(); $payload->setChannel($channel); $payload->setText($message); $payload->setUsername('DojoBot'); $payload->setIconEmoji('coderdojo'); if (false === empty($attachments)) { foreach ($attachments as $attachment) { $payload->addAttachment($attachment); } } $this->client->send($payload); return; }
/** * Initialize CodeIgniter system paths and defines * * @param Request $request * * @throws \UnexpectedValueException */ public function setCiPaths(Request $request = null) { if (!$this->isConfigValid()) { throw new \UnexpectedValueException('Bundle configuration is not valid. You need to specify application_path and system_path in config.yml'); } if ($this->pathsInitialized === false) { $scriptFile = $request !== null ? '.' . $request->getBasePath() . $request->getScriptName() : __FILE__; $rootPath = realpath($this->kernel->getRootDir() . '/..'); if ($rootPath === false) { throw new \LogicException('Nercury CI bundle was expecting to find kernel root dir in /app directory.'); } $systemPath = $this->getSystemPath() . '/'; $applicationFolder = $this->getAppPath() . '/'; if ($scriptFile === __FILE__) { $scriptFile = $rootPath . '/app.php'; $rootPath = realpath($rootPath . '/' . $systemPath) . '/'; $applicationFolder = realpath($rootPath . '/' . $applicationFolder); } $environment = $this->kernel->getEnvironment(); $environmentMap = array('dev' => 'development', 'test' => 'testing', 'prod' => 'production'); if (array_key_exists($environment, $environmentMap)) { $environment = $environmentMap[$environment]; } define('ENVIRONMENT', $environment); /* * ------------------------------------------------------------------- * Now that we know the path, set the main path constants * ------------------------------------------------------------------- */ // The name of THIS file define('SELF', pathinfo($scriptFile, PATHINFO_BASENAME)); // The PHP file extension // this global constant is deprecated. define('EXT', '.php'); // Path to the system folder define('BASEPATH', str_replace("\\", "/", $systemPath)); // Name of the "system folder" define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/')); define('APPPATH', $applicationFolder . '/'); // Path to the front controller (this file) define('FCPATH', $applicationFolder . '../'); // if (!defined('APPPATH')) { // // The path to the "application" folder // if (is_dir($application_folder)) { // define('APPPATH', $application_folder . '/'); // } else { // if (!is_dir(BASEPATH . $application_folder . '/')) { // exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: " . SELF); // } // // define('APPPATH', BASEPATH . $application_folder . '/'); // } // } $this->pathsInitialized = true; } }
/** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { if ($this->kernel->getEnvironment() == 'test' || HttpKernel::MASTER_REQUEST != $event->getRequestType()) { // don't do anything if it's not the master request return; } $request = $event->getRequest(); if ($request->attributes->get('_route') != 'page_promotion' || $request->getHost() == 'stfalcon.de' || $request->query->has('_check')) { return; } $response = new RedirectResponse('/'); $locale = $this->geoIpService->getLocaleByIp($request->getClientIp()); if ($request->getLocale() == $locale) { return; } $currentRouteParams = array_replace($request->attributes->get('_route_params'), ['_locale' => $locale]); $redirectUrl = $this->router->generate($request->attributes->get('_route'), $currentRouteParams); $response->setTargetUrl($redirectUrl); $event->setResponse($response); }
/** * @param PostResponseEvent $event */ public function onKernelTerminate(PostResponseEvent $event) { if (!in_array($this->kernel->getEnvironment(), $this->config['environnements'])) { return; } if (in_array($this->request->get('_route'), $this->config['disabledRoutes'])) { return; } if (strpos($this->request->get('_controller'), 'Tga\\AudienceBundle') !== false) { return; } if (substr($this->request->get('_route'), 0, 1) == '_') { return; } if (session_id() != '') { $this->sessionData = $_SESSION; } $timeToLoad = microtime(true) - $this->startTime; // Get the session and update it if required /** @var $em EntityManager */ $em = $this->doctrine->getManager(); $session = $em->createQueryBuilder()->select('s, c')->from('TgaAudienceBundle:VisitorSession', 's')->leftJoin('s.calls', 'c')->where('s.ip = :ip')->andWhere('s.lastVisit > :invalidateTime')->setParameter('ip', $this->request->getClientIp())->setParameter('invalidateTime', time() - $this->config['sessionDuration'])->getQuery()->getOneOrNullResult(); if (!$session) { $session = new \Tga\AudienceBundle\Entity\VisitorSession(); if (isset($_SERVER['HTTP_USER_AGENT'])) { $infos = $this->getBrowser($_SERVER['HTTP_USER_AGENT']); } else { $infos = new UserAgent(); } $session->setBrowser($infos->getBrowser())->setBrowserVersion($infos->getBrowserVersion())->setPlatform($infos->getPlatform())->setIp($this->request->getClientIp())->setDatas($this->sessionData); } $session->setLastVisit(new \DateTime()); $em->persist($session); if (!$session->lastPageIs($this->request->getRequestUri())) { $call = new \Tga\AudienceBundle\Entity\VisitorCall(); $call->setSession($session)->setDate(new \DateTime())->setController($this->request->get('_controller'))->setRoute($this->request->get('_route'))->setRequestUri($this->request->getRequestUri())->setReferer(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null)->setTimeToLoad($timeToLoad); $em->persist($call); } $em->flush(); }
/** * @param int $publisherId * @param int $divClass * @param array $targets * @param $cacheLifetime * @param Kernel $kernel * @param Connection $conn * @param \Memcached $memcached */ public function __construct($publisherId, $divClass, array $targets, $cacheLifetime, Kernel $kernel, Connection $conn, \Memcached $memcached) { $this->setPublisherId($publisherId); $this->setDivClass($divClass); $this->setTargets($targets); $this->conn = $conn; $this->memcached = $memcached; $this->cacheLifetime = !empty($cacheLifetime) ? $cacheLifetime : self::CacheLifeTime; $this->env = $kernel->getEnvironment(); if ($this->env == 'dev') { $this->enabled = false; } }
/** * Check if given environment is current environment. * * @param string|array $env * * @return bool */ protected function isCurrentEnvironment($env) { return $env === null || $env === $this->kernel->getEnvironment() || is_array($env) && in_array($this->kernel->getEnvironment(), $env); }
/** * Collects information about the Symfony kernel. * * @return Value\SymfonyKernelSystemInfo */ public function collect() { ksort($this->bundles, SORT_FLAG_CASE | SORT_STRING); return new Value\SymfonyKernelSystemInfo(['environment' => $this->kernel->getEnvironment(), 'debugMode' => $this->kernel->isDebug(), 'version' => Kernel::VERSION, 'bundles' => $this->bundles, 'rootDir' => $this->kernel->getRootDir(), 'name' => $this->kernel->getName(), 'cacheDir' => $this->kernel->getCacheDir(), 'logDir' => $this->kernel->getLogDir(), 'charset' => $this->kernel->getCharset()]); }
public function setUpContainer(Kernel $kernel, ContainerInterface $container) { $container->setParameter('foo', $kernel->getEnvironment()); }