/**
  * Handle the request stack
  */
 protected function handleRequestStack()
 {
     $currentRequest = $this->requestStack->getCurrentRequest();
     if ($currentRequest) {
         $this->add('request.locale', $currentRequest->getLocale());
     }
 }
 /**
  * @param $instance
  * @return array
  */
 public function getConfiguration($instance)
 {
     $request = $this->requestStack->getCurrentRequest();
     $efParameters = $this->parameters;
     $parameters = $efParameters['instances'][$instance];
     $options = array();
     $options['corsSupport'] = $parameters['cors_support'];
     $options['debug'] = $parameters['connector']['debug'];
     $options['bind'] = $parameters['connector']['binds'];
     $options['plugins'] = $parameters['connector']['plugins'];
     $options['roots'] = array();
     foreach ($parameters['connector']['roots'] as $parameter) {
         $path = $parameter['path'];
         $homeFolder = $this->container->get('security.token_storage')->getToken()->getUser()->getUsername();
         //            var_dump($path.$homeFolder);
         $driver = $this->container->has($parameter['driver']) ? $this->container->get($parameter['driver']) : null;
         $driverOptions = array('driver' => $parameter['driver'], 'service' => $driver, 'glideURL' => $parameter['glide_url'], 'glideKey' => $parameter['glide_key'], 'plugin' => $parameter['plugins'], 'path' => $path . '/' . $homeFolder, 'startPath' => $parameter['start_path'], 'URL' => $this->getURL($parameter, $request, $homeFolder, $path), 'alias' => $parameter['alias'], 'mimeDetect' => $parameter['mime_detect'], 'mimefile' => $parameter['mimefile'], 'imgLib' => $parameter['img_lib'], 'tmbPath' => $parameter['tmb_path'], 'tmbPathMode' => $parameter['tmb_path_mode'], 'tmbUrl' => $parameter['tmb_url'], 'tmbSize' => $parameter['tmb_size'], 'tmbCrop' => $parameter['tmb_crop'], 'tmbBgColor' => $parameter['tmb_bg_color'], 'copyOverwrite' => $parameter['copy_overwrite'], 'copyJoin' => $parameter['copy_join'], 'copyFrom' => $parameter['copy_from'], 'copyTo' => $parameter['copy_to'], 'uploadOverwrite' => $parameter['upload_overwrite'], 'uploadAllow' => $parameter['upload_allow'], 'uploadDeny' => $parameter['upload_deny'], 'uploadMaxSize' => $parameter['upload_max_size'], 'defaults' => $parameter['defaults'], 'attributes' => $parameter['attributes'], 'acceptedName' => $parameter['accepted_name'], 'disabled' => $parameter['disabled_commands'], 'treeDeep' => $parameter['tree_deep'], 'checkSubfolders' => $parameter['check_subfolders'], 'separator' => $parameter['separator'], 'timeFormat' => $parameter['time_format'], 'archiveMimes' => $parameter['archive_mimes'], 'archivers' => $parameter['archivers']);
         if (!$parameter['show_hidden']) {
             $driverOptions['accessControl'] = array($this, 'access');
         }
         if ($parameter['driver'] == 'Flysystem') {
             $driverOptions['filesystem'] = $filesystem;
         }
         $options['roots'][] = array_merge($driverOptions, $this->configureDriver($parameter));
     }
     return $options;
 }
 /**
  * @return array The Render Array
  */
 public function search()
 {
     $formSubmitted = $this->currentRequest->getCurrentRequest()->get('search-button');
     $queryString = $this->currentRequest->getCurrentRequest()->get('search-value');
     $currentPage = $this->currentRequest->getCurrentRequest()->get('search-page');
     if (!isset($currentPage) || empty($currentPage)) {
         $currentPage = 1;
     }
     if (!isset($formSubmitted) || empty($formSubmitted) || $formSubmitted != SearchResultsController::FORM_SUBMITTED_VALUE || !isset($queryString) || empty($queryString)) {
         return ['#type' => 'markup', '#markup' => $this->t("No Search was performed")];
     }
     $config = $this->config('google_site_search.settings');
     $key = $config->get('google_site_search_key');
     $index = $config->get('google_site_search_index');
     if (empty($key) || !isset($key) || empty($index) || !isset($index)) {
         return ['#type' => 'markup', '#markup' => $this->t("The google site search is not configured correctly")];
     }
     /* @var $gssService \Drupal\google_site_search\GoogleSiteSearchSearch */
     $gssService = \Drupal::service('google_site_search.search');
     $currentLanguage = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
     $results = $gssService->getSearchResults($currentLanguage, $queryString, $key, $index, $currentPage);
     // check for errors or no results
     if ($results instanceof TranslatableMarkup || !isset($results['items']) || count($results['items']) === 0) {
         return ['#theme' => 'google_no_search_results', '#title' => t('No Search Results'), '#content' => ['query' => $queryString]];
     }
     return ['#theme' => 'google_search_results', '#title' => t('Search Results'), '#content' => ['items' => $results['items'], 'total' => $results['queries']['request'][0]['totalResults'], 'count' => $results['queries']['request'][0]['count'], 'start' => ($currentPage - 1) * 10 + 1, 'nextPage' => isset($results['queries']['nextPage']) ? $currentPage + 1 : 0, 'prevPage' => isset($results['queries']['prevPage']) ? $currentPage - 1 : 0, 'query' => $queryString], '#cache' => ['contexts' => $this->getCacheContexts()]];
 }
 /**
  * @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);
 }
 /**
  * @param $page
  *
  * @return string
  */
 protected function getUriForPage($page)
 {
     $request = $this->requestStack->getCurrentRequest();
     $request->query->set('page', $page);
     $query = urldecode(http_build_query($request->query->all()));
     return $request->getSchemeAndHttpHost() . $request->getBaseUrl() . $request->getPathInfo() . '?' . $query;
 }
