Load element data.

@param Request $request

@return JsonResponse
@Route("/load", name="elements_data_load")
341021
public function loadAction(Request $request)
    {
        $treeId = (int) $request->get('id');
        $teaserId = (int) $request->get('teaser_id');
        $language = $request->get('language');
        $version = $request->get('version');
        $unlockId = $request->get('unlock');
        $doLock = (bool) $request->get('lock', false);

        $diff = $request->get('diff');
        $diffVersionFrom = (int) $request->get('diff_version_from');
        $diffVersionTo = (int) $request->get('diff_version_to');
        $diffLanguage = $request->get('diff_language');

        $teaserManager = $this->get('phlexible_teaser.teaser_manager');
        $treeManager = $this->get('phlexible_tree.tree_manager');
        $elementService = $this->get('phlexible_element.element_service');
        $iconResolver = $this->get('phlexible_element.icon_resolver');
        $elementHistoryManager = $this->get('phlexible_element.element_history_manager');
        $lockManager = $this->get('phlexible_element.element_lock_manager');
        $userManager = $this->get('phlexible_user.user_manager');
        $authorizationChecker = $this->get('security.authorization_checker');
        $linkFetcher = $this->get('phlexible_element.link_fetcher');

        $teaser = null;
        if ($teaserId) {
            $teaser = $teaserManager->find($teaserId);
            $eid = $teaser->getTypeId();
            $treeId = $teaser->getTreeId();
            $tree = $treeManager->getByNodeId($treeId);
            $node = $tree->get($treeId);
        } elseif ($treeId) {
            $tree = $treeManager->getByNodeId($treeId);
            $node = $tree->get($treeId);
            $eid = $node->getTypeId();
        } else {
            throw new InvalidArgumentException('Unknown data requested.');
        }

        $element = $elementService->findElement($eid);
        $elementMasterLanguage = $element->getMasterLanguage();

        if (!$language) {
            $language = $elementMasterLanguage;
        }

        if ($teaser) {
            $isPublished = $teaserManager->isPublished($teaser, $language);
            $onlineVersion = $teaserManager->getPublishedVersion($teaser, $language);
        } elseif ($treeId) {
            $isPublished = $tree->isPublished($node, $language);
            $onlineVersion = $tree->getPublishedVersion($node, $language);
        } else {
            throw new InvalidArgumentException('Unknown data requested.');
        }

        if ($version) {
            $elementVersion = $elementService->findElementVersion($element, $version);
        } else {
            $elementVersion = $elementService->findLatestElementVersion($element);
        }

        $elementStructure = $elementService->findElementStructure($elementVersion, $language);

        $elementtype = $elementService->findElementtype($element);
        $elementtypeStructure = $elementtype->getStructure();
        $type = $elementtype->getType();

        // versions

        if ($teaser) {
            $publishedVersions = $elementHistoryManager->findBy(
                [
                    'teaserId' => $teaser->getId(),
                    'action' => 'publishTeaser',
                ]
            );
        } else {
            $publishedVersions = $elementHistoryManager->findBy(
                [
                    'treeId' => $node->getId(),
                    'action' => 'publishNode',
                ]
            );
        }

        $versions = [];
        foreach ($elementService->findElementVersions($element, array('version' => 'DESC')) as $version) {
            $versions[$version->getVersion()] = [
                'version' => $version->getVersion(),
                'format' => 2,
                'create_date' => $version->getCreatedAt()->format('Y-m-d H:i:s'),
                'is_published' => false,
                'was_published' => false,
            ];
        }

        foreach ($publishedVersions as $publishedVersion) {
            if (!isset($versions[$publishedVersion->getVersion()])) {
                continue;
            }
            $versions[$publishedVersion->getVersion()]['online'] = true;
            if ($publishedVersion->getVersion() === $onlineVersion) {
                $versions[$publishedVersion->getVersion()]['is_published'] = true;
            } else {
                $versions[$publishedVersion->getVersion()]['was_published'] = true;
            }
        }

        $versions = array_values($versions);

        // instances

        $instances = [];
        if ($teaser) {
            foreach ($teaserManager->getInstances($teaser) as $instanceTeaser) {
                $instance = [
                    'id' => $instanceTeaser->getId(),
                    'instance_master' => false,
                    'modify_time' => $instanceTeaser->getCreatedAt()->format('Y-m-d H:i:s'),
                    'icon' => $iconResolver->resolveTeaser($instanceTeaser, $language),
                    'type' => 'teaser',
                    'link' => [],
                ];

                $instances[] = $instance;
            }
        } else {
            foreach ($treeManager->getInstanceNodes($node) as $instanceNode) {
                $instance = [
                    'id' => $instanceNode->getId(),
                    'instance_master' => false,
                    'modify_time' => $instanceNode->getCreatedAt()->format('Y-m-d H:i:s'),
                    'icon' => $iconResolver->resolveTreeNode($instanceNode, $language),
                    'type' => 'treenode',
                    'link' => [],
                ];

                if ($instanceNode->getTree()->getSiterootId() !== $tree->getSiterootId()) {
                    $instance['link'] = [
                        'start_tid_path' => '/'.implode('/', $instanceNode->getTree()->getIdPath($instanceNode)),
                    ];
                }

                $instances[] = $instance;
            }
        }

        // allowed child elements

        $allowedChildren = [];
        if (!$teaser) {
            foreach ($elementService->findAllowedChildren($elementtype) as $childElementtype) {
                if ($childElementtype->getType() !== 'full') {
                    continue;
                }

                $allowedChildren[] = [
                    $childElementtype->getId(),
                    $childElementtype->getTitle(),
                    $iconResolver->resolveElementtype($childElementtype),
                ];
            }
        }

        // diff

        if ($diff && $diffVersionFrom) {
            $fromElementVersion = $elementService->findElementVersion($element, $diffVersionFrom);
            $fromElementStructure = $elementService->findElementStructure($fromElementVersion, $diffLanguage);

            if ($diffVersionTo) {
                $toElementVersion = $elementService->findElementVersion($element, $diffVersionTo);
                $toElementStructure = $elementService->findElementStructure($toElementVersion, $diffLanguage);
            } else {
                $toElementStructure = $elementStructure;
            }

            if ($fromElementStructure !== $toElementStructure) {
                $differ = new Differ();
                $differ->diff($fromElementStructure, $toElementStructure);
            }

            $elementStructure = $fromElementStructure;
        }

        $diffInfo = null;
        if ($diff) {
            $diffInfo = [
                'enabled' => $diff,
                'version_from' => $diffVersionFrom,
                'version_to' => $diffVersionTo,
                'language' => $diffLanguage,
            ];
        }

        // lock

        if ($unlockId !== null) {
            $unlockElement = $elementService->findElement($unlockId);
            if ($unlockElement && $lockManager->isLockedByUser($unlockElement, $this->getUser()->getId())) {
                try {
                    $lockManager->unlock($unlockElement, $this->getUser()->getId());
                } catch (\Exception $e) {
                    // unlock failed
                }
            }
        }

        if ($node instanceof DomainObjectInterface) {
            if (!$authorizationChecker->isGranted('ROLE_SUPER_ADMIN') &&
                !$authorizationChecker->isGranted(['permission' => 'EDIT', 'language' => $language], $node)
            ) {
                $doLock = false;
            }
        }

        $lock = null;
        if ($doLock && !$diff) {
            if (!$lockManager->isLockedByOtherUser($element, $this->getUser()->getId())) {
                $lock = $lockManager->lock($element, $this->getUser()->getId());
            }
        }

        if (!$lock) {
            $lock = $lockManager->findLock($element);
        }

        $lockInfo = null;

        if ($lock && !$diff) {
            $lockUser = $userManager->find($lock->getUserId());

            $lockInfo = [
                'status' => 'locked',
                'id' => $lock->getElement()->getEid(),
                'username' => $lockUser->getDisplayName(),
                'time' => $lock->getLockedAt()->format('Y-m-d H:i:s'),
                'age' => time() - $lock->getLockedAt()->format('U'),
                'type' => $lock->getType(),
            ];

            if ($lock->getUserId() === $this->getUser()->getId()) {
                $lockInfo['status'] = 'edit';
            } elseif ($lock->getType() === ElementLock::TYPE_PERMANENTLY) {
                $lockInfo['status'] = 'locked_permanently';
            }
        } elseif ($diff) {
            // Workaround for loading diffs without locking and view-mask
            // TODO: introduce new diff lock mode

            $lockInfo = [
                'status' => 'edit',
                'id' => '',
                'username' => '',
                'time' => '',
                'age' => 0,
                'type' => ElementLock::TYPE_TEMPORARY,
            ];
        }

        // meta

        $meta = [];
        $elementMetaSetResolver = $this->get('phlexible_element.element_meta_set_resolver');
        $elementMetaDataManager = $this->get('phlexible_element.element_meta_data_manager');
        $optionResolver = $this->get('phlexible_meta_set.option_resolver');
        $metaSetId = $elementtype->getMetaSetId();

        if ($metaSetId) {
            $metaSet = $elementMetaSetResolver->resolve($elementVersion);
            $metaData = $elementMetaDataManager->findByMetaSetAndElementVersion($metaSet, $elementVersion);

            $fieldDatas = [];

            foreach ($metaSet->getFields() as $field) {
                $options = $optionResolver->resolve($field);

                $fieldData = [
                    'key' => $field->getName(),
                    'type' => $field->getType(),
                    'options' => $options,
                    'readonly' => $field->isReadonly(),
                    'required' => $field->isRequired(),
                    'synchronized' => $field->isSynchronized(),
                ];

                if ($metaData) {
                    foreach ($metaData->getLanguages() as $metaLanguage) {
                        if ($language === $metaLanguage) {
                            $fieldData['value'] = $metaData->get($field->getName(), $language);
                            break;
                        }
                    }
                }

                $fieldDatas[] = $fieldData;
            }

            $meta = [
                'set_id' => $metaSetId,
                'title' => $metaSet->getName(),
                'fields' => $fieldDatas,
            ];
        }

        // redirects
        // TODO: auslagern

        $redirects = [];
        if (!$teaser && $this->container->has('redirectsManager')) {
            $redirectsManager = $this->get('redirectsManager');
            $redirects = $redirectsManager->getForTidAndLanguage($treeId, $language);
        }

        // preview / online url

        $urls = [
            'preview' => '',
            'online' => '',
        ];

        $publishDate = null;
        $publishUser = null;
        $onlineVersion = null;
        $latestVersion = null;

        if (in_array($elementtype->getType(), [Elementtype::TYPE_FULL, Elementtype::TYPE_STRUCTURE, Elementtype::TYPE_PART])) {
            if ($type === Elementtype::TYPE_FULL || $type === Elementtype::TYPE_PART) {
                $nodeUrlGenerator = $this->get('phlexible_tree.node_url_generator');
                $urls['preview'] = $nodeUrlGenerator->generatePreviewUrl($node, $language);

                if ($isPublished) {
                    $urls['online'] = $nodeUrlGenerator->generateOnlineUrl($node, $language);
                }
            }

            if ($isPublished) {
                if ($teaser) {
                    $teaserOnline = $teaserManager->findOneOnlineByTeaserAndLanguage($teaser, $language);
                    $publishDate = $teaserOnline->getPublishedAt()->format('Y-m-d H:i:s');
                    $publishUser = $userManager->find($teaserOnline->getPublishUserId());
                    $onlineVersion = $teaserOnline->getVersion();
                } else {
                    $treeNodeOnline = $tree->findOneOnlineByTreeNodeAndLanguage($node, $language);
                    $publishDate = $treeNodeOnline->getPublishedAt()->format('Y-m-d H:i:s');
                    $publishUser = $userManager->find($treeNodeOnline->getPublishUserId());
                    $onlineVersion = $treeNodeOnline->getVersion();
                }
            }

            $latestVersion = $element->getLatestVersion();
        }

        // configuration

        if ($teaser) {
            $configuration = $teaser->getAttributes();
        } else {
            $configuration = $node->getAttributes();
            $configuration['navigation'] = $node->getInNavigation() ? true : false;
        }

        // context
        // TODO: repair element context

        $context = [];
        if (0) {
            $contextManager = $this->get('phlexible_element.context.manager');

            if ($contextManager->useContext()) {
                $contextCountries = $contextManager->getAllCountries();

                $activeContextCountries = $teaserId
                    ? $contextManager->getActiveCountriesByTeaserId($teaserId)
                    : $contextManager->getActiveCountriesByTid($node->getId());

                foreach ($contextCountries as $contextKey => $contextValue) {
                    $context[] = [
                        'id' => $contextKey,
                        'country' => $contextValue,
                        'active' => in_array($contextKey, $activeContextCountries) ? 1 : 0,
                    ];
                }
            }
        }

        // pager

        $pager = [];
        if (!$teaser) {
            $parentNode = $tree->getParent($node);
            if ($parentNode) {
                $parentElement = $elementService->findElement($parentNode->getTypeId());
                $parentElementtype = $elementService->findElementtype($parentElement);
                if ($parentElementtype->getHideChildren()) {
                    $filter = new TreeFilter(
                        $this->get('doctrine.dbal.default_connection'),
                        $request->getSession(),
                        $this->get('event_dispatcher'),
                        $parentNode->getId(),
                        $language
                    );
                    $pager = $filter->getPager($node->getId());
                }
            }
        }

        // rights

        $permissionResolver = $this->get('phlexible_tree.node_permission_resolver');
        $tokenStorage = $this->get('security.token_storage');

        $userRights = $permissionResolver->resolve($node, $language, $tokenStorage->getToken());
        if ($userRights === null) {
            return new JsonResponse(array('success' => false, 'message' => 'no permission'));
        }

        // state

        $status = '';
        if ($teaser) {
            $stateManager = $this->get('phlexible_teaser.state_manager');
            if ($stateManager->isPublished($teaser, $language)) {
                $status = $stateManager->isAsync($teaser, $language) ? 'async' : 'online';
            }
        } else {
            $stateManager = $this->get('phlexible_tree.state_manager');
            if ($stateManager->isPublished($node, $language)) {
                $status = $stateManager->isAsync($node, $language) ? 'async' : 'online';
            }
        }

        $icon = $iconResolver->resolveTreeNode($node, $language);

        $createUser = $userManager->find($elementVersion->getCreateUserId());

        // glue together

        $properties = [
            'tid' => $treeId,
            'eid' => $eid,
            'siteroot_id' => empty($teaserId) ? $node->getTree()->getSiterootId() : null,
            'teaser_id' => $teaserId,
            'language' => $language,
            'version' => $elementVersion->getVersion(),
            'is_published' => $isPublished,
            'master' => $language === $element->getMasterLanguage() ? true : false,
            'status' => $status,
            'backend_title' => mb_substr(
                strip_tags($elementVersion->getBackendTitle($language, $elementMasterLanguage)),
                0,
                30,
                'UTF-8'
            ),
            'page_title' => mb_substr(
                strip_tags($elementVersion->getPageTitle($language, $elementMasterLanguage)),
                0,
                30,
                'UTF-8'
            ),
            'navigation_title' => mb_substr(
                strip_tags($elementVersion->getNavigationTitle($language, $elementMasterLanguage)),
                0,
                30,
                'UTF-8'
            ),
            'unique_id' => $element->getUniqueID(),
            'et_id' => $elementtype->getId(),
            'et_title' => $elementtype->getTitle(),
            'et_version' => $elementVersion->getElementTypeVersion().' ['.$elementtype->getRevision().']',
            'et_unique_id' => $elementtype->getUniqueId(),
            'et_type' => $elementtype->getType(),
            'author' => $createUser ? $createUser->getDisplayName() : 'Unknown',
            'create_date' => $elementVersion->getCreatedAt()->format('Y-m-d H:i:s'),
            'publish_date' => $publishDate,
            'publisher' => $publishUser ? $publishUser->getDisplayName() : null,
            'latest_version' => (int) $latestVersion,
            'online_version' => (int) $onlineVersion,
            'masterlanguage' => $elementMasterLanguage,
            'sort_mode' => $node->getSortMode(),
            'sort_dir' => $node->getSortDir(),
            'icon' => $icon,
            'navigation' => $node->getInNavigation(),
        ];

        $elementtypeSerializer = new ElementtypeArraySerializer();
        $serializedStructure = $elementtypeSerializer->serialize($elementtypeStructure);

        $elementSerializer = new ElementArraySerializer();
        $serializedValues = $elementSerializer->serialize($elementStructure, $language, $element->getMasterLanguage());

        $links = $linkFetcher->fetch($elementVersion, $language);

        $data = [
            'success' => true,
            'properties' => $properties,
            'configuration' => $configuration,
            'comment' => $elementVersion->getComment(),
            'meta' => $meta,
            'redirects' => $redirects,
            'default_tab' => $elementtype->getDefaultTab(),
            'default_content_tab' => $elementtype->getDefaultContentTab(),
            'lockinfo' => $lockInfo,
            'diff' => $diffInfo,
            'urls' => $urls,
            'context' => $context,
            'pager' => $pager,
            'rights' => $userRights,
            'instances' => $instances,
            'children' => $allowedChildren,
            'versions' => $versions,
            'valueStructure' => $serializedValues,
            'structure' => $serializedStructure,
            'links' => $links,
        ];

        $data = (object) $data;
        $event = new LoadDataEvent($node, $teaser, $language, $data);
        $this->get('event_dispatcher')->dispatch(ElementEvents::LOAD_DATA, $event);
        $data = (array) $data;

        return new JsonResponse($data);
    }
