public function testJsonEncode() { $expected = '"valueToEncode"'; $valueToEncode = 'valueToEncode'; $this->jsonEncoderMock->expects($this->once())->method('encode')->willReturn($expected); $this->assertEquals($expected, $this->helper->jsonEncode($valueToEncode)); }
public function testJsonEncodeDecode() { $data = ['one' => 1, 'two' => 'two']; $jsonData = '{"one":1,"two":"two"}'; $this->assertEquals($jsonData, $this->_helper->jsonEncode($data)); $this->assertEquals($data, $this->_helper->jsonDecode($jsonData)); }
/** * Don't actually redirect if we've got AJAX request - return redirect URL instead. * * @param string $path * @param array $arguments * @return $this|\Magento\Backend\App\AbstractAction */ protected function _redirect($path, $arguments = []) { if ($this->getRequest()->isXmlHttpRequest()) { $this->getResponse()->representJson($this->jsonHelper->jsonEncode(['_redirect' => $this->getUrl($path, $arguments)])); return $this; } else { return parent::_redirect($path, $arguments); } }
/** * Compile JSON response * * @param string $error * @return Http */ protected function jsonResponse($error = '') { $response = $this->sidebar->getResponseData($error); if (empty($error)) { $resultPage = $this->resultPageFactory->create(); $block = $resultPage->getLayout()->getBlock('minicart.content')->toHtml(); $response['content'] = $block; } return $this->getResponse()->representJson($this->jsonHelper->jsonEncode($response)); }
/** * Search for attributes by part of attribute's label in admin store * * @return void */ public function executeInternal() { $this->storeManager->setCurrentStore(\Magento\Store\Model\Store::ADMIN_CODE); $collection = $this->collectionFactory->create(); $collection->addFieldToFilter('main_table.attribute_id', $this->getRequest()->getParam('attributes')); $attributes = []; foreach ($collection->getItems() as $attribute) { $attributes[] = ['id' => $attribute->getId(), 'label' => $attribute->getFrontendLabel(), 'code' => $attribute->getAttributeCode(), 'options' => $attribute->getSource()->getAllOptions(false)]; } $this->getResponse()->representJson($this->jsonHelper->jsonEncode($attributes)); }
/** * @return void */ public function execute() { $severity = $this->getRequest()->getParam('severity'); if ($severity) { $this->messageCollection->setSeverity($severity); } $result = []; foreach ($this->messageCollection->getItems() as $item) { $result[] = ['severity' => $item->getSeverity(), 'text' => $item->getText()]; } if (empty($result)) { $result[] = ['severity' => (string) \Magento\Framework\Notification\MessageInterface::SEVERITY_NOTICE, 'text' => 'You have viewed and resolved all recent system notices. ' . 'Please refresh the web page to clear the notice alert.']; } $this->getResponse()->representJson($this->jsonHelper->jsonEncode($result)); }
/** * Check Captcha On Checkout as Guest Page * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $formId = 'guest_checkout'; $captchaModel = $this->_helper->getCaptcha($formId); $checkoutMethod = $this->_typeOnepage->getQuote()->getCheckoutMethod(); if ($checkoutMethod == \Magento\Checkout\Model\Type\Onepage::METHOD_GUEST) { if ($captchaModel->isRequired()) { $controller = $observer->getControllerAction(); if (!$captchaModel->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId))) { $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); $result = ['error' => 1, 'message' => __('Incorrect CAPTCHA')]; $controller->getResponse()->representJson($this->jsonHelper->jsonEncode($result)); } } } return $this; }
/** * Get JSON string that contains attribute code and value * * @param array $options * @return string */ protected function getJsonConfigurableAttributes(array $options = []) { $result = []; foreach ($options as $option) { $result[$option['attribute_code']] = $option['value']; } return $this->jsonHelper->jsonEncode($result); }
/** * Returns the list of countries, for which region is required * * @param boolean $asJson * @return array */ public function getCountriesWithStatesRequired($asJson = false) { $value = trim($this->scopeConfig->getValue(self::XML_PATH_STATES_REQUIRED, ScopeInterface::SCOPE_STORE)); $countryList = preg_split('/\\,/', $value, 0, PREG_SPLIT_NO_EMPTY); if ($asJson) { return $this->jsonHelper->jsonEncode($countryList); } return $countryList; }
/** * Get all tax rates JSON for all product tax classes. * * @return string */ public function getAllRatesByProductClassJson() { $result = []; foreach ($this->productTaxClassSource->getAllOptions() as $productTaxClass) { $taxClassId = $productTaxClass['value']; $taxRate = $this->calculationService->getDefaultCalculatedRate($taxClassId, $this->currentCustomer->getCustomerId(), $this->getStore()->getId()); $result["value_{$taxClassId}"] = $taxRate; } return $this->jsonHelper->jsonEncode($result); }
/** * Get prices javascript format json * * @param null|int|string|Store $store * @return string */ public function getPriceFormat($store = null) { $this->_localeResolver->emulate($store); $priceFormat = $this->_localeFormat->getPriceFormat(); $this->_localeResolver->revert(); if ($store) { $priceFormat['pattern'] = $this->_storeManager->getStore($store)->getCurrentCurrency()->getOutputFormat(); } return $this->jsonHelper->jsonEncode($priceFormat); }
/** * Get paths of where current template is used as default * * @param bool $asJSON * @return string */ public function getUsedDefaultForPaths($asJSON = true) { /** @var $template \Magento\Email\Model\BackendTemplate */ $template = $this->getEmailTemplate(); $paths = $template->getSystemConfigPathsWhereUsedAsDefault(); $pathsParts = $this->_getSystemConfigPathsParts($paths); if ($asJSON) { return $this->jsonHelper->jsonEncode($pathsParts); } return $pathsParts; }
/** * Validate api user. */ public function execute() { $params = $this->getRequest()->getParams(); $apiUsername = $params['api_username']; //@codingStandardsIgnoreStart $apiPassword = base64_decode($params['api_password']); //@codingStandardsIgnoreEnd //validate api, check against account info. if ($this->data->isEnabled()) { $client = $this->data->getWebsiteApiClient(); $result = $client->validate($apiUsername, $apiPassword); $resonseData['success'] = true; //validation failed if (!$result) { $resonseData['success'] = false; $resonseData['message'] = 'Authorization has been denied for this request.'; } $this->getResponse()->representJson($this->jsonHelper->jsonEncode($resonseData)); } }
/** * Duplicating downloadable product data * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Catalog\Model\Product $duplicate * @return void */ public function build(\Magento\Catalog\Model\Product $product, \Magento\Catalog\Model\Product $duplicate) { if ($product->getTypeId() !== \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) { //do nothing if not downloadable return; } $data = []; /** @var \Magento\Downloadable\Model\Product\Type $type */ $type = $product->getTypeInstance(); foreach ($type->getLinks($product) as $link) { /* @var \Magento\Downloadable\Model\Link $link */ $linkData = $link->getData(); $data['link'][] = ['is_delete' => false, 'link_id' => null, 'title' => $linkData['title'], 'is_shareable' => $linkData['is_shareable'], 'sample' => ['type' => $linkData['sample_type'], 'url' => $linkData['sample_url'], 'file' => $this->jsonHelper->jsonEncode([['file' => $linkData['sample_file'], 'name' => $linkData['sample_file'], 'size' => 0, 'status' => null]])], 'file' => $this->jsonHelper->jsonEncode([['file' => $linkData['link_file'], 'name' => $linkData['link_file'], 'size' => 0, 'status' => null]]), 'type' => $linkData['link_type'], 'link_url' => $linkData['link_url'], 'sort_order' => $linkData['sort_order'], 'number_of_downloads' => $linkData['number_of_downloads'], 'price' => $linkData['price']]; } /** @var \Magento\Downloadable\Model\Sample $sample */ foreach ($type->getSamples($product) as $sample) { $sampleData = $sample->getData(); $data['sample'][] = ['is_delete' => false, 'sample_id' => null, 'title' => $sampleData['title'], 'type' => $sampleData['sample_type'], 'file' => $this->jsonHelper->jsonEncode([['file' => $sampleData['sample_file'], 'name' => $sampleData['sample_file'], 'size' => 0, 'status' => null]]), 'sample_url' => $sampleData['sample_url'], 'sort_order' => $sampleData['sort_order']]; } $duplicate->setDownloadableData($data); }
/** * Return messages stored in cookies * * @return array */ protected function getCookiesMessages() { try { $messages = $this->jsonHelper->jsonDecode($this->cookieManager->getCookie(self::MESSAGES_COOKIES_NAME, $this->jsonHelper->jsonEncode([]))); if (!is_array($messages)) { $messages = []; } } catch (\Zend_Json_Exception $e) { $messages = []; } return $messages; }
/** * Place order for checkout flow * * @return string */ protected function placeCheckoutOrder() { $result = new DataObject(); $response = $this->getResponse(); try { $this->cartManagement->placeOrder($this->_getCheckout()->getQuote()->getId()); $result->setData('success', true); $this->eventManager->dispatch('checkout_directpost_placeOrder', ['result' => $result, 'action' => $this]); } catch (\Exception $exception) { $result->setData('error', true); $result->setData('error_messages', __('An error occurred on the server. Please try to place the order again.')); } if ($response instanceof Http) { $response->representJson($this->jsonHelper->jsonEncode($result)); } }
/** * Serialize info for Resource Model to save * For new model check and set available cookie key * * @return $this */ public function beforeSave() { parent::beforeSave(); // Setting info $info = []; foreach ($this->getData() as $index => $value) { if (!in_array($index, $this->_unserializableFields)) { $info[$index] = $value; } } $this->setInfo($this->jsonHelper->jsonEncode($info)); if ($this->isObjectNew()) { $this->setWebsiteId($this->_storeManager->getStore()->getWebsiteId()); // Setting cookie key do { $this->setKey($this->mathRandom->getRandomString(self::KEY_LENGTH)); } while (!$this->getResource()->isKeyAllowed($this->getKey())); } return $this; }
/** * Save import rows bunch. * * @param string $entity * @param string $behavior * @param array $data * @return int */ public function saveBunch($entity, $behavior, array $data) { return $this->_getWriteAdapter()->insert($this->getMainTable(), ['behavior' => $behavior, 'entity' => $entity, 'data' => $this->jsonHelper->jsonEncode($data)]); }
/** * Search for attributes by part of attribute's label in admin store * * @return void */ public function executeInternal() { $this->storeManager->setCurrentStore(\Magento\Store\Model\Store::ADMIN_CODE); $this->getResponse()->representJson($this->jsonHelper->jsonEncode($this->attributeList->getSuggestedAttributes($this->getRequest()->getParam('label_part')))); }
/** * Initialize system message dialog widget * * @return string */ public function getSystemMessageDialogJson() { return $this->jsonHelper->jsonEncode(['systemMessageDialog' => ['buttons' => [], 'modalClass' => 'ui-dialog-active ui-popup-message modal-system-messages', 'ajaxUrl' => $this->_getMessagesUrl()]]); }
/** * Encode the mixed $valueToEncode into the JSON format * * @param mixed $valueToEncode * @return string */ public function jsonEncode($valueToEncode) { return $this->jsonHelper->jsonEncode($valueToEncode); }
/** * Search for attributes by part of attribute's label in admin store * * @return void */ public function execute() { $this->getResponse()->representJson($this->jsonHelper->jsonEncode($this->saveAttributeOptions())); }
/** * Prepare block children and data * * @return void */ protected function _prepareLayout() { $onclick = "jQuery('[data-form=edit-product]').attr('action', " . $this->jsonHelper->jsonEncode($this->getContinueUrl()) . ").addClass('ignore-validate').submit();"; $this->addChild('continue_button', 'Magento\\Backend\\Block\\Widget\\Button', ['label' => __('Generate Variations'), 'onclick' => $onclick, 'class' => 'save']); parent::_prepareLayout(); }
/** * Javascript setup object for filebrowser instance * * @return string */ public function getFilebrowserSetupObject() { $setupObject = new \Magento\Framework\Object(); $setupObject->setData(['newFolderPrompt' => __('New Folder Name:'), 'deleteFolderConfirmationMessage' => __('Are you sure you want to delete this folder?'), 'deleteFileConfirmationMessage' => __('Are you sure you want to delete this file?'), 'targetElementId' => $this->getTargetElementId(), 'contentsUrl' => $this->getContentsUrl(), 'onInsertUrl' => $this->getOnInsertUrl(), 'newFolderUrl' => $this->getNewfolderUrl(), 'deleteFolderUrl' => $this->getDeletefolderUrl(), 'deleteFilesUrl' => $this->getDeleteFilesUrl(), 'headerText' => $this->getHeaderText(), 'showBreadcrumbs' => true]); return $this->jsonHelper->jsonEncode($setupObject); }
/** * Retrieve price format configuration in Json. * * @return array */ public function getJsonPriceFormat() { return $this->jsonHelper->jsonEncode($this->getPriceFormat()); }
/** * {@inheritDoc} */ public function execute() { $responseData = $this->getPreviewObject()->getData(); $json = $this->jsonHelper->jsonEncode($responseData); $this->getResponse()->representJson($json); }
/** * Get attributes * * @return void */ public function execute() { $this->storeManager->setCurrentStore(\Magento\Store\Model\Store::ADMIN_CODE); $attributes = $this->attributesList->getAttributes($this->getRequest()->getParam('attributes')); $this->getResponse()->representJson($this->jsonHelper->jsonEncode($attributes)); }
/** * Compile JSON response * * @param string $error * @return Http */ protected function jsonResponse($error = '') { $response = $this->sidebar->getResponseData($error); return $this->getResponse()->representJson($this->jsonHelper->jsonEncode($response)); }
/** * Validate data rows and save bunches to DB. * * @return $this|void * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function _saveValidatedBunches() { $source = $this->_getSource(); $currentDataSize = 0; $bunchRows = []; $startNewBunch = false; $nextRowBackup = []; $maxDataSize = $this->_resourceHelper->getMaxDataSize(); $bunchSize = $this->_importExportData->getBunchSize(); $source->rewind(); $this->_dataSourceModel->cleanBunches(); while ($source->valid() || $bunchRows) { if ($startNewBunch || !$source->valid()) { $this->_dataSourceModel->saveBunch($this->getEntityTypeCode(), $this->getBehavior(), $bunchRows); $bunchRows = $nextRowBackup; $currentDataSize = strlen(serialize($bunchRows)); $startNewBunch = false; $nextRowBackup = []; } if ($source->valid()) { try { $rowData = $source->current(); } catch (\InvalidArgumentException $e) { $this->addRowError($e->getMessage(), $this->_processedRowsCount); $this->_processedRowsCount++; $source->next(); continue; } $this->_processedRowsCount++; if ($this->validateRow($rowData, $source->key())) { // add row to bunch for save $rowData = $this->_prepareRowForDb($rowData); $rowSize = strlen($this->jsonHelper->jsonEncode($rowData)); $isBunchSizeExceeded = $bunchSize > 0 && count($bunchRows) >= $bunchSize; if ($currentDataSize + $rowSize >= $maxDataSize || $isBunchSizeExceeded) { $startNewBunch = true; $nextRowBackup = [$source->key() => $rowData]; } else { $bunchRows[$source->key()] = $rowData; $currentDataSize += $rowSize; } } $source->next(); } } return $this; }
/** * Initialize system message dialog widget * * @return string */ public function getSystemMessageDialogJson() { return $this->jsonHelper->jsonEncode(['systemMessageDialog' => ['autoOpen' => false, 'width' => '75%', 'modal' => true, 'minHeight' => '0', 'dialogClass' => 'ui-dialog-active ui-popup-message', 'ajaxUrl' => $this->_getMessagesUrl()]]); }