示例#6
0
 protected function prepareRequest(array $params)
 {
     // Get action
     $action = $this->popParameter($params, "action");
     // Then get and filter query, request and method
     $query = $this->popParameter($params, "query");
     $query = $this->filterArrayStrParam($query);
     $request = $this->popParameter($params, "request");
     $request = $this->filterArrayStrParam($request);
     $method = strtoupper($this->popParameter($params, "method", "GET"));
     // Then build the request
     $requestObject = clone $this->requestStack->getCurrentRequest();
     $requestObject->query = new ParameterBag($query);
     $requestObject->request = new ParameterBag($request);
     $requestObject->attributes = new ParameterBag(["_controller" => $action]);
     // Apply the method
     if (!empty($request) && "GET" === $method) {
         $requestObject->setMethod("POST");
     } else {
         $requestObject->setMethod($method);
     }
     // Then all the attribute parameters
     foreach ($params as $key => $attribute) {
         $requestObject->attributes->set($key, $attribute);
     }
     return $requestObject;
 }
 /**
  * @param  string                $name
  * @param  string                $type
  * @param  array                 $data
  * @param  array                 $options
  * @return \Thelia\Form\BaseForm
  */
 public function createForm($name, $type = "form", array $data = array(), array $options = array())
 {
     if (!isset($this->formDefinition[$name])) {
         throw new \OutOfBoundsException(sprintf("The form '%s' doesn't exist", $name));
     }
     return new $this->formDefinition[$name]($this->requestStack->getCurrentRequest(), $type, $data, $options, $this->container);
 }
 /**
  * {@inheritdoc}
  */
 public function createDocument(array $options = [])
 {
     $document = new PdfDocument();
     $params = $this->params;
     $request = $this->requestStack->getCurrentRequest();
     $document->setOptions($this->getWkHtmlToPdfOptions($request->getUri(), $params['pdf_wkhtmltopdf_bin']));
     $document->outputSelector(function () use($request) {
         return $request->query->get('do');
     });
     $head = $document->element('head');
     $bootstrap = new HtmlElement('link');
     $bootstrap->attr('rel', 'stylesheet');
     $bootstrap->attr('type', 'text/css');
     $bootstrap->attr('href', $request->getSchemeAndHttpHost() . $this->appPaths->url("web") . '/pdf/css/bootstrap.min.css');
     $bootstrap->insertTo($head);
     $style = new HtmlElement('link');
     $style->attr('rel', 'stylesheet');
     $style->attr('type', 'text/css');
     $style->attr('href', $request->getSchemeAndHttpHost() . $this->appPaths->url("web") . '/pdf/css/pdf.css');
     $style->insertTo($head);
     $filename = $this->appPaths->getRootDir() . '/../pdf/' . $request->getPathInfo();
     $dir = dirname($filename);
     if (!is_dir($dir)) {
         mkdir($dir, 0755, true);
     }
     $document->setFilename($filename);
     return $document;
 }
 public function configureOptions(OptionsResolver $resolver)
 {
     $locale = $this->requestStack->getCurrentRequest()->getLocale();
     $resolver->setDefaults(array('class' => 'ChillActivityBundle:ActivityReasonCategory', 'property' => 'name[' . $locale . ']', 'query_builder' => function (EntityRepository $er) {
         return $er->createQueryBuilder('c')->where('c.active = true');
     }));
 }