1212225
public function referenceAction(Request $request)
    {
        $siterootId = $request->get('siteroot_id');
        $tid = $request->get('node');
        $language = $request->get('language');

        $treeManager = $this->get('phlexible_tree.tree_manager');
        $elementService = $this->get('phlexible_element.element_service');
        $translator = $this->get('translator');
        $teaserManager = $this->get('phlexible_teaser.teaser_manager');
        $elementSourceManager = $this->get('phlexible_element.element_source_manager');
        $nodeSerializer = $this->get('phlexible_tree.node_serializer');
        $iconResolver = $this->get('phlexible_element.icon_resolver');

        $tree = $treeManager->getBySiteRootId($siterootId);

        $treeNode = $tree->get($tid);
        $rootNode = $tree->getRoot();

        $data = [];
        if ($rootNode !== null) {
            if ($tid === null || $tid < 1) {
                $data = [$nodeSerializer->serializeNode($rootNode, $language)];

                return new JsonResponse($data);
            }

            $node = $tree->get($tid);

            // check if children of this node should be shown
            $element = $elementService->findElement($node->getTypeId());
            $elementtype = $elementService->findElementtype($element);

            $nodes = $tree->getChildren($node);
            if (!empty($nodes) && !$elementtype->getHideChildren()) {
                $data = $nodeSerializer->serializeNodes($nodes, $language);
            }

            foreach ($data as $key => $row) {
                if ($row['leaf']) {
                    unset($data[$key]);
                    continue;
                }
                $data[$key]['cls'] = (!empty($data[$key]['cls']) ? $data[$key]['cls'].' ' : '').'node-disabled';
            }
        }

        $currentTreeId = $tid;

        $element = $elementService->findElement($treeNode->getTypeId());
        $elementtype = $elementService->findElementtype($element);

        $layoutareas = [];
        // TODO: repair
        foreach ($elementSourceManager->findElementtypesByType('layout') as $layoutarea) {
            if (in_array($elementtype, $elementService->findAllowedParents($layoutarea))) {
                $layoutareas[] = $layoutarea;
            }
        }

        foreach ($layoutareas as $layoutarea) {
            $areaRoot = [
                'id' => 'area_'.$layoutarea->getId(),
                'area_id' => $layoutarea->getId(),
                'parent_tid' => $currentTreeId,
                'parent_eid' => $element->getEid(),
                'icon' => $iconResolver->resolveElementtype($layoutarea),
                'text' => $layoutarea->getTitle(),
                'type' => 'area',
                'inherited' => null, //true,
                'leaf' => false,
                'expanded' => true,
                'allowDrag' => false,
                'allowDrop' => false,
                'children' => [],
                'qtip' => $translator->trans('elements.doubleclick_to_sort', [], 'gui'),
            ];

            $teasers = $teaserManager->findForLayoutAreaAndTreeNode($layoutarea, $treeNode);

            foreach ($teasers as $teaser) {
                switch ($teaser->getType()) {
                    case 'element':
                        $teaserElement = $elementService->findElement($teaser->getTypeId());
                        $teaserElementVersion = $elementService->findLatestElementVersion($teaserElement);

                        $areaRoot['children'][] = [
                            'id' => $teaser->getId(),
                            'parent_tid' => $currentTreeId,
                            'parent_eid' => $element->getEid(),
                            'layoutarea_id' => $layoutarea->getId(),
                            'icon' => $iconResolver->resolveTeaser($teaser, $language),
                            'text' => $teaserElementVersion->getBackendTitle($language),
                            'text' => $teaserElementVersion->getBackendTitle($language),
                            'eid' => $teaser->getTypeId(),
                            'type' => 'teaser',
                            'expanded' => false,
                            'leaf' => true,
                            'allowDrag' => false,
                            'allowDrop' => false,
                            'children' => [],
                        ];

                        break;
                }
            }

            if (count($areaRoot['children'])) {
                $data[] = $areaRoot;
            }
        }

        $data = array_values($data);

        return new JsonResponse($data);
    }
