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)); }
/** * Set data for response of frontend saveOrder action * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function addAdditionalFieldsToResponseFrontend(\Magento\Framework\Event\Observer $observer) { /* @var $order \Magento\Sales\Model\Order */ $order = $this->_coreRegistry->registry('directpost_order'); if ($order && $order->getId()) { $payment = $order->getPayment(); if ($payment && $payment->getMethod() == $this->_payment->getCode()) { /** @var \Magento\Checkout\Controller\Action $controller */ $controller = $observer->getEvent()->getData('controller_action'); $request = $controller->getRequest(); $response = $controller->getResponse(); $result = $this->_coreData->jsonDecode($response->getBody('default')); if (empty($result['error'])) { $payment = $order->getPayment(); //if success, then set order to session and add new fields $this->_session->addCheckoutOrderIncrementId($order->getIncrementId()); $this->_session->setLastOrderIncrementId($order->getIncrementId()); $requestToAuthorizenet = $payment->getMethodInstance()->generateRequestFromOrder($order); $requestToAuthorizenet->setControllerActionName($request->getControllerName()); $requestToAuthorizenet->setIsSecure((string) $this->_storeManager->getStore()->isCurrentlySecure()); $result['directpost'] = array('fields' => $requestToAuthorizenet->getData()); $response->clearHeader('Location'); $response->representJson($this->_coreData->jsonEncode($result)); } } } return $this; }
/** * 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 = array()) { if ($this->getRequest()->isXmlHttpRequest()) { $this->getResponse()->representJson($this->_coreHelper->jsonEncode(array('_redirect' => $this->getUrl($path, $arguments)))); return $this; } else { return parent::_redirect($path, $arguments); } }
/** * Return an array of selected resource ids. If everything is allowed then iterate through all * available resources to generate a comprehensive array of all resource ids, rather than just * returning "Magento_Adminhtml::all". * * @return string */ public function getSelectedResourcesJson() { $selectedResources = $this->_selectedResources; if ($this->isEverythingAllowed()) { $resources = $this->_resourceProvider->getAclResources(); $selectedResources = $this->_getAllResourceIds($resources[1]['children']); } return $this->_coreHelper->jsonEncode($selectedResources); }
/** * Returns the list of countries, for which region is required * * @param boolean $asJson * @return array */ public function getCountriesWithStatesRequired($asJson = false) { $value = trim($this->_config->getValue(self::XML_PATH_STATES_REQUIRED, \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $countryList = preg_split('/\\,/', $value, 0, PREG_SPLIT_NO_EMPTY); if ($asJson) { return $this->_coreHelper->jsonEncode($countryList); } return $countryList; }
/** * 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->_coreData->jsonEncode($priceFormat); }
/** * Get all tax rates JSON for all product tax classes. * * @return string */ public function getAllRatesByProductClassJson() { $result = array(); 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->coreHelper->jsonEncode($result); }
/** * 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->_coreHelper->jsonEncode($pathsParts); } return $pathsParts; }
/** * 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 = array(); /** @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'][] = array('is_delete' => false, 'link_id' => null, 'title' => $linkData['title'], 'is_shareable' => $linkData['is_shareable'], 'sample' => array('type' => $linkData['sample_type'], 'url' => $linkData['sample_url'], 'file' => $this->encoder->jsonEncode(array(array('file' => $linkData['sample_file'], 'name' => $linkData['sample_file'], 'size' => 0, 'status' => null)))), 'file' => $this->encoder->jsonEncode(array(array('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'][] = array('is_delete' => false, 'sample_id' => null, 'title' => $sampleData['title'], 'type' => $sampleData['sample_type'], 'file' => $this->encoder->jsonEncode(array(array('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); }
/** * Check Captcha On Checkout Register Page * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function checkRegisterCheckout($observer) { $formId = 'register_during_checkout'; $captchaModel = $this->_helper->getCaptcha($formId); $checkoutMethod = $this->_typeOnepage->getQuote()->getCheckoutMethod(); if ($checkoutMethod == \Magento\Checkout\Model\Type\Onepage::METHOD_REGISTER) { if ($captchaModel->isRequired()) { $controller = $observer->getControllerAction(); if (!$captchaModel->isCorrect($this->_getCaptchaString($controller->getRequest(), $formId))) { $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); $result = array('error' => 1, 'message' => __('Incorrect CAPTCHA')); $controller->getResponse()->representJson($this->_coreData->jsonEncode($result)); } } } return $this; }
/** * Format error data according to required format. * * @param string $errorMessage * @param string $trace * @param int $httpCode * @param string $format * @return array|string */ protected function _formatError($errorMessage, $trace, $httpCode, $format) { $errorData = []; $message = ['code' => $httpCode, 'message' => $errorMessage]; $isDeveloperMode = $this->_appState->getMode() == State::MODE_DEVELOPER; if ($isDeveloperMode) { $message['trace'] = $trace; } $errorData['messages']['error'][] = $message; switch ($format) { case self::DATA_FORMAT_JSON: $errorData = $this->_coreHelper->jsonEncode($errorData); break; case self::DATA_FORMAT_XML: $errorData = '<?xml version="1.0"?>' . '<error>' . '<messages>' . '<error>' . '<data_item>' . '<code>' . $httpCode . '</code>' . '<message><![CDATA[' . $errorMessage . ']]></message>' . ($isDeveloperMode ? '<trace><![CDATA[' . $trace . ']]></trace>' : '') . '</data_item>' . '</error>' . '</messages>' . '</error>'; break; } return $errorData; }
/** * Serialize info for Resource Model to save * For new model check and set available cookie key * * @return $this */ protected function _beforeSave() { parent::_beforeSave(); // Setting info $info = array(); foreach ($this->getData() as $index => $value) { if (!in_array($index, $this->_unserializableFields)) { $info[$index] = $value; } } $this->setInfo($this->_coreData->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; }
/** * Set data for response of frontend saveOrder action * * @param EventObserver $observer * @return $this */ public function setResponseAfterSaveOrder(EventObserver $observer) { /* @var $order \Magento\Sales\Model\Order */ $order = $this->_coreRegistry->registry('hss_order'); if ($order && $order->getId()) { $payment = $order->getPayment(); if ($payment && in_array($payment->getMethod(), $this->_paypalHss->getHssMethods())) { /* @var $controller \Magento\Framework\App\Action\Action */ $controller = $observer->getEvent()->getData('controller_action'); $result = $this->_coreData->jsonDecode($controller->getResponse()->getBody('default')); if (empty($result['error'])) { $this->_view->loadLayout('checkout_onepage_review', true, true, false); $html = $this->_view->getLayout()->getBlock('paypal.iframe')->toHtml(); $result['update_section'] = array('name' => 'paypaliframe', 'html' => $html); $result['redirect'] = false; $result['success'] = false; $controller->getResponse()->clearHeader('Location'); $controller->getResponse()->representJson($this->_coreData->jsonEncode($result)); } } } return $this; }
/** * Convert data to JSON. * * @param object|array|int|string|bool|float|null $data * @return string */ public function render($data) { return $this->_helper->jsonEncode($data); }
/** * Search for attributes by part of attribute's label in admin store * * @return void */ public function execute() { $this->storeManager->setCurrentStore(\Magento\Store\Model\Store::ADMIN_CODE); $this->getResponse()->representJson($this->coreHelper->jsonEncode($this->attributeList->getSuggestedAttributes($this->getRequest()->getParam('label_part')))); }
/** * 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(), array('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 execute() { $this->getResponse()->representJson($this->coreHelper->jsonEncode($this->attributeList->getSuggestedAttributes($this->getRequest()->getParam('label_part')))); }
/** * Prepare block children and data * * @return void */ protected function _prepareLayout() { $onclick = "jQuery('[data-form=edit-product]').attr('action', " . $this->_coreHelper->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(); }
/** * Validate data rows and save bunches to DB. * * @return $this|void */ protected function _saveValidatedBunches() { $source = $this->_getSource(); $currentDataSize = 0; $bunchRows = array(); $startNewBunch = false; $nextRowBackup = array(); $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 = array(); } if ($source->valid()) { if ($this->_errorsCount >= $this->_errorsLimit) { // errors limit check return; } $rowData = $source->current(); $this->_processedRowsCount++; if ($this->validateRow($rowData, $source->key())) { // add row to bunch for save $rowData = $this->_prepareRowForDb($rowData); $rowSize = strlen($this->_coreData->jsonEncode($rowData)); $isBunchSizeExceeded = $bunchSize > 0 && count($bunchRows) >= $bunchSize; if ($currentDataSize + $rowSize >= $maxDataSize || $isBunchSizeExceeded) { $startNewBunch = true; $nextRowBackup = array($source->key() => $rowData); } else { $bunchRows[$source->key()] = $rowData; $currentDataSize += $rowSize; } } $source->next(); } } return $this; }
/** * Encode the mixed $valueToEncode into the JSON format * * @param mixed $valueToEncode * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default * @param array $options Additional options used during encoding * @return string */ public function jsonEncode($valueToEncode, $cycleCheck = false, $options = []) { return $this->coreDataHelper->jsonEncode($valueToEncode, $cycleCheck, $options); }
/** * Javascript setup object for filebrowser instance * * @return string */ public function getFilebrowserSetupObject() { $setupObject = new \Magento\Framework\Object(); $setupObject->setData(array('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->_coreHelper->jsonEncode($setupObject); }
/** * Get custom js files * * @return \Magento\Core\Model\Resource\Theme\File\Collection */ public function getFiles() { $customization = $this->_themeContext->getStagingTheme()->getCustomization(); $jsFiles = $customization->getFilesByType(\Magento\Framework\View\Design\Theme\Customization\File\Js::TYPE); return $this->_coreHelper->jsonEncode($customization->generateFileInfo($jsFiles)); }
/** * Initialize system message dialog widget * * @return string */ public function getSystemMessageDialogJson() { return $this->_coreHelper->jsonEncode(array('systemMessageDialog' => array('autoOpen' => false, 'width' => 600, 'ajaxUrl' => $this->_getMessagesUrl()))); }