示例#10
0
 /**
  * {@inheritdoc}
  */
 public function log($level, $message, array $context = array())
 {
     if ($this->callDepth == self::MAX_CALL_DEPTH) {
         return;
     }
     $this->callDepth++;
     // Merge in defaults.
     $context += array('channel' => $this->channel, 'link' => '', 'user' => NULL, 'uid' => 0, 'request_uri' => '', 'referer' => '', 'ip' => '', 'timestamp' => time());
     // Some context values are only available when in a request context.
     if ($this->requestStack && ($request = $this->requestStack->getCurrentRequest())) {
         $context['request_uri'] = $request->getUri();
         $context['referer'] = $request->headers->get('Referer', '');
         $context['ip'] = $request->getClientIP();
         try {
             if ($this->currentUser) {
                 $context['user'] = $this->currentUser;
                 $context['uid'] = $this->currentUser->id();
             }
         } catch (\Exception $e) {
             // An exception might be thrown if the database connection is not
             // available or due to another unexpected reason. It is more important
             // to log the error that we already have so any additional exceptions
             // are ignored.
         }
     }
     if (is_string($level)) {
         // Convert to integer equivalent for consistency with RFC 5424.
         $level = $this->levelTranslation[$level];
     }
     // Call all available loggers.
     foreach ($this->sortLoggers() as $logger) {
         $logger->log($level, $message, $context);
     }
     $this->callDepth--;
 }
示例#11
0
文件: Canonical.php 项目: bolt/bolt
 /**
  * Returns the canonical url for the current request,
  * or null if called outside of the request cycle.
  *
  * @return string|null
  */
 public function getUrl()
 {
     if (($request = $this->requestStack->getCurrentRequest()) === null) {
         return null;
     }
     return $this->urlGenerator->generate($request->attributes->get('_route'), $request->attributes->get('_route_params'), UrlGeneratorInterface::ABSOLUTE_URL);
 }