356605
public function childElementsAction(Request $request)
    {
        $tid = $request->get('tree_id');
        $layoutareaId = $request->get('layoutarea_id');
        $language = $request->get('language', 'de');

        $translator = $this->get('translator');
        $treeManager = $this->get('phlexible_tree.tree_manager');
        $teaserManager = $this->get('phlexible_teaser.teaser_manager');
        $elementService = $this->get('phlexible_element.element_service');
        $elementtypeService = $this->get('phlexible_elementtype.elementtype_service');
        $iconResolver = $this->get('phlexible_element.icon_resolver');

        $data = [];
        $data[] = [
            'id' => '0',
            'title' => $translator->trans('elements.first', [], 'gui'),
            'icon' => $iconResolver->resolveIcon('_top.gif'),
        ];

        $tree = $treeManager->getByNodeId($tid);
        $treeNode = $tree->get($tid);
        $treeNodePath = $tree->getPath($treeNode);

        $layoutarea = $elementtypeService->findElementtype($layoutareaId);
        $teasers = $teaserManager->findForLayoutAreaAndTreeNodePath($layoutarea, $treeNodePath);

        foreach ($teasers as $teaser) {
            $teaserElement = $elementService->findElement($teaser->getTypeId());
            $teaserElementVersion = $elementService->findLatestElementVersion($teaserElement);
            $data[] = [
                'id' => $teaser->getId(),
                'title' => $teaserElementVersion->getBackendTitle($language),
                'icon' => $iconResolver->resolveTeaser($teaser, $language),
            ];
        }

        return new JsonResponse(['elements' => $data]);
    }
