/** * Internal method to create the size * @param ImageReferencedElement $entity * @param EntityManager $em */ protected function createImageSize(ImageReferencedElement $entity, EntityManager $em) { $imageId = $entity->getImageId(); $fileStorage = $this->container['cms.file_storage']; /* @var $fileStorage \Supra\Package\Cms\FileStorage\FileStorage */ $image = $fileStorage->findImage($imageId); if ($image === null) { $this->container->getLogger()->warn("Image [{$imageId}] was not found inside the file storage." . " Maybe another file storage must be configured for the image size creator listener?"); return false; } $width = $entity->getWidth(); $height = $entity->getHeight(); // No dimensions if ($width > 0 && $height > 0 || $entity->isCropped()) { if ($entity->isCropped()) { $sizeName = $fileStorage->createImageVariant($image, $width, $height, $entity->getCropLeft(), $entity->getCropTop(), $entity->getCropWidth(), $entity->getCropHeight()); } else { $sizeName = $fileStorage->createResizedImage($image, $width, $height); } $entity->setSizeName($sizeName); // Maybe could update to real width/height inside image metadata? // $size = $image->getImageSize($sizeName); // $entity->setWidth($size->getWidth()); // $entity->setHeight($size->getHeight()); // Recalculate the changeset because of changed size name field $class = $em->getClassMetadata(ImageReferencedElement::CN()); $unitOfWork = $em->getUnitOfWork(); $unitOfWork->recomputeSingleEntityChangeSet($class, $entity); } }
/** * {@inheritDoc} */ public function filter($content, array $options = array()) { if ($this->blockProperty->getMetadata()->offsetExists('link')) { $element = $this->blockProperty->getMetadata()->get('link')->getReferencedElement(); if ($element !== null) { /* @var $element LinkReferencedElement */ if (!$element instanceof LinkReferencedElement) { // @TODO: any exception should be thrown probably return null; } // @TODO: the same code is inside HtmlFilter, should combine somehow. $title = ReferencedElementUtils::getLinkReferencedElementTitle($element, $this->container->getDoctrine()->getManager(), $this->container->getLocaleManager()->getCurrentLocale()); // @TODO: what if we failed to obtain the URL? $url = ReferencedElementUtils::getLinkReferencedElementUrl($element, $this->container->getDoctrine()->getManager(), $this->container->getLocaleManager()->getCurrentLocale()); $tag = new HtmlTag('a', $title ? $title : $url); $tag->setAttribute('title', $title)->setAttribute('href', $url)->setAttribute('class', $element->getClassName()); $target = $element->getTarget(); if (!empty($target)) { $tag->setAttribute('target', $target); } switch ($element->getResource()) { case LinkReferencedElement::RESOURCE_FILE: $tag->setAttribute('target', '_blank'); break; } return $tag; } } return null; }
/** * @param RequestResponseEvent $event */ public function listen(RequestResponseEvent $event) { $context = $this->container->getSecurityContext(); if ($context->getToken() && $context->getToken()->getUser()) { $this->container->getSession()->set($this->container->getParameter('cms_authentication.session.storage_key'), $context->getToken()); } }
public function renderController($name) { //@todo: parameters support $configuration = $this->container->getApplication()->parseControllerName($name); $request = new Request(); $request->attributes->add(array('_controller' => $configuration['controller'], '_action' => $configuration['action'])); return $this->container->getKernel()->handle($request)->getContent(); }
protected function logEvent($name, $event) { //log this into monolog $context = array(); if ($event instanceof RequestResponseEvent) { $context['url'] = $event->getRequest()->getPathInfo(); } $this->container->getLogger()->addDebug(sprintf('Processing event "%s"', $name), $context); }
/** * Gets the source code of a template, given its name. * * @param string $name The name of the template to load * * @return string The template source code * * @throws Twig_Error_Loader When $name is not found */ public function getSource($name) { if (strpos($name, ':') === false) { throw new \Exception(sprintf('Oops, template file name does not seem to be in Package:file\\name\\path.html.twig format ("%s" given")', $name)); } list($packageName, $templatePath) = explode(':', $name); $path = $this->container->getApplication()->locateViewFile($packageName, $templatePath); return file_get_contents($path); }
/** * Called by the DebugBar when data needs to be collected * * @return array Collected data */ public function collect() { $events = $this->container->getEventDispatcher()->getEventTrace(); $dataFormatter = $this->getDataFormatter(); return array_map(function ($value) use($dataFormatter) { $value = array('name' => $value['name'], 'timestamp' => $value['timestamp'], 'listeners' => $value['listeners'], 'event' => $value['event'] ? get_class($value['event']) : 'unknown'); return $dataFormatter->formatVar($value); }, $events); }
protected function execute(InputInterface $input, OutputInterface $output) { $registry = $this->container->getDoctrine(); $em = $registry->getManager($input->getOption('em')); $con = $registry->getConnection($input->getOption('con')); $helperSet = $this->getApplication()->getHelperSet(); $helperSet->set(new EntityManagerHelper($em), 'em'); parent::execute($input, $output); }
/** * Smart fetch from a cache. $prefix and $key are (in most cases) combined yet can be used by cache driver for * sharding. Default can be a scalar value OR callable; it will be called only on cache miss (thus saving you some * code execution). * * Additionally, if $timestamp (last modification timestamp of you cache source) is provided and is newer than * saved by cache driver, cache miss will be considered. * * $respectDebug means that, in debug mode, a cache miss will always be considered, disabled by default. * * Optional $ttl can be specified, although the driver may nor respect it. * * @param string $prefix * @param mixed $key * @param null $default * @param int $timestamp * @param int $ttl * @param bool $respectDebug * @return mixed */ public function fetch($prefix, $key, $default = null, $timestamp = 0, $ttl = 0, $respectDebug = false) { if ($respectDebug && $this->container->getParameter('debug')) { return $this->store($prefix, $key, $default, $timestamp, $ttl); } if ($value = $this->driver->get($prefix, $key, $timestamp)) { return $value; } return $this->store($prefix, $key, $default, $timestamp, $ttl); }
/** * @param RequestResponseEvent $event */ public function listen(RequestResponseEvent $event) { $request = $event->getRequest(); $cmsPrefix = $this->container->getParameter('cms.prefix'); if (strpos($request->getPathInfo(), $cmsPrefix) === 0) { //in any way we should try to extract data from session $session = $this->container->getSession(); $tokenParameter = $this->container->getParameter('cms_authentication.session.storage_key'); $securityContext = $this->container->getSecurityContext(); if ($session->has($tokenParameter)) { $securityContext->setToken($session->get($tokenParameter)); $this->container->getEventDispatcher()->dispatch(AuthController::TOKEN_CHANGE_EVENT, new DataAgnosticEvent()); } //non-authorized users that are not on anonymous paths are getting redirected to login if ((!$securityContext->getToken() || !$securityContext->getToken()->getUser()) && !in_array($request->getPathInfo(), $this->container->getParameter('cms_authentication.paths.anonymous'))) { if ($request->isXmlHttpRequest()) { $event->setResponse(new Response(AuthController::EMPTY_BODY, AuthController::FAILURE_STATUS)); } else { $event->setResponse(new RedirectResponse($this->container->getRouter()->generate('cms_authentication_login'))); } $event->stopPropagation(); } //authorized users on login path are redirected to dashboard if ($securityContext->getToken() && $securityContext->getToken()->getUser() && strpos($request->getPathInfo(), $this->container->getParameter('cms_authentication.paths.login')) === 0) { $event->setResponse(new RedirectResponse($cmsPrefix)); $event->stopPropagation(); } } }
public function listen(RequestResponseEvent $event) { $request = $this->container->getRequest(); $localeManager = $this->container->getLocaleManager(); try { $localeManager->detect($request); $request->setLocale($localeManager->getCurrentLocale()->getId()); } catch (LocaleException $e) { $request->setDefaultLocale($localeManager->getCurrentLocale()->getId()); } }
/** * @return ThemeInterface */ public function getActiveTheme() { if (!$this->container->hasParameter('cms.active_theme')) { throw new \RuntimeException('No active theme set.'); } $themeName = $this->container->getParameter('cms.active_theme'); if (!isset($this->themes[$themeName])) { throw new \InvalidArgumentException("There is no theme [{$themeName}]."); } return $this->themes[$themeName]; }
protected function getUser() { $context = $this->container->getSecurityContext(); if ($context) { $token = $context->getToken(); if ($token) { $user = $token->getUser(); return $user; } } return false; }
/** * Called by the DebugBar when data needs to be collected * * @return array Collected data */ public function collect() { $request = $this->container->getRequest(); if (!$request->hasSession()) { return array('session' => false); } else { $dataFormatter = $this->getDataFormatter(); return array_map(function ($value) use($dataFormatter) { return $dataFormatter->formatVar($value); }, $request->getSession()->all()); } }
public function write($session_id, $session_data) { $entity = $this->container->getDoctrine()->getRepository('Framework:SessionData')->findOneBy(array('sessionId' => $session_id)); if ($entity) { $entity->setData($session_data); $entity->setTimestamp(time()); $this->container->getDoctrine()->getManager()->flush(); } else { $entity = new SessionData(); $entity->setSessionId($session_id); $entity->setData($session_data); $this->container->getDoctrine()->getManager()->persist($entity); $this->container->getDoctrine()->getManager()->flush(); } }
/** * @TODO: should have some BlockBuilder? BlockConfigurationBuilder? instead * * @param Config\BlockConfig $config */ protected function initialize(Config\BlockConfig $config) { $templating = $this->container->getTemplating(); if (!$templating instanceof TwigTemplating) { throw new \RuntimeException('Twig templating engine is required.'); } $config->initialize($templating->getTwig()); }
public function load($file) { if (!is_file($file) || !is_readable($file)) { throw new Exception\ConfigLoaderException(sprintf('File "%s" is not readable or does not exist', $file)); } return $this->container->getCache()->fetch('config', $file, function () use($file) { $info = pathinfo($file); $data = file_get_contents($file); switch (strtolower($info['extension'])) { case 'yml': $data = Yaml::parse($data); break; default: throw new Exception\ConfigLoaderException(sprintf('File "%s" is not supported', $file)); } return $data ? $data : array(); }, filemtime($file)); }
/** * @param AbstractPage $source * @return AbstractPage */ public function copyAbstractPage(AbstractPage $source) { $deepCopy = new DeepCopy(); $entityManager = $this->container->getDoctrine()->getManagerForClass(get_class($source)); $deepCopy->addFilter(new KeepFilter(), new PropertyMatcher(AbstractPage::CN(), 'nestedSetNode')); $this->addDeepCopyCommonFilters($deepCopy, $entityManager); $copiedPage = $deepCopy->copy($source); $entityManager->persist($copiedPage); return $copiedPage; }
/** * {@inheritDoc} * @return string */ public function filter($content, array $options = array()) { $itemTemplate = !empty($options['itemTemplate']) ? (string) $options['itemTemplate'] : ''; $wrapperTemplate = !empty($options['wrapperTemplate']) ? (string) $options['wrapperTemplate'] : ''; $output = ''; $fileStorage = $this->container['cms.file_storage']; /* @var $fileStorage \Supra\Package\Cms\FileStorage\FileStorage */ foreach ($this->blockProperty->getMetadata() as $metadata) { /* @var $metadata \Supra\Package\Cms\Entity\BlockPropertyMetadata */ $element = $metadata->getReferencedElement(); if (!$element instanceof ImageReferencedElement || $element->getSizeName() === null) { continue; } $image = $fileStorage->findImage($element->getImageId()); if ($image === null) { continue; } $previewSize = $image->getImageSize($element->getSizeName()); if ($previewSize === null) { continue; } $previewUrl = $fileStorage->getWebPath($image, $previewSize); $crop = isset($options['fullSizeCrop']) ? (bool) $options['fullSizeCrop'] : true; $fullSizeWidth = !empty($options['fullSizeMaxWidth']) ? (int) $options['fullSizeMaxWidth'] : null; $fullSizeHeight = !empty($options['fullSizeMaxHeight']) ? (int) $options['fullSizeMaxWidth'] : null; try { list($width, $height) = $this->getFullSizeDimensions($image, $fullSizeWidth, $fullSizeHeight, $crop); $fullSizeName = $fileStorage->createResizedImage($image, $width, $height, $crop); } catch (FileStorageException $e) { $this->container->getLogger()->warn($e->getMessage()); continue; } $fullSize = $image->getImageSize($fullSizeName); $fullSizeUrl = $fileStorage->getWebPath($image, $fullSize); $itemData = array('image' => '<img src="' . $previewUrl . '" alt="' . $element->getAlternateText() . '" />', 'imageUrl' => $previewUrl, 'title' => $element->getTitle(), 'description' => $element->getDescription(), 'fullSizeUrl' => $fullSizeUrl, 'fullSizeWidth' => $fullSize->getWidth(), 'fullSizeHeight' => $fullSize->getHeight()); $output .= preg_replace_callback('/{{\\s*(image|title|description|fullSizeUrl|fullSizeWidth|fullSizeHeight)\\s*}}/', function ($matches) use($itemData) { return $itemData[$matches[1]]; }, $itemTemplate); } return preg_replace('/{{\\s*items\\s*}}/', $output, $wrapperTemplate); }
public function finish(ContainerInterface $container) { $container->setParameter('cms_authentication.provider_key', 'cms_authentication'); $container['cms_authentication.users.voters'] = function (ContainerInterface $container) { $voters = array(); foreach ($container->getParameter('cms_authentication.users.voters') as $id) { $voters[] = $container[$id]; } return $voters; }; $container['cms_authentication.users.access_decision_manager'] = function (ContainerInterface $container) { return new AccessDecisionManager($container['cms_authentication.users.voters']); }; $container['cms_authentication.encoder_factory'] = function (ContainerInterface $container) { $encoders = array(); foreach ($container->getParameter('cms_authentication.users.password_encoders') as $user => $encoderClass) { $encoders[$user] = new $encoderClass(); } return new EncoderFactory($encoders); }; $container['cms_authentication.users.authentication_manager'] = function (ContainerInterface $container) { $providers = array(); foreach ($container->getParameter('cms_authentication.users.user_providers') as $type => $providersDefinition) { if ($type != 'doctrine') { throw new \Exception('Only "doctrine" user providers are allowed now'); } foreach ($providersDefinition as $name => $providerDefinition) { $provider = $container->getDoctrine()->getManager($providerDefinition['em'])->getRepository($providerDefinition['entity']); $provider->setDefaultDomain($container->getParameter('cms_authentication.users.default_domain')); $providers[] = $provider; } $chainProvider = new ChainUserProvider($providers); $realProviders = array(new AnonymousAuthenticationProvider(uniqid()), new DaoAuthenticationProvider($chainProvider, new UserChecker(), $container->getParameter('cms_authentication.provider_key'), $container['cms_authentication.encoder_factory'])); return new AuthenticationProviderManager($realProviders); } return new AuthenticationProviderManager($providers); }; $container['security.context'] = function (ContainerInterface $container) { return new SecurityContext($container['cms_authentication.users.authentication_manager'], $container['cms_authentication.users.access_decision_manager']); }; }
/** * Parse supra.image * * @param ImageReferencedElement $imageData * @return null|HtmlTag */ protected function parseSupraImage(ImageReferencedElement $imageData) { $imageId = $imageData->getImageId(); $fileStorage = $this->container['cms.file_storage']; /* @var $fileStorage \Supra\Package\Cms\FileStorage\FileStorage */ $image = $fileStorage->findImage($imageId); if ($image === null) { return null; } $sizeName = $imageData->getSizeName(); $size = $image->findImageSize($sizeName); if ($size === null) { $this->container->getLogger()->warn("Image [{$imageId}] size [{$sizeName}] not found."); return null; } $tag = new HtmlTag('img'); if ($size->isCropped()) { $width = $size->getCropWidth(); $height = $size->getCropHeight(); } else { $width = $size->getWidth(); $height = $size->getHeight(); } $src = $fileStorage->getWebPath($image, $size); $tag->setAttribute('src', $src); $align = $imageData->getAlign(); if (!empty($align)) { if ($align === 'left') { $tag->addClass('pull-left'); } else { if ($align === 'right') { $tag->addClass('pull-right'); } else { if ($align === 'center') { $tag->addClass('center-block'); $tag->setAttribute('style', "width: {$width}px;"); } } } } if (!empty($width)) { $tag->setAttribute('width', $width); } if (!empty($height)) { $tag->setAttribute('height', $height); } $title = trim($imageData->getTitle()); if (!empty($title)) { $tag->setAttribute('title', $title); } $tag->setAttribute('alt', trim($imageData->getAlternateText())); return $tag; }
/** * @param RequestResponseEvent $event */ public function listen(RequestResponseEvent $event) { $path = $event->getRequest()->getPathInfo(); $parts = pathinfo($path); $parts = array_merge(array('dirname' => '', 'basename' => '', 'extension' => '', 'filename'), $parts); switch (strtolower($parts['extension'])) { case 'css': //possible it's not yet compiled less file? $lessFile = $this->container->getApplication()->getWebRoot() . $path . '.less'; if (is_file($lessFile)) { $asset = new FileAsset($lessFile); $asset->ensureFilter(new LessphpFilter()); $content = $this->container->getCache()->fetch('assets_404', $path, function () use($asset) { return $asset->dump(); }, $asset->getLastModified(), 0, true); $event->setResponse(new Response($content, 200, array('Content-Type' => 'text/css'))); $event->stopPropagation(); return; } break; } }
public function getRouteCollection() { //@todo: maybe consider route collection as frozen if ($this->routeCollection) { return $this->routeCollection; } $routeCollection = new RouteCollection(); foreach ($this->routes as $route) { $pattern = $this->container->replaceParametersScalar($route['config']['configuration']['prefix'] . $route['params']['pattern']); $routeObj = new Route($pattern, array_merge($route['config']['configuration']['defaults'], $route['params']['defaults'], array('controller' => $route['params']['controller'])), $route['params']['requirements'], $route['params']['options']); $routeCollection->add($route['name'], $routeObj); } $this->routes = array(); return $this->routeCollection = $routeCollection; }
/** * {@inheritDoc} */ public function transform($value) { $imageDataArray = array(); $fileStorage = $this->getFileStorage(); foreach ($this->property->getMetadata() as $metadata) { /* @var $metadata BlockPropertyMetadata */ $element = $metadata->getReferencedElement(); if (!$element instanceof ImageReferencedElement) { throw new TransformationFailedException(sprintf('Expecting only image referenced elements, [%s] received.', $element ? get_class($element) : 'NULL')); } $image = $fileStorage->findImage($element->getImageId()); if ($image === null) { $this->container->getLogger()->warn("Image [{$element->getImageId()}] not found."); continue; } $imageDataArray[] = array('title' => $element->getTitle(), 'description' => $element->getDescription(), 'image' => array_merge($element->toArray(), array('image' => $fileStorage->getFileInfo($image)))); } return $imageDataArray; }
public function inject(ContainerInterface $container) { if (!$container->getParameter('debug')) { return; } $container[$this->name . '.session_collector'] = function () { return new SessionCollector(); }; $container[$this->name . '.timeline_collector'] = function () { return new TimelineCollector(); }; $container[$this->name . '.event_collector'] = function () { return new EventCollector(); }; $container[$this->name . '.monolog_collector'] = function (ContainerInterface $container) { return new MonologCollector($container->getLogger()); }; $container[$this->name . '.doctrine_collector'] = function (ContainerInterface $container) { $debugStack = new DebugStack(); $container['doctrine.logger']->addLogger($debugStack); return new DoctrineCollector($debugStack); }; $container[$this->name . '.debug_bar'] = function ($container) { $debugBar = new StandardDebugBar(); $debugBar->addCollector($container[$this->name . '.session_collector']); $debugBar->addCollector($container[$this->name . '.doctrine_collector']); $debugBar->addCollector($container[$this->name . '.event_collector']); $debugBar->addCollector($container[$this->name . '.monolog_collector']); return $debugBar; }; $container[$this->name . '.response_listener'] = new DebugBarResponseListener(); $container[$this->name . '.assets_listener'] = new AssetsPublishEventListener(); $container->getEventDispatcher()->addListener(KernelEvent::RESPONSE, array($container[$this->name . '.response_listener'], 'listen')); $container->getEventDispatcher()->addListener(FrameworkConsoleEvent::ASSETS_PUBLISH, array($container[$this->name . '.assets_listener'], 'listen')); //timeline collector binds to many events at once $container->getEventDispatcher()->addSubscriber($container[$this->name . '.timeline_collector']); }
/** * Logs a SQL statement somewhere. * * @param string $sql The SQL to be executed. * @param array $params The SQL parameters. * @param array $types The SQL parameter types. * @return void */ public function startQuery($sql, array $params = null, array $types = null) { $this->container->getLogger()->addDebug(sprintf('DOCTRINE: %s', $sql), $params ? $params : array()); }
protected function fireFileEvent($type, $event) { $this->container->getEventDispatcher()->dispatch($type, $event); }
protected function getCache() { return $this->container->getCache(); }
protected function buildEvents(ContainerInterface $container) { if ($container->getParameter('debug')) { $container['event.dispatcher'] = new TraceableEventDispatcher(); } else { $container['event.dispatcher'] = new EventDispatcher(); } }
/** * @return \Doctrine\Common\Persistence\ObjectManager */ protected function getEntityManager() { return $this->container->getDoctrine()->getManager(); }