示例#12
0
 /**
  * Process theliaModule template inclusion function
  *
  * This function accepts two parameters:
  *
  * - location : this is the location in the admin template. Example: folder-edit'. The function will search for
  *   AdminIncludes/<location>.html file, and fetch it as a Smarty template.
  * - countvar : this is the name of a template variable where the number of found modules includes will be assigned.
  *
  * @param array                     $params
  * @param \Smarty_Internal_Template $template
  * @internal param \Thelia\Core\Template\Smarty\Plugins\unknown $smarty
  *
  * @return string
  */
 public function theliaModule($params, \Smarty_Internal_Template $template)
 {
     $content = null;
     $count = 0;
     if (false !== ($location = $this->getParam($params, 'location', false))) {
         if ($this->debug === true && $this->requestStack->getCurrentRequest()->get('SHOW_INCLUDE')) {
             echo sprintf('<div style="background-color: #C82D26; color: #fff; border-color: #000000; border: solid;">%s</div>', $location);
         }
         $moduleLimit = $this->getParam($params, 'module', null);
         $modules = ModuleQuery::getActivated();
         /** @var \Thelia\Model\Module $module */
         foreach ($modules as $module) {
             if (null !== $moduleLimit && $moduleLimit != $module->getCode()) {
                 continue;
             }
             $file = $module->getAbsoluteAdminIncludesPath() . DS . $location . '.html';
             if (file_exists($file)) {
                 $output = trim(file_get_contents($file));
                 if (!empty($output)) {
                     $content .= $output;
                     $count++;
                 }
             }
         }
     }
     if (false !== ($countvarname = $this->getParam($params, 'countvar', false))) {
         $template->assign($countvarname, $count);
     }
     if (!empty($content)) {
         return $template->fetch(sprintf("string:%s", $content));
     }
     return "";
 }
 /**
  * __construct
  * @param RequestStack $requestStack
  * @return void
  **/
 public function __construct(RequestStack $requestStack)
 {
     $scheme = $requestStack->getCurrentRequest()->getScheme();
     $host = $requestStack->getCurrentRequest()->getHost();
     $port = $requestStack->getCurrentRequest()->getPort();
     $this->u2f = new \u2flib_server\U2F($scheme . '://' . $host . (80 !== $port && 443 !== $port ? ':' . $port : ''));
 }
示例#14
0
 /**
  * Returns formatted and translated date.
  *
  * @param string $route   The route of the current link
  * @param string $classes Classes of the current element
  *
  * @return string The attribute of the element
  */
 public function localeDate($date, $formatType = null, $timezone = null)
 {
     $request = $this->requestStack->getCurrentRequest();
     $locale = $request->get('_locale');
     $localeFormats = $this->localesConfig[$locale];
     if (null === $formatType || !isset($localeFormats[$formatType])) {
         $result = twig_date_format_filter($this->twig, $date, null, $timezone);
     } else {
         $format = $localeFormats[$formatType];
         if (!preg_match('/[DlMF]/', $format)) {
             $result = twig_date_format_filter($this->twig, $date, $format, $timezone);
         } else {
             $pattern = '/[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/';
             $length = mb_strlen($format, 'UTF-8');
             $result = '';
             for ($i = 0; $i < $length; $i++) {
                 $symbol = mb_substr($format, $i, 1, 'UTF-8');
                 if (preg_match($pattern, $symbol)) {
                     $value = twig_date_format_filter($this->twig, $date, $symbol, $timezone);
                     if (preg_match('/[DlMF]/', $symbol)) {
                         $value = $this->translator->trans($value);
                     }
                 } else {
                     $value = $symbol;
                 }
                 $result .= $value;
             }
         }
     }
     return $result;
 }