571766
protected function load($model, $request)
    {
        $model->load($request->getQueryParams());

        return $model->load($request->getBodyParams());
    }
1369548
public function sendRequest(Request $request)
    {

        $result = $this->responseFactory->create();
        $client = $this->httpClientFactory->create();

        $apiData = $request->getApiData();
        $apiUrl = $request->getApiUrl();
        $apiKey = $request->getApiKey();
        $requestMethod = $request->getRequestMethod();

        $requestData = $requestMethod !== "GET" ? json_encode($apiData, JSON_UNESCAPED_SLASHES) : null;

        $client->setUri($apiUrl);

        $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);

        $headers =  [
            'User-Agent'            => 'BoltPay/Magento-'.$this->configHelper->getStoreVersion() . '/' . $this->configHelper->getModuleVersion(),
            'X-Bolt-Plugin-Version' => $this->configHelper->getModuleVersion(),
            'Content-Type'          => 'application/json',
            'Content-Length'        => $requestData ? strlen($requestData) : null,
            'X-Api-Key'             => $apiKey,
            'X-Nonce'               => rand(100000000000, 999999999999)
        ] + (array)$request->getHeaders();

        $request->setHeaders($headers);

        $this->bugsnag->registerCallback(function ($report) use ($request) {
            $report->setMetaData([
                'BOLT API REQUEST' => $request->getData()
            ]);
        });

        $client->setHeaders($headers);

        $responseBody = null;

        try {
            $response     = $client->setRawData($requestData, 'application/json')->request($requestMethod);
            $responseBody = $response->getBody();

            $this->bugsnag->registerCallback(function ($report) use ($response) {
                $report->setMetaData([
                    'BOLT API RESPONSE' => [
                        'headers' => $response->getHeaders(),
                        'body'    => $response->getBody(),
                    ]
                ]);
            });

            $this->bugsnag->registerCallback(function ($report) use ($response) {
                $headers = $response->getHeaders();
                $report->setMetaData([
                    'META DATA' => [
                        'bolt_trace_id' => @$headers[ConfigHelper::BOLT_TRACE_ID_HEADER],
                    ]
                ]);
            });
        } catch (\Exception $e) {
            throw new LocalizedException($this->wrapGatewayError($e->getMessage()));
        }

        if ($request->getStatusOnly() && $response) {
            return $response->getStatus();
        }

        if ($responseBody) {
            $resultFromJSON = json_decode($responseBody);
            $jsonError  = $this->handleJsonParseError();
            if ($jsonError != null) {
                $message = __("JSON Parse Error: " . $jsonError);
                throw new LocalizedException($message);
            }

            if ($this->isResponseError($resultFromJSON)) {
                $message = isset($resultFromJSON->errors[0]->message) ? __($resultFromJSON->errors[0]->message) :  __("Bolt API Error Response");
                throw new LocalizedException($message);
            }

            $result->setResponse($resultFromJSON);
        } else {
            throw new LocalizedException(
                __('Something went wrong in the payment gateway.')
            );
        }
        return $result;
    }
