Retrieve given request data depending on its content type.

@param Request $request
@param string  $inflection optional inflector to tuse on parameter keys

@return array

@throws HttpException if JSON content-type and invalid JSON data
352427
protected function getRequestData(Request $request, $inflection = 'camelize')
    {
        switch ($request->headers->get('content-type')) {

            case 'application/json':
                if (!($data = @json_decode($request->getContent(), true))
                    && ($error = json_last_error()) != JSON_ERROR_NONE
                ) {
                    throw new HttpException(400, sprintf(
                        'Invalid submitted json data, error %s : %s',
                        $error,
                        json_last_error_msg()
                    ));
                }

                break;
            default:
                $data = array_replace_recursive(
                    $request->request->all(),
                    $request->files->all()
                );
                break;
        }

        // data camel case normalization
        return $inflection && $this->container->has('majora.inflector')?
            $this->container->get('majora.inflector')->normalize($data, $inflection) :
            $data
        ;
    }
209740
public function filter($request)
	{
		foreach($this->_filters as $filter)
		{
			if(!$request = $filter->filter($request))
			{
				throw new Exception("Filter returned a null request");
			}
		}

		return $request;
	}
889881
private function getContentFromRequest(Request $request): array
    {
        $data = json_decode($request->getContent(), true);
        foreach ($data as $key => $value) {
            if ($value === null || $value === '') {
                unset($data[$key]);
            }
        }
        return $data;
    }
1302215
public function cgetAction(Request $request)
    {
        if ('true' == $request->get('flat')) {
            /** @var RestHelperInterface $restHelper */
            $restHelper = $this->get('sulu_core.doctrine_rest_helper');

            /** @var DoctrineListBuilderFactory $factory */
            $factory = $this->get('sulu_core.doctrine_list_builder_factory');

            $tagEntityName = $this->getParameter('sulu.model.tag.class');

            $fieldDescriptors = $this->get('sulu_core.list_builder.field_descriptor_factory')
                ->getFieldDescriptors('tags');
            $listBuilder = $factory->create($tagEntityName);

            $names = array_filter(explode(',', $request->get('names', '')));
            if (count($names) > 0) {
                $listBuilder->in($fieldDescriptors['name'], $names);
            }

            $restHelper->initializeListBuilder($listBuilder, $fieldDescriptors);

            $list = new ListRepresentation(
                $listBuilder->execute(),
                self::$entityKey,
                'get_tags',
                $request->query->all(),
                $listBuilder->getCurrentPage(),
                $listBuilder->getLimit(),
                $listBuilder->count()
            );
            $view = $this->view($list, 200);
        } else {
            $list = new CollectionRepresentation($this->getManager()->findAll(), self::$entityKey);

            $context = new Context();
            $context->setGroups(['partialTag']);
            $view = $this->view($list, 200)->setContext($context);
        }

        return $this->handleView($view);
    }
603765
public function retrieveCurrent(Request $request)
    {
        if (ConfigQuery::isRewritingEnable()) {
            $view = $request->attributes->get('_view', null);

            $viewLocale = $this->getViewLocale($request);

            $viewId = $view === null ? null : $request->query->get($view . '_id', null);

            $allOtherParameters = $request->query->all();
            if ($view !== null) {
                unset($allOtherParameters['view']);
                if ($viewId !== null) {
                    unset($allOtherParameters[$view . '_id']);
                }
            }
            if ($viewLocale !== null) {
                unset($allOtherParameters['lang']);
                unset($allOtherParameters['locale']);
            }

            $this->retriever->loadSpecificUrl($view, $viewLocale, $viewId, $allOtherParameters);
        } else {
            $allParametersWithoutView = $request->query->all();
            $view = $request->attributes->get('_view');
            if (isset($allOtherParameters['view'])) {
                unset($allOtherParameters['view']);
            }
            $this->retriever->rewrittenUrl = null;
            $this->retriever->url = URL::getInstance()->viewUrl($view, $allParametersWithoutView);
        }

        return $this->retriever;
    }
657203
private function isFormRequest(Request $request)
    {
        $contentTypeParts = explode(';', $request->headers->get('Content-Type'));

        if (isset($contentTypeParts[0])) {
            return in_array($contentTypeParts[0], ['multipart/form-data', 'application/x-www-form-urlencoded']);
        }

        return false;
    }
1241512
public function typesAction(Request $request)
    {
        $component = $request->request->get('component');

        $taskTypes = $this->get('phlexible_task.types');

        $types = [];
        foreach ($taskTypes->all() as $type) {
            /* @var $type TypeInterface */
            if ($component && $type->getComponent() !== $component) {
                continue;
            }

            $types[] = [
                'id' => $type->getName(),
                'name' => $type->getName(),
            ];
        }

        return new JsonResponse(['types' => $types]);
    }