示例#15
0
 /**
  * {@inheritdoc}
  */
 public function validateForm($form_id, &$form, FormStateInterface &$form_state)
 {
     // If this form is flagged to always validate, ensure that previous runs of
     // validation are ignored.
     if (!empty($form_state['must_validate'])) {
         $form_state['validation_complete'] = FALSE;
     }
     // If this form has completed validation, do not validate again.
     if (!empty($form_state['validation_complete'])) {
         return;
     }
     // If the session token was set by self::prepareForm(), ensure that it
     // matches the current user's session.
     if (isset($form['#token'])) {
         if (!$this->csrfToken->validate($form_state['values']['form_token'], $form['#token'])) {
             $url = $this->requestStack->getCurrentRequest()->getRequestUri();
             // Setting this error will cause the form to fail validation.
             $form_state->setErrorByName('form_token', $this->t('The form has become outdated. Copy any unsaved work in the form below and then <a href="@link">reload this page</a>.', array('@link' => $url)));
             // Stop here and don't run any further validation handlers, because they
             // could invoke non-safe operations which opens the door for CSRF
             // vulnerabilities.
             $this->finalizeValidation($form, $form_state, $form_id);
             return;
         }
     }
     // Recursively validate each form element.
     $this->doValidateForm($form, $form_state, $form_id);
     $this->finalizeValidation($form, $form_state, $form_id);
     $this->handleErrorsWithLimitedValidation($form, $form_state, $form_id);
 }
 /**
  * Adds in the current user as a context.
  *
  * @param \Drupal\page_manager\Event\PageManagerContextEvent $event
  *   The page entity context event.
  */
 public function onPageContext(PageManagerContextEvent $event)
 {
     $request = $this->requestStack->getCurrentRequest();
     $page = $event->getPage();
     $routes = $this->routeProvider->getRoutesByPattern($page->getPath())->all();
     $route = reset($routes);
     if ($route && ($route_contexts = $route->getOption('parameters'))) {
         foreach ($route_contexts as $route_context_name => $route_context) {
             // Skip this parameter.
             if ($route_context_name == 'page_manager_page_variant' || $route_context_name == 'page_manager_page') {
                 continue;
             }
             $context_name = $this->t('{@name} from route', ['@name' => $route_context_name]);
             if ($request->attributes->has($route_context_name)) {
                 $value = $request->attributes->get($route_context_name);
             } else {
                 // @todo Find a way to add in a fake value for configuration.
                 $value = NULL;
             }
             $cacheability = new CacheableMetadata();
             $cacheability->setCacheContexts(['route']);
             $context = new Context(new ContextDefinition($route_context['type'], $context_name, FALSE), $value);
             $context->addCacheableDependency($cacheability);
             $page->addContext($route_context_name, $context);
         }
     }
 }
示例#17
0
 public function processRecord(array $record)
 {
     $request = $this->requestStack->getCurrentRequest();
     if ($request) {
         $record['http'] = ['url' => sprintf('[%s] [%s]', $request->getMethod(), $request->getRequestUri())];
         if (count($request->query->all())) {
             $record['http']['get'] = $request->query->all();
         }
         if (count($request->request->all())) {
             $record['http']['post'] = $request->request->all();
         }
         $content = $request->getContent();
         if ($content) {
             if (strlen($content) < 1024) {
                 $record['http']['json'] = json_decode($content, true);
             } else {
                 $record['http']['json'] = $this->s3Uploader->uploadString('json-params', $content);
             }
         }
         if (isset($_SERVER['REMOTE_ADDR'])) {
             $record['http']['ip'] = $_SERVER['REMOTE_ADDR'];
         }
         if (isset($_SERVER['HTTP_X_USER_AGENT'])) {
             $record['http']['userAgent'] = $_SERVER['HTTP_X_USER_AGENT'];
         } elseif (isset($_SERVER['HTTP_USER_AGENT'])) {
             $record['http']['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
         }
     }
     if (php_sapi_name() == 'cli') {
         if (!empty($_SERVER['argv'])) {
             $record['cliCommand'] = implode(' ', $_SERVER['argv']);
         }
     }
     return $record;
 }
 /**
  * {@inheritdoc}
  */
 public function getLocale()
 {
     if ($request = $this->requestStack->getCurrentRequest()) {
         return $request->getLocale();
     }
     return $this->defaultLocale;
 }
 /**
  * Extract the route object from the request if one is available.
  *
  * @return \Symfony\Component\Routing\Route
  *   The route object extracted from the current request.
  */
 protected function getRouteFromRequest()
 {
     $request = $this->requestStack->getCurrentRequest();
     if ($request) {
         return $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT);
     }
 }