1044107
public function send(Request $request)
    {
        $response     = new GetIndexResponse();
        $httpRequest  = $this->createHttpRequest($request);
        $httpResponse = $this->client->send($httpRequest);
        $json         = $httpResponse->json();

        $response->name   = $request->name;
        $response->nVal   = $json['n_val'];
        $response->schema = $json['schema'];

        return $response;
    }
1207095
public function loadDataFromRequest(array $request)
    {
        if ($this->attributeKey !== null) {
            // We need to do this because of the request whitelist + the weird request
            // namespacing we do with attribute forms.
            $this->data['akID'][$this->attributeKey->getAttributeKeyID()]
                = $request['akID'][$this->attributeKey->getAttributeKeyID()];
        }
    }
1075307
protected function decodeRequestData(Request $request)
    {
        $dataRaw = $request->getContent();
        $data = null;

        if (!empty($dataRaw)) {
            $data = json_decode($dataRaw, true);
        }

        return $data;
    }
873361
public function xmlAction(Request $request)
    {
        $redis = $this->get('snc_redis.victoire_client');
        $locale = $request->getLocale();
        $cacheKey = "sitemap.$locale";

        $pages = $redis->get($cacheKey);
        if ($pages === null) {
            $exportHandler = $this->get('victoire_sitemap.export.handler');

            $pages = $exportHandler->serialize(
                $exportHandler->handle($locale)
            );
        }

        return $this->render('VictoireSitemapBundle:Sitemap:sitemap.xml.twig', [
            'pages' => json_decode($pages),
        ]);
    }