1373817
private function getParams(Request $request, array $data = []): array
    {
        // Add default request parameters
        $data = \array_filter($data) + [
                static::PARAM_QUERY => null,
                static::PARAM_VARIABLES => null,
                static::PARAM_OPERATION_NAME => null,
            ];

        // Keep a reference to the query-string
        $qs = $request->query;

        // Override request using query-string parameters
        $query = $qs->has(static::PARAM_QUERY) ? $qs->get(static::PARAM_QUERY) : $data[static::PARAM_QUERY];
        $variables = $qs->has(static::PARAM_VARIABLES) ? $qs->get(static::PARAM_VARIABLES) : $data[static::PARAM_VARIABLES];
        $operationName = $qs->has(static::PARAM_OPERATION_NAME) ? $qs->get(static::PARAM_OPERATION_NAME) : $data[static::PARAM_OPERATION_NAME];

        // `query` parameter is mandatory.
        if (empty($query)) {
            throw new BadRequestHttpException('Must provide query parameter');
        }

        // Variables can be defined using a JSON-encoded object.
        // If the parsing fails, an exception will be thrown.
        if (\is_string($variables)) {
            $variables = \json_decode($variables, true);

            if (\JSON_ERROR_NONE !== \json_last_error()) {
                throw new BadRequestHttpException('Variables are invalid JSON');
            }
        }

        return [
            static::PARAM_QUERY => $query,
            static::PARAM_VARIABLES => $variables,
            static::PARAM_OPERATION_NAME => $operationName,
        ];
    }
287972
public function cgetAction(Request $request)
    {
        $locale = $this->getRequestParameter($request, 'locale', true);

        $restHelper = $this->get('sulu_core.list_rest_helper');

        /** @var Manager $manager */
        $manager = $this->get('es.manager.default');
        $repository = $manager->getRepository($this->get('sulu_article.view_document.factory')->getClass('article'));
        $search = $repository->createSearch();

        $limit = (int) $restHelper->getLimit();
        $page = (int) $restHelper->getPage();

        if (null !== $locale) {
            $search->addQuery(new TermQuery('locale', $locale));
        }

        if (count($ids = array_filter(explode(',', $request->get('ids', ''))))) {
            $search->addQuery(new IdsQuery($this->getViewDocumentIds($ids, $locale)));
            $limit = count($ids);
        }

        if (!empty($searchPattern = $restHelper->getSearchPattern())
            && 0 < count($searchFields = $restHelper->getSearchFields())
        ) {
            $boolQuery = new BoolQuery();
            foreach ($searchFields as $searchField) {
                $boolQuery->add(new MatchPhrasePrefixQuery($searchField, $searchPattern), BoolQuery::SHOULD);
            }
            $search->addQuery($boolQuery);
        }

        if (null !== ($type = $request->get('type'))) {
            $search->addQuery(new TermQuery('type', $type));
        }

        if ($contactId = $request->get('contactId')) {
            $boolQuery = new BoolQuery();
            $boolQuery->add(new MatchQuery('changer_contact_id', $contactId), BoolQuery::SHOULD);
            $boolQuery->add(new MatchQuery('creator_contact_id', $contactId), BoolQuery::SHOULD);
            $boolQuery->add(new MatchQuery('author_id', $contactId), BoolQuery::SHOULD);
            $search->addQuery($boolQuery);
        }

        if ($categoryId = $request->get('categoryId')) {
            $search->addQuery(new TermQuery('excerpt.categories.id', $categoryId), BoolQuery::MUST);
        }

        if ($tagId = $request->get('tagId')) {
            $search->addQuery(new TermQuery('excerpt.tags.id', $tagId), BoolQuery::MUST);
        }

        if ($pageId = $request->get('pageId')) {
            $search->addQuery(new TermQuery('parent_page_uuid', $pageId), BoolQuery::MUST);
        }

        if ($workflowStage = $request->get('workflowStage')) {
            $search->addQuery(new TermQuery('published_state', 'published' === $workflowStage), BoolQuery::MUST);
        }

        if ($this->getBooleanRequestParameter($request, 'exclude-shadows', false, false)) {
            $search->addQuery(new TermQuery('localization_state.state', 'shadow'), BoolQuery::MUST_NOT);
        }

        if ($this->getBooleanRequestParameter($request, 'exclude-ghosts', false, false)) {
            $search->addQuery(new TermQuery('localization_state.state', 'ghost'), BoolQuery::MUST_NOT);
        }

        $authoredFrom = $request->get('authoredFrom');
        $authoredTo = $request->get('authoredTo');
        if ($authoredFrom || $authoredTo) {
            $search->addQuery($this->getRangeQuery('authored', $authoredFrom, $authoredTo), BoolQuery::MUST);
        }

        if (null === $search->getQueries()) {
            $search->addQuery(new MatchAllQuery());
        }

        if (null !== $restHelper->getSortColumn() &&
            $sortField = $this->getSortFieldName($restHelper->getSortColumn())
        ) {
            $search->addSort(
                new FieldSort($sortField, $restHelper->getSortOrder())
            );
        }

        $fieldDescriptors = $this->getFieldDescriptors();

        if ($limit) {
            $search->setSize($limit);
            $search->setFrom(($page - 1) * $limit);

            $fields = array_merge(
                $restHelper->getFields() ?: [],
                ['id', 'localizationState', 'publishedState', 'published']
            );
            $fieldDescriptors = array_filter(
                $fieldDescriptors,
                function (FieldDescriptorInterface $fieldDescriptor) use ($fields) {
                    return in_array($fieldDescriptor->getName(), $fields);
                }
            );
        } else {
            $search->setSize(1000);
            $search->setScroll('1m');
        }

        $searchResult = $repository->findRaw($search);
        $result = [];
        foreach ($searchResult as $document) {
            $documentData = $this->normalize($document['_source'], $fieldDescriptors);
            if (false !== ($index = array_search($documentData['id'], $ids))) {
                $result[$index] = $documentData;
            } else {
                $result[] = $documentData;
            }
        }

        if (count($ids)) {
            ksort($result);
            $result = array_values($result);
        }

        $count = $searchResult->count();

        return $this->handleView(
            $this->view(
                new ListRepresentation(
                    $result,
                    'articles',
                    'get_articles',
                    $request->query->all(),
                    $page,
                    $limit,
                    $count
                )
            )
        );
    }