示例#20
0
 private function getRemoteRequestToken()
 {
     if (!$this->requestStack->getCurrentRequest()) {
         return null;
     }
     return $this->requestStack->getCurrentRequest()->headers->get('X-Remote-Request-Token');
 }
 /**
  * @param StatefulInterface $object
  * @return TokenReadInterface[]
  */
 public function getTokens(StatefulInterface $object)
 {
     $request = $this->stack->getCurrentRequest();
     $process = $request->attributes->get($this->processPath, null, true);
     $stateMachine = $this->factory->create($process, $object);
     return $stateMachine->getTokens();
 }
示例#22
0
 /**
  * {@inheritdoc}
  */
 public function resolveForPreview($webspaceKey, $locale)
 {
     // take first portal url
     $portalInformation = $this->webspaceManager->getPortalInformations($this->environment);
     $portalUrl = array_keys($portalInformation)[0];
     return ['request' => ['webspaceKey' => $webspaceKey, 'locale' => $locale, 'defaultLocale' => $locale, 'portalUrl' => $portalUrl, 'resourceLocatorPrefix' => '', 'resourceLocator' => '', 'get' => $this->requestStack->getCurrentRequest()->query->all(), 'post' => $this->requestStack->getCurrentRequest()->request->all(), 'analyticsKey' => $this->previewDefaults['analyticsKey']]];
 }