263738
public function acceptXml(Request $request)
    {
        $ret = new \DOMDocument("1.0", "UTF-8");
        $ret->preserveWhiteSpace = false;

        $root = $ret->appendChild($ret->createElement("result"));
        $root->appendChild($ret->createCDATASection(var_export([
            "bid"   => $request->get('bid'),
            "id"    => $request->get('id'),
            "piv"   => $request->get('piv'),
        ], true)));

        $refresh_list = $root->appendChild($ret->createElement("refresh_list"));

        if (null === $bid = $request->get("bid")) {
            return new Response('Missing bid parameter', 400);
        }

        try {
            /** @var \databox $databox */
            $databox = $this->findDataboxById((int) $bid);
            $databox->get_connection()->connect();

            $dom = $databox->get_dom_cterms();
            $xpath = new \DOMXPath($dom);
            $q = "/cterms//te[@id='" . $request->get('id') . "']";

            /** @var \DOMElement $te */
            $te = $xpath->query($q)->item(0);
            if ($te) {
                $this->acceptBranch($bid, $te);

                $databox->saveCterms($dom);

                /** @var \DOMElement $r */
                $r = $refresh_list->appendChild($ret->createElement("refresh"));
                /** @var \DOMElement $p */
                $p = $te->parentNode;
                $r->setAttribute("id", $p->getAttribute("id"));
                $r->setAttribute("type", "CT");
            }
        } catch (\Exception $e) {

        }

        return new Response($ret->saveXML(), 200, ['Content-Type' => 'text/xml']);
    }
1081471
public function childelementsAction(Request $request)
    {
        $id = $request->get('id');
        $language = $request->get('language');

        $treeManager = $this->get('phlexible_tree.tree_manager');
        $elementService = $this->get('phlexible_element.element_service');
        $iconResolver = $this->get('phlexible_element.icon_resolver');

        $tree = $treeManager->getByNodeID($id);
        $node = $tree->get($id);
        $eid = $node->getTypeId();
        $element = $elementService->findElement($eid);

        if (!$language) {
            $language = $element->getMasterLanguage();
        }

        $firstString = $this->get('translator')->trans('elements.first', [], 'gui');

        $data = [];
        $data[] = [
            'id' => '0',
            'title' => $firstString,
            'icon' => $iconResolver->resolveIcon('_top.gif'),
        ];

        foreach ($tree->getChildren($node) as $childNode) {
            $childElement = $elementService->findElement($childNode->getTypeId());
            $childElementVersion = $elementService->findLatestElementVersion($childElement);

            $data[] = [
                'id' => $childNode->getId(),
                'title' => $childElementVersion->getBackendTitle($language, $childElementVersion->getElement()->getMasterLanguage()).' ['.$childNode->getId().']',
                'icon' => $iconResolver->resolveTreeNode($childNode, $language),
            ];
        }

        return new JsonResponse(['elements' => $data]);
    }
