/** * @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()); }
/** * 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 getFilters() { $client = new \Mleko\ImageSqueeze\Client\Client(); $squeeze = new \Twig_SimpleFilter('squeeze', function ($path) use($client) { $path = (string) $path; if (strlen($path) > 0 && $path[0] === '@') { $path = $this->kernel->locateResource($path); } if (file_exists($path)) { $inputFile = new \Mleko\ImageSqueeze\Client\File($path); } else { $inputFile = new \Mleko\ImageSqueeze\Client\File($path, $this->webRoot); } $pathHash = str_pad(base_convert(sha1($path), 16, 36), 31, '0', STR_PAD_LEFT); $compressedName = implode("/", str_split(substr($pathHash, 0, 6), 1)) . "/" . substr($pathHash, 6); if (false !== ($dotPosition = strrpos($path, "."))) { $compressedName .= substr($path, $dotPosition); } $newPath = '/cache/image/' . $compressedName; $fullPath = $this->webRoot . $newPath; if (!file_exists($fullPath)) { $newDir = dirname($fullPath); if (!file_exists($newDir)) { mkdir($newDir, 0777, true); } return $client->shrink($inputFile)->toFile($newPath, $this->webRoot); } return new \Mleko\ImageSqueeze\Client\File($newPath, $this->webRoot); }); return ['squeeze' => $squeeze]; }
/** * Generate PDF-file of ticket * * @param string $html HTML to generate pdf * @param string $outputFile Name of output file * * @return mixed */ public function generatePdfFile($html, $outputFile) { // Override default fonts directory for mPDF define('_MPDF_SYSTEM_TTFONTS', realpath($this->kernel->getRootDir() . '/../web/fonts/open-sans/') . '/'); /** @var \TFox\MpdfPortBundle\Service\MpdfService $mPDFService */ $mPDFService = $this->container->get('tfox.mpdfport'); $mPDFService->setAddDefaultConstructorArgs(false); $constructorArgs = array('mode' => 'BLANK', 'format' => 'A5-L', 'margin_left' => 0, 'margin_right' => 0, 'margin_top' => 0, 'margin_bottom' => 0, 'margin_header' => 0, 'margin_footer' => 0); $mPDF = $mPDFService->getMpdf($constructorArgs); // Open Sans font settings $mPDF->fontdata['opensans'] = array('R' => 'OpenSans-Regular.ttf', 'B' => 'OpenSans-Bold.ttf', 'I' => 'OpenSans-Italic.ttf', 'BI' => 'OpenSans-BoldItalic.ttf'); $mPDF->sans_fonts[] = 'opensans'; $mPDF->available_unifonts[] = 'opensans'; $mPDF->available_unifonts[] = 'opensansI'; $mPDF->available_unifonts[] = 'opensansB'; $mPDF->available_unifonts[] = 'opensansBI'; $mPDF->default_available_fonts[] = 'opensans'; $mPDF->default_available_fonts[] = 'opensansI'; $mPDF->default_available_fonts[] = 'opensansB'; $mPDF->default_available_fonts[] = 'opensansBI'; $mPDF->SetDisplayMode('fullpage'); $mPDF->WriteHTML($html); $pdfFile = $mPDF->Output($outputFile, 'S'); return $pdfFile; }
private function resolvePath($file) { if (isset($this->config['aliases'][$file]['path'])) { return $this->kernel->getRootDir() . '/../web/' . $this->config['aliases'][$file]['path']; } return $file; }
/** * @before */ public function setUpDatabase() { if (isset($_SERVER['IS_DOCTRINE_ORM_SUPPORTED']) && $_SERVER['IS_DOCTRINE_ORM_SUPPORTED']) { $this->entityManager = static::$sharedKernel->getContainer()->get('doctrine.orm.entity_manager'); $this->purgeDatabase(); } }
/** * {@inheritdoc} */ public function locate($resource, GeneratorInterface $generator) { $bundles = $this->kernel->getBundles(); $class = get_class($generator); $appResources = $this->kernel->getContainer()->getParameter('kernel.root_dir') . '/Resources/'; $location = "skeleton/{$generator->getName()}/{$resource}"; /** @var Bundle $bundle */ foreach ($bundles as $bundle) { if (strpos($class, $bundle->getNamespace()) !== false) { $global = "{$appResources}/{$bundle->getName()}/{$location}"; if (file_exists($global) && is_readable($global)) { return $global; } else { $local = "{$bundle->getPath()}/Resources/{$location}"; if (file_exists($local) && is_readable($local)) { return $local; } else { throw new ResourceNotFoundException("Resource {$resource} could not be located for generator {$generator->getName()}"); } } } } $nonBundle = "{$appResources}{$location}"; if (file_exists($nonBundle) && is_readable($nonBundle)) { return $nonBundle; } throw new ResourceNotFoundException("Resource {$resource} could not be located for generator {$generator->getName()}"); }
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']); } }
/** * Load the generators confirming to default naming rules in all bundles in the given Kernel. * @param Kernel $kernel */ public function loadBundleGenerators(Kernel $kernel) { /** @var Bundle $bundle */ foreach ($kernel->getBundles() as $bundle) { $this->loadGeneratorsForBundle($bundle); } }
/** * {@inheritdoc} */ public function handleRequest(RequestInterface $request) { $symfonyRequest = $request->getHttpFoundationRequest(); $symfonyResponse = $this->kernel->handle($symfonyRequest); $this->kernel->terminate($symfonyRequest, $symfonyResponse); return $symfonyResponse; }
/** * @author Krzysztof Bednarczyk * @return string[] */ public function findWebsocketClasses() { $dirs = array(); foreach ($this->kernel->getBundles() as $bundle) { if (in_array($bundle->getName(), $this->blackListedBundles)) { continue; } if (!is_dir($websocketDir = $bundle->getPath() . '/Websocket')) { continue; } $dirs[] = $websocketDir; } foreach (Finder::create()->name('*Websocket.php')->in($dirs)->files() as $file) { $filename = $file->getRealPath(); if (!in_array($filename, $this->blackListedWebsocketFiles)) { require_once $filename; } } // It is not so important if these controllers never can be reached with // the current configuration nor whether they are actually controllers. // Important is only that we do not miss any classes. return array_filter(get_declared_classes(), function ($name) { return preg_match('/Websocket\\\\(.+)Websocket$/', $name) > 0; }); }
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 bool $loaded * @param Kernel $kernel * @param string $pluginName */ private function pluginIs($loaded, Kernel $kernel, $pluginName) { $this->assertSame($loaded, $kernel->getContainer()->hasParameter($pluginName . '.loaded')); $this->assertSame($loaded, $kernel->getContainer()->hasParameter($pluginName . '.build_was_called')); if ($kernel->getContainer()->has($pluginName . 'boot')) { $this->assertSame($loaded, $kernel->getContainer()->get($pluginName . '.boot')->wasCalled()); } }
public function getClassName($path) { $srcDir = realpath(sprintf('%s/../src', $this->kernel->getRootDir())); $className = substr($path, strlen($srcDir) + 1); $className = str_replace('/', '\\', $className); $className = str_replace('.php', '', $className); return $className; }
protected function copyTemplates() { $from = $this->kernel->locateResource('@AnimeDbCatalogBundle/Resources/views/'); $to = $this->root_dir . '/Resources/'; // overwrite twig error templates $this->fs->copy($from . 'errors/error.html.twig', $to . 'TwigBundle/views/Exception/error.html.twig', true); $this->fs->copy($from . 'errors/error404.html.twig', $to . 'TwigBundle/views/Exception/error404.html.twig', true); }
/** * @param string $filePath * @param \Symfony\Component\HttpFoundation\ServerBag $server * * @return bool */ private function authenticate($filePath, ServerBag $server) { $passFile = $this->kernel->getRootDir() . '/../web/var/export/' . substr($filePath, 0, strrpos($filePath, '/')) . '/.htpasswd'; list($auth['user'], $auth['pass']) = explode(':', file_get_contents($passFile)); $user = $server->get('PHP_AUTH_USER'); $pass = crypt($server->get('PHP_AUTH_PW'), md5($server->get('PHP_AUTH_PW'))); return $user == $auth['user'] && $pass == $auth['pass']; }
/** * Rename for local development by removing underscores. */ public function _____testSimpleException() { $request = $this->buildRequest(); $exception = new \RuntimeException('Hello', 404, new \InvalidArgumentException('Invalid argument, or something', 500)); $exception = FlattenException::create($exception); $context = array('a' => 'b', 'c' => array('x' => 'y', array('t' => 'q'))); $body = $this->_kernel->getContainer()->get('templating')->render('EhoughEmailErrorsBundle::mail.html.twig', array('exception' => $exception, 'request' => $request, 'context' => $context, 'status_text' => Response::$statusTexts[$exception->getStatusCode()])); file_put_contents('/tmp/out.txt', $body); }
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); } }
public function let(IntentDocumentGeneratedEvent $event, RumGeneratorInterface $rumGenerator, Intent $intent, Kernel $kernel) { $this->event = $event; $this->rumGenerator = $rumGenerator; $this->intent = $intent; $this->kernel = $kernel; $this->event->getIntent()->willReturn($this->intent); $kernel->locateResource('@DonatePaymentBundle/Resources/public/img/sepa-template.jpg')->willReturn(__DIR__ . '/test.jpg'); $this->beConstructedWith($rumGenerator, $kernel); }
/** * CommandValidator constructor. * * @param Kernel $kernel */ public function __construct(Kernel $kernel) { $this->_kernel = $kernel; $this->_app = new Application($kernel); foreach ($kernel->getBundles() as $bundle) { if ($bundle instanceof Bundle) { $bundle->registerCommands($this->_app); } } }
/** * Constructor. */ public function __construct(Kernel $kernel) { $this->kernel = $kernel; parent::__construct('Symfony', Kernel::VERSION . ' - ' . $kernel->getName()); $this->definition->addOption(new InputOption('--shell', '-s', InputOption::PARAMETER_NONE, 'Launch the shell.')); if (!$this->kernel->isBooted()) { $this->kernel->boot(); } $this->registerCommands(); }
/** * @covers ::load */ public function testService() { $container = $this->kernel->getContainer(); $salvaAsseticFilter = $container->getParameter('salva_assetic_filter.jshrink.class'); $salvaTwigExtension = $container->getParameter('salva_twig_extension.jshrink.class'); $this->assertTrue($container->has('salva_assetic_filter.jshrink')); $this->assertTrue($container->has('salva_twig_extension.jshrink')); $this->assertInstanceOf($salvaAsseticFilter, $container->get('salva_assetic_filter.jshrink')); $this->assertInstanceOf($salvaTwigExtension, $container->get('salva_twig_extension.jshrink')); }
/** * @param Kernel $kernel * @return array */ protected function getUserBundles(Kernel $kernel) { $bundles = []; /** @var Bundle $bundle */ foreach ($kernel->getBundles() as $bundle) { if (strpos($bundle->getPath(), 'vendor') === false) { $bundles[] = $bundle; } } return $bundles; }
/** * @param null $filter * @return array|BundleInterface[] */ public function getBundles($filter = null) { $bundles = $this->kernel->getBundles(); $filterFunction = function (Bundle $bundle) use($filter) { return strpos($bundle->getName(), $filter) !== false; }; if (!$filter) { return $bundles; } else { return array_filter($bundles, $filterFunction); } }
/** * PostManager constructor. * * @param Kernel $kernel * @param RequestStack $requestStack */ public function __construct(Kernel $kernel, RequestStack $requestStack) { $this->kernel = $kernel; $this->file = $kernel->getCacheDir() . DIRECTORY_SEPARATOR . 'api_bundle_posts'; $this->request = $requestStack->getCurrentRequest(); if (!file_exists($this->file)) { $fs = new Filesystem(); $fs->touch($this->file); file_put_contents($this->file, serialize(array())); } $this->data = unserialize(file_get_contents($this->file)); }
public function replay(Request $baseRequest, Notification $notification) { $webHook = $notification->getWebHook(); $endpoint = $webHook->getEndpoint(); $content = json_decode($notification->getContent(), true); $query = array_merge(['username' => $webHook->getUser()->getUsername(), 'endpoint' => $endpoint], $content['query']); $url = $this->router->generate('notifications', $query); $request = Request::create($url, $content['method'], [], [], [], $baseRequest->server->all(), $content['body']); $request->headers->replace($content['headers']); $response = $this->kernel->handle($request, HttpKernelInterface::SUB_REQUEST); return $response; }
/** * @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 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; } }
/** * @param $filename * @return array */ public function getResource($filename) { $builder = new PathBuilder($this->resourcesDir); $fullPath = $builder->getResourcesPath($this->kernel->getRootDir(), $filename); $role = $builder->getRoleFromPath($fullPath); if ($role != null && false === $this->securityContext->isGranted($role)) { throw new AccessDeniedException(); } if (!file_exists($fullPath)) { throw new FileNotFoundException(sprintf("The file %s was not found", $filename)); } $contentType = MimeType::get($filename); return ['contentType' => $contentType, 'content' => file_get_contents($fullPath)]; }
private function configurePheal(Kernel $kernel, $userAgent, LoggerInterface $logger) { $config = Config::getInstance(); $cacheDir = $kernel->getCacheDir() . '/pheal/'; if (!is_dir($cacheDir)) { if (false === @mkdir($cacheDir, 0777, true)) { throw new \RuntimeException(sprintf('Could not create cache directory "%s".', $cacheDir)); } } $config->cache = new HashedNameFileStorage($cacheDir); $config->access = new StaticCheck(); $config->rateLimiter = new FileLockRateLimiter($cacheDir); $config->log = new PsrLogger($logger); $config->http_user_agent = $userAgent; }