示例#23
0
 /**
  * {@inheritdoc}
  */
 public function apply(ResourceInterface $resource, QueryBuilder $queryBuilder)
 {
     $request = $this->requestStack->getCurrentRequest();
     if (null === $request) {
         return;
     }
     foreach ($this->extractProperties($request) as $property => $values) {
         // Expect $values to be an array having the period as keys and the date value as values
         if (!$this->isPropertyEnabled($property) || !$this->isPropertyMapped($property, $resource) || !$this->isDateField($property, $resource) || !is_array($values)) {
             continue;
         }
         $alias = 'o';
         $field = $property;
         if ($this->isPropertyNested($property)) {
             $propertyParts = $this->splitPropertyParts($property);
             $parentAlias = $alias;
             foreach ($propertyParts['associations'] as $association) {
                 $alias = QueryNameGenerator::generateJoinAlias($association);
                 $queryBuilder->join(sprintf('%s.%s', $parentAlias, $association), $alias);
                 $parentAlias = $alias;
             }
             $field = $propertyParts['field'];
         }
         $nullManagement = isset($this->properties[$property]) ? $this->properties[$property] : null;
         if (self::EXCLUDE_NULL === $nullManagement) {
             $queryBuilder->andWhere($queryBuilder->expr()->isNotNull(sprintf('%s.%s', $alias, $field)));
         }
         if (isset($values[self::PARAMETER_BEFORE])) {
             $this->addWhere($queryBuilder, $alias, $field, self::PARAMETER_BEFORE, $values[self::PARAMETER_BEFORE], $nullManagement);
         }
         if (isset($values[self::PARAMETER_AFTER])) {
             $this->addWhere($queryBuilder, $alias, $field, self::PARAMETER_AFTER, $values[self::PARAMETER_AFTER], $nullManagement);
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     // Mock a logger.
     $this->logger = $this->prophesize(LoggerInterface::class);
     // Mock the logger service, make it return our mocked logger, and register
     // it in the container.
     $this->loggerFactory = $this->prophesize(LoggerChannelFactoryInterface::class);
     $this->loggerFactory->get('rules')->willReturn($this->logger->reveal());
     $this->container->set('logger.factory', $this->loggerFactory->reveal());
     // Mock a parameter bag.
     $this->parameterBag = $this->prophesize(ParameterBag::class);
     // Mock a request, and set our mocked parameter bag as it attributes
     // property.
     $this->currentRequest = $this->prophesize(Request::class);
     $this->currentRequest->attributes = $this->parameterBag->reveal();
     // Mock the request stack, make it return our mocked request when the
     // current request is requested, and register it in the container.
     $this->requestStack = $this->prophesize(RequestStack::class);
     $this->requestStack->getCurrentRequest()->willReturn($this->currentRequest);
     $this->container->set('request_stack', $this->requestStack->reveal());
     // Mock the current path stack.
     $this->currentPathStack = $this->prophesize(CurrentPathStack::class);
     $this->container->set('path.current', $this->currentPathStack->reveal());
     // Instantiate the redirect action.
     $this->action = $this->actionManager->createInstance('rules_page_redirect');
 }
示例#25
0
 /**
  * {@inheritdoc}
  *
  * Orders collection by properties. The order of the ordered properties is the same as the order specified in the
  * query.
  * For each property passed, if the resource does not have such property or if the order value is different from
  * `asc` or `desc` (case insensitive), the property is ignored.
  */
 public function apply(ResourceInterface $resource, QueryBuilder $queryBuilder)
 {
     $request = $this->requestStack->getCurrentRequest();
     if (null === $request) {
         return;
     }
     $properties = $this->extractProperties($request);
     foreach ($properties as $property => $order) {
         if (!$this->isPropertyEnabled($property) || !$this->isPropertyMapped($property, $resource)) {
             continue;
         }
         if (empty($order) && isset($this->properties[$property])) {
             $order = $this->properties[$property];
         }
         $order = strtoupper($order);
         if (!in_array($order, ['ASC', 'DESC'])) {
             continue;
         }
         $alias = 'o';
         $field = $property;
         if ($this->isPropertyNested($property)) {
             $propertyParts = $this->splitPropertyParts($property);
             $parentAlias = $alias;
             foreach ($propertyParts['associations'] as $association) {
                 $alias = QueryNameGenerator::generateJoinAlias($association);
                 $queryBuilder->leftJoin(sprintf('%s.%s', $parentAlias, $association), $alias);
                 $parentAlias = $alias;
             }
             $field = $propertyParts['field'];
         }
         $queryBuilder->addOrderBy(sprintf('%s.%s', $alias, $field), $order);
     }
 }
 /**
  * @return Request
  * @throws \LogicException
  */
 private function getRequest()
 {
     $request = $this->requestStack->getCurrentRequest();
     if (null === $request) {
         throw new \LogicException('Request should exist so it can be processed for error.');
     }
     return $request;
 }
 /**
  * Updates the record with the request identifier.
  *
  * @param array $record
  *
  * @return array
  */
 public function __invoke(array $record)
 {
     if (null === ($request = $this->requestStack->getCurrentRequest())) {
         return $record;
     }
     $record['context']['tags'] = ['request-identifier' => (string) $this->requestIdentifierResolver->resolve($request)];
     return $record;
 }
 /**
  * Get current locale. If request is null, take the default locale defined in config
  *
  * @return string
  */
 public function getCurrentLocale()
 {
     $request = $this->requestStack->getCurrentRequest();
     if (null === $request) {
         return $this->defaultLocale;
     }
     return $request->getLocale();
 }
示例#29
0
 /**
  * Returns the base url of a convention
  *
  *
  * @param Convention $convention
  * @return string
  */
 public function conventionURL(Convention $convention)
 {
     $request = $this->requestStack->getCurrentRequest();
     $domain = $convention->getDomain();
     $url = str_replace('http://', '', $request->getUri());
     $url_complete = "http://" . $domain . "." . $url;
     return $url_complete;
 }
示例#30
0
 /**
  * {@inheritdoc}
  */
 public function isAllowed($name, $threshold, $window = 3600, $identifier = NULL)
 {
     if (!isset($identifier)) {
         $identifier = $this->requestStack->getCurrentRequest()->getClientIp();
     }
     $number = $this->connection->select('flood', 'f')->condition('event', $name)->condition('identifier', $identifier)->condition('timestamp', REQUEST_TIME - $window, '>')->countQuery()->execute()->fetchField();
     return $number < $threshold;
 }