569153
public function childElementtypesAction(Request $request)
    {
        $id = $request->get('id');

        $elementSourceManager = $this->get('phlexible_element.element_source_manager');
        $elementService = $this->get('phlexible_element.element_service');
        $iconResolver = $this->get('phlexible_element.icon_resolver');

        $elementtype = $elementSourceManager->findElementtype($id);
        $childElementtypes = $elementService->findAllowedChildren($elementtype);

        $data = [];
        foreach ($childElementtypes as $childElementtype) {
            $data[$childElementtype->getTitle().$childElementtype->getId()] = [
                'id' => $childElementtype->getId(),
                'title' => $childElementtype->getTitle(),
                'icon' => $iconResolver->resolveElementtype($childElementtype),
            ];
        }
        ksort($data);
        $data = array_values($data);

        return new JsonResponse(['elementtypes' => $data]);
    }
979180
public function childrenAction(Request $request)
    {
        $this->denyAccessUnlessGranted('ez:tags:read');

        $subTreeLimit = (int) $request->query->get('subTreeLimit', 0);
        $hideRootTag = (bool) $request->query->get('hideRootTag', false);
        $locale = $request->query->get('locale');

        $tags = $this->tagsService->loadTagChildren(
            !empty($subTreeLimit) ? $this->tagsService->loadTag($subTreeLimit) : null,
            0,
            -1,
            [$locale]
        );

        $data = $this->filterTags($tags, $subTreeLimit, $hideRootTag);

        return new JsonResponse($data);
    }
1072744
public function lockAction(Request $request)
    {
        // get request parameters
        $eid = (int) $request->get('eid');
        $language = $request->get('language');

        $elementService = $this->get('phlexible_element.element_service');
        $lockManager = $this->get('phlexible_element.element_lock_manager');

        $element = $elementService->findElement($eid);

        if ($lockManager->isLocked($element)) {
            return new ResultResponse(false, 'Element already locked.');
        } else {
            try {
                // try to lock the element
                $lockManager->lock($element, $this->getUser()->getId());

                return new ResultResponse(true, 'Lock aquired.');
            } catch (\Exception $e) {
                return new ResultResponse(false, $e->getMessage());
            }
        }
    }
1325792
public function listAction(Request $request)
    {
        $id = $request->get('id');

        $elementtypeService = $this->get('phlexible_elementtype.elementtype_service');
        $viabilityManager = $this->get('phlexible_elementtype.viability_manager');
        $elementtype = $elementtypeService->findElementtype($id);

        $viabilities = [];
        foreach ($viabilityManager->findAllowedParents($elementtype) as $viability) {
            $viabilityElementtype = $elementtypeService->findElementtype($viability->getUnderElementtypeId());
            $viabilities[] = [
                'id' => $viabilityElementtype->getId(),
                'title' => $viabilityElementtype->getTitle(),
                'icon' => $viabilityElementtype->getIcon(),
            ];
        }

        return new JsonResponse(['viability' => $viabilities]);
    }
1170992
protected function loadRoots(Request $request)
    {
        $locale = $request->get('_locale', $this->defaultLocale);

        if (isset($this->roots[$locale])) {
            return $this->roots[$locale];
        }

        $connection = $this->em->getConnection();
        $where = 'lvl=0';

        if ($locale) {
            $where .= sprintf(' AND (language IS NULL OR language=%s)', $connection->quote($locale));
        } else {
            $where .= ' AND language IS NULL';
        }

        $rows = $connection->query('SELECT id, name, language, lft, rgt FROM menu_item WHERE ' . $where)->fetchAll(\PDO::FETCH_NUM);
        foreach ($rows as list($id, $name, $language, $lft, $rgt)) {
            // if the language is null, and the root items is already loaded; ignore it.
            if (null === $language && isset($this->roots[$name])) {
                continue;
            }

            $this->roots[$locale][$name] = [$id, $lft, $rgt];
        }

        if (!isset($this->roots[$locale])) {
            return [];
        }

        return $this->roots[$locale];
    }
242182
public function indexAction(Request $request)
    {
        $paginator = $this->get('opifer.content.content_manager')
            ->getPaginatedByRequest($request);

        $contents = $paginator->getCurrentPageResults();

        $contents = $this->get('jms_serializer')->serialize(iterator_to_array($contents), 'json', SerializationContext::create()->setGroups(['list'])->enableMaxDepthChecks());

        $data = [
            'results'       => json_decode($contents, true),
            'total_results' => $paginator->getNbResults()
        ];

        return new JsonResponse($data);
    }