1318815
protected function getTypeFromRequestBody(array &$request_body)
    {
        $type_class = $this->getTypeClassName();

        if (isset($request_body['type'])) {
            $type_class = $request_body['type'];
            unset($request_body['type']);
        }

        if (class_exists($type_class)) {
            $type_class_reflection = new ReflectionClass($type_class);

            if ($type_class_reflection->isSubclassOf($this->getTypeClassName()) && !$type_class_reflection->isAbstract()) {
                return $type_class;
            }
        }

        throw new InvalidArgumentException('Please specify a valid type');
    }
799386
private function getValuesFromRequest(Request $request)
    {
        $values = array_merge($request->query->all(), $request->request->all());
        $contentValues = json_decode($request->getContent(), true);
        if (is_array($contentValues)) {
            $values = array_merge($values, $contentValues);
        }

        return $values;
    }
885989
public function indexAction(Request $request)
    {
        $id = $request->get('id');
        $version = $request->get('version');
        $mode = $request->get('mode', 'edit');

        $elementtypeService = $this->get('phlexible_elementtype.elementtype_service');

        $elementtype = $elementtypeService->findElementtype($id);
        $elementtypeStructure = $elementtype->getStructure();

        $rootNode = $elementtypeStructure->getRootNode();
        $type = $elementtype->getType(); // != 'reference' ? 'root' : 'referenceroot';

        $children = [];
        $rootDsId = '';
        $rootType = 'root';
        if ($rootNode) {
            $rootDsId = $rootNode->getDsId();
            $rootType = $rootNode->getType();
            $children = $elementtypeStructure->getChildNodes($rootNode->getDsId());
        }

        $language = $this->getUser()->getInterfaceLanguage('en');
        if (!$language) {
            $language = 'en';
        }

        $data = [
            [
                'text' => $elementtype->getTitle($language)
                    .' [v'.$elementtype->getRevision().', '
                    .$elementtype->getType().']',
                'id' => md5(serialize($rootNode)),
                'ds_id' => $rootDsId,
                'element_type_id' => $elementtype->getId(),
                'element_type_version' => $elementtype->getRevision(),
                'icon' => '/bundles/phlexibleelementtype/elementtypes/'.$elementtype->getIcon(),
                'cls' => 'p-elementtypes-type-'.$type,
                'leaf' => false,
                'expanded' => true,
                'type' => $rootType,
                'allowDrag' => ($type === Elementtype::TYPE_REFERENCE),
                'allowDrop' => $mode === 'edit',
                'editable' => $mode === 'edit',
                'properties' => [
                    'root' => [
                        'title' => $elementtype->getTitle($language),
                        'reference_title' => $elementtype->getTitle($language)
                            .' [v'.$elementtype->getRevision().']',
                        'unique_id' => $elementtype->getUniqueId(),
                        'icon' => $elementtype->getIcon(),
                        'hide_children' => $elementtype->getHideChildren() ? 'on' : '',
                        'default_tab' => $elementtype->getDefaultTab(),
                        'default_content_tab' => $elementtype->getDefaultContentTab(),
                        'type' => $type,
                        'template' => $elementtype->getTemplate(),
                        'metaset' => $elementtype->getMetaSetId(),
                        'comment' => $elementtype->getComment(),
                    ],
                    'mappings' => $elementtype->getMappings(),
                ],
                'children' => $this->recurseTree(
                    $elementtypeStructure,
                    $children,
                    $language,
                    $mode,
                    false,
                    true
                ),
            ],
        ];

        return new JsonResponse($data);
    }
687187
protected function parseRequest(ServerRequestInterface $request): array
    {
        $method = $request->getMethod();
        if (!\in_array($method, ['PUT', 'POST', 'PATCH'])) {
            throw new \RuntimeException(sprintf('FlexForm: Bad HTTP method %s', $method));
        }

        $body = $request->getParsedBody();
        $data = isset($body['data']) ? $this->decodeData($body['data']) : null;

        $flash = $this->getFlash();
        /*
        if (null !== $data) {
            $flash->setData($data);
            $flash->save();
        }
        */

        $blueprint = $this->getBlueprint();
        $includeOriginal = (bool)($blueprint->form()['images']['original'] ?? null);
        $files = $flash->getFilesByFields($includeOriginal);

        $data = $blueprint->processForm($data ?? [], $body['toggleable_data'] ?? []);

        return [
            $data,
            $files ?? []
        ];
    }
213072
public function getAction(Request $request)
    {
        $structureProvider = $this->get('sulu.content.structure_manager');
        $type = $request->get('type', 'default');

        $templates = [];
        foreach ($structureProvider->getStructures('article') as $structure) {
            if ($this->getType($structure->getStructure()) !== $type) {
                continue;
            }

            $templates[] = [
                'internal' => $structure->getInternal(),
                'template' => $structure->getKey(),
                'title' => $structure->getLocalizedTitle($this->getUser()->getLocale()),
            ];
        }

        return new JsonResponse(
            [
                '_embedded' => $templates,
                'total' => count($templates),
            ]
        );
    }
154492
private function input(ServerRequestInterface $request): array
    {
        if (! is_null($this->parser)) {

            $input = ($this->parser)($request);

            if (is_array($input)) {

                return $input;

            }

            throw new InputTypeException($input);

        }

        return array_merge(
            $request->getAttributes(),
            $request->getQueryParams(),
            $request->getParsedBody(),
            $request->getUploadedFiles()
        );
    }
521932
private function preVerifyContentType(RequestInterface $request, $retryWithUrlEncodingDisabled = null)
    {
        $configuration = $this->getConfiguration();

        try {
            $response = $configuration->getHttpClient()->send($request);
        } catch (BadResponseException $badResponseException) {
            if (is_null($retryWithUrlEncodingDisabled) && $configuration->getRetryWithUrlEncodingDisabled()) {
                $retryWithUrlEncodingDisabled = true;
            }

            if ($retryWithUrlEncodingDisabled) {
                return $this->preVerifyContentType($this->deEncodeRequestUrl($request), false);
            }

            $response = $badResponseException->getResponse();
        }

        if (!$this->isSuccessResponse($response)) {
            return null;
        }

        $contentType = $this->getContentTypeFromResponse($response);

        $hasMappedWebResourceClassName = $configuration->hasMappedWebResourceClassName(
            $contentType->getTypeSubtypeString()
        );

        if (!$hasMappedWebResourceClassName && !$configuration->getAllowUnknownResourceTypes()) {
            throw new InvalidContentTypeException($contentType, $response, $request);
        }

        return true;
    }
680629
protected function getContentTypeHeader(Request $request): ContentType
	{
		$headerName = 'Content-Type';
		if (!$request->hasHeader($headerName))
		{
			throw new Exception\BadRequest('Content-Type header should be declared');
		}
		if (count($request->getHeader($headerName)) > 1)
		{
			throw new Exception\BadRequest('Multiple Content-Type headers are not allowed');
		}
		try
		{
			return ContentType::fromString($headerName . ': ' . $request->getHeaderLine($headerName));
		}
		catch (\Exception $e)
		{
			throw new Exception\BadRequest('Invalid Content-Type header', $e);
		}
	}