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)); }
public function testJsonDecode() { $expected = '"valueToDecode"'; $valueToDecode = 'valueToDecode'; $this->jsonDecoderMock->expects($this->once())->method('decode')->willReturn($expected); $this->assertEquals($expected, $this->helper->jsonDecode($valueToDecode)); }
/** * Login registered users and initiate a session. * * Expects a POST. ex for JSON {"username":"******", "password":"******"} * * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { $credentials = null; $httpBadRequestCode = 400; /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */ $resultRaw = $this->resultRawFactory->create(); try { $credentials = $this->helper->jsonDecode($this->getRequest()->getContent()); } catch (\Exception $e) { return $resultRaw->setHttpResponseCode($httpBadRequestCode); } if (!$credentials || $this->getRequest()->getMethod() !== 'POST' || !$this->getRequest()->isXmlHttpRequest()) { return $resultRaw->setHttpResponseCode($httpBadRequestCode); } $response = ['errors' => false, 'message' => __('Login successful.')]; try { $customer = $this->customerAccountManagement->authenticate($credentials['username'], $credentials['password']); $this->customerSession->setCustomerDataAsLoggedIn($customer); $this->customerSession->regenerateId(); } catch (EmailNotConfirmedException $e) { $response = ['errors' => true, 'message' => $e->getMessage()]; } catch (InvalidEmailOrPasswordException $e) { $response = ['errors' => true, 'message' => $e->getMessage()]; } catch (\Exception $e) { $response = ['errors' => true, 'message' => __('Something went wrong while validating the login and password.')]; } /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); return $resultJson->setData($response); }
public function execute() { if ($this->_expireAjax()) { return; } $data = $this->_jsonHelper->jsonDecode($this->getRequest()->getContent()); if (!empty($data['vatpername']) && !empty($data['vatcomment'])) { $data['vatdeclare'] = 1; } $vatExemptModel = $this->_vatExemptModel; $result = $vatExemptModel->saveVatexempt($data); return $this->resultJsonFactory->create()->setData($result); }
/** * Product variations attributes validation * * @param Product $parentProduct * @param array $products * @param RequestInterface $request * @return array */ protected function _validateProductVariations(Product $parentProduct, array $products, RequestInterface $request) { $this->eventManager->dispatch('catalog_product_validate_variations_before', ['product' => $parentProduct, 'variations' => $products]); $validationResult = []; foreach ($products as $productData) { $product = $this->productFactory->create(); $product->setData('_edit_mode', true); $storeId = $request->getParam('store'); if ($storeId) { $product->setStoreId($storeId); } $product->setAttributeSetId($parentProduct->getAttributeSetId()); $product->addData($this->getRequiredDataFromProduct($parentProduct)); $product->addData($productData); $product->setCollectExceptionMessages(true); $configurableAttribute = []; $encodedData = $productData['configurable_attribute']; if ($encodedData) { $configurableAttribute = $this->jsonHelper->jsonDecode($encodedData); } $configurableAttribute = implode('-', $configurableAttribute); $errorAttributes = $product->validate(); if (is_array($errorAttributes)) { foreach ($errorAttributes as $attributeCode => $result) { if (is_string($result)) { $key = 'variations-matrix-' . $configurableAttribute . '-' . $attributeCode; $validationResult[$key] = $result; } } } } return $validationResult; }
/** * @param \Magento\Framework\Object $object * @return $this|void * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function beforeSave($object) { $attrCode = $this->getAttribute()->getAttributeCode(); $value = $object->getData($attrCode); if (!is_array($value) || !isset($value['images'])) { return; } if (!is_array($value['images']) && strlen($value['images']) > 0) { $value['images'] = $this->jsonHelper->jsonDecode($value['images']); } if (!is_array($value['images'])) { $value['images'] = []; } $clearImages = []; $newImages = []; $existImages = []; if ($object->getIsDuplicate() != true) { foreach ($value['images'] as &$image) { if (!empty($image['removed'])) { $clearImages[] = $image['file']; } elseif (empty($image['value_id'])) { $newFile = $this->_moveImageFromTmp($image['file']); $image['new_file'] = $newFile; $newImages[$image['file']] = $image; $this->_renamedImages[$image['file']] = $newFile; $image['file'] = $newFile; } else { $existImages[$image['file']] = $image; } } } else { // For duplicating we need copy original images. $duplicate = []; foreach ($value['images'] as &$image) { if (empty($image['value_id'])) { continue; } $duplicate[$image['value_id']] = $this->_copyImage($image['file']); $image['new_file'] = $duplicate[$image['value_id']]; $newImages[$image['file']] = $image; } $value['duplicate'] = $duplicate; } foreach ($object->getMediaAttributes() as $mediaAttribute) { $mediaAttrCode = $mediaAttribute->getAttributeCode(); $attrData = $object->getData($mediaAttrCode); if (in_array($attrData, $clearImages)) { $object->setData($mediaAttrCode, 'no_selection'); } if (in_array($attrData, array_keys($newImages))) { $object->setData($mediaAttrCode, $newImages[$attrData]['new_file']); $object->setData($mediaAttrCode . '_label', $newImages[$attrData]['label']); } if (in_array($attrData, array_keys($existImages))) { $object->setData($mediaAttrCode . '_label', $existImages[$attrData]['label']); } } $object->setData($attrCode, $value); return $this; }
/** * Login registered users and initiate a session. * * Expects a POST. ex for JSON {"username":"******", "password":"******"} * * @return \Magento\Framework\Controller\ResultInterface * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { $credentials = null; $httpBadRequestCode = 400; /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */ $resultRaw = $this->resultRawFactory->create(); try { $credentials = $this->helper->jsonDecode($this->getRequest()->getContent()); } catch (\Exception $e) { return $resultRaw->setHttpResponseCode($httpBadRequestCode); } if (!$credentials || $this->getRequest()->getMethod() !== 'POST' || !$this->getRequest()->isXmlHttpRequest()) { return $resultRaw->setHttpResponseCode($httpBadRequestCode); } $response = ['errors' => false, 'message' => __('Login successful.')]; try { $customer = $this->customerAccountManagement->authenticate($credentials['username'], $credentials['password']); $this->customerSession->setCustomerDataAsLoggedIn($customer); $this->customerSession->regenerateId(); $redirectRoute = $this->getAccountRedirect()->getRedirectCookie(); if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectRoute) { $response['redirectUrl'] = $this->_redirect->success($redirectRoute); $this->getAccountRedirect()->clearRedirectCookie(); } } catch (EmailNotConfirmedException $e) { $response = ['errors' => true, 'message' => $e->getMessage()]; } catch (InvalidEmailOrPasswordException $e) { $response = ['errors' => true, 'message' => $e->getMessage()]; } catch (\Exception $e) { $response = ['errors' => true, 'message' => __('Invalid login or password.')]; } /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); return $resultJson->setData($response); }
/** * Load file and set path to sample * * @param SampleInterface $sample * @return void */ protected function setFiles(SampleInterface $sample) { if ($sample->getSampleType() == \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE && $sample->getFile()) { $sampleFileName = $this->downloadableFile->moveFileFromTmp($sample->getBaseTmpPath(), $sample->getBasePath(), $this->jsonHelper->jsonDecode($sample->getFile())); $sample->setSampleFile($sampleFileName); $sample->setSampleUrl(null); } }
public function decodeShippingDetails($shippingDetailsEnc) { $decoded = array(); if (!is_null($shippingDetailsEnc) && $shippingDetailsEnc != '') { $decoded = $this->jsonHelper->jsonDecode($shippingDetailsEnc); } return $decoded; }
/** * @param array $item * @return array */ protected function getFiles(array $item) { $files = []; if (isset($item[self::FIELD_FILE]) && $item[self::FIELD_FILE]) { $files = $this->jsonHelper->jsonDecode($item[self::FIELD_FILE]); } return $files; }
/** * @return $this|\Magento\Framework\View\Result\Page */ public function execute() { $paymentMethodNonce = $this->getRequest()->getParam('payment_method_nonce'); $details = $this->getRequest()->getParam('details'); if (!empty($details)) { $details = $this->jsonHelper->jsonDecode($details); } try { $this->initCheckout(); if ($paymentMethodNonce && $details) { if (!$this->braintreePayPalConfig->isBillingAddressEnabled()) { unset($details['billingAddress']); } $this->getCheckout()->initializeQuoteForReview($paymentMethodNonce, $details); $paymentMethod = $this->getQuote()->getPayment()->getMethodInstance(); $paymentMethod->validate(); } else { $paymentMethod = $this->getQuote()->getPayment()->getMethodInstance(); if (!$paymentMethod || $paymentMethod->getCode() !== PayPal::METHOD_CODE) { $this->messageManager->addErrorMessage(__('Incorrect payment method.')); /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); return $resultRedirect->setPath('checkout/cart'); } $this->getQuote()->setMayEditShippingMethod(true); } /** @var \Magento\Framework\View\Result\Page $resultPage */ $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE); /** @var \Magento\Braintree\Block\Checkout\Review $reviewBlock */ $reviewBlock = $resultPage->getLayout()->getBlock('braintree.paypal.review'); $reviewBlock->setQuote($this->getQuote()); $reviewBlock->getChildBlock('shipping_method')->setQuote($this->getQuote()); return $resultPage; } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addExceptionMessage($e, $e->getMessage()); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __('We can\'t initialize checkout review.')); } /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); return $resultRedirect->setPath('checkout/cart'); }
/** * Set model data from info field * * @return $this */ protected function _afterLoad() { parent::_afterLoad(); $info = $this->jsonHelper->jsonDecode($this->getInfo()); if (is_array($info)) { foreach ($info as $key => $value) { $this->setData($key, $value); } } return $this; }
/** * 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; }
/** * Unserialize the sorted_products field of category if it is a string value. * * @param \Magento\Catalog\Model\Category $category Category * * @return array */ private function unserializeProductPositions(\Magento\Catalog\Model\Category $category) { $productPositions = $category->getSortedProducts() ? $category->getSortedProducts() : []; if (is_string($productPositions)) { try { $productPositions = $this->jsonHelper->jsonDecode($productPositions); } catch (\Exception $e) { $productPositions = []; } } $category->setSortedProducts($productPositions); return $this; }
/** * Load files and set paths to link and sample of link * * @param LinkInterface $link * @return void */ protected function setFiles(LinkInterface $link) { if ($link->getSampleType() == \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE && $link->getSampleFileData()) { $linkSampleFileName = $this->downloadableFile->moveFileFromTmp($link->getBaseSampleTmpPath(), $link->getBaseSamplePath(), $this->jsonHelper->jsonDecode($link->getSampleFileData())); $link->setSampleFile($linkSampleFileName); $link->setSampleUrl(null); } if ($link->getLinkType() == \Magento\Downloadable\Helper\Download::LINK_TYPE_FILE && $link->getFile()) { $linkFileName = $this->downloadableFile->moveFileFromTmp($link->getBaseTmpPath(), $link->getBasePath(), $this->jsonHelper->jsonDecode($link->getFile())); $link->setLinkFile($linkFileName); $link->setLinkUrl(null); } }
/** * Get feed url from satis repository. * * To do that we send a request to http://docs.swissuplabs.com/packages/packages.json, * which returns actual packages list url: http://docs.swissuplabs.com/packages/include/all${sha1}.json * * @return string */ protected function getFeedUrl() { $useHttps = $this->scopeConfig->getValue(self::XML_USE_HTTPS_PATH, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); $url = $this->scopeConfig->getValue(self::XML_FEED_URL_PATH, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); // http://docs.swissuplabs.com/packages/packages.json $url = ($useHttps ? 'https://' : 'http://') . $url; $response = $this->fetch($url . '/packages.json'); $response = $this->jsonHelper->jsonDecode($response); if (!is_array($response) || !isset($response['includes'])) { return false; } // http://docs.swissuplabs.com/packages/include/all${sha1}.json return $url . '/' . key($response['includes']); }
/** * Parse server response * * @param string $response * <pre> * "{success: true}" or "{error: error_message}" * </pre> */ protected function parseResponse($response) { try { $result = $this->jsonHelper->jsonDecode($response); if (!is_array($result)) { throw new \Exception('Decoding failed'); } if (is_array($result) && isset($result['error'])) { $result['error'][0] = $this->convertMagento1xTranslation($result['error'][0]); } } catch (\Exception $e) { $result = ['error' => ['Sorry, try again in five minutes. Validation response parsing error: %1', $e->getMessage()], 'response' => $response]; } return $result; }
/** * Get next bunch of validated rows. * * @return array|null */ public function getNextBunch() { if (null === $this->_iterator) { $this->_iterator = $this->getIterator(); $this->_iterator->rewind(); } if ($this->_iterator->valid()) { $dataRow = $this->_iterator->current(); $dataRow = $this->jsonHelper->jsonDecode($dataRow[0]); $this->_iterator->next(); } else { $this->_iterator = null; $dataRow = null; } return $dataRow; }
/** * Get next bunch of validated rows. * * @return array|null */ public function getNextBunch() { if (null === $this->_iterator) { $this->_iterator = $this->getIterator(); $this->_iterator->rewind(); } $dataRow = null; if ($this->_iterator->valid()) { $encodedData = $this->_iterator->current(); if (array_key_exists(0, $encodedData) && $encodedData[0]) { $dataRow = $this->jsonHelper->jsonDecode($encodedData[0]); $this->_iterator->next(); } } if (!$dataRow) { $this->_iterator = null; } return $dataRow; }
/** * @param array $item * @return array */ protected function getFiles(array $item) { $files = isset($item[self::FIELD_FILE]) ? $this->jsonHelper->jsonDecode($item[self::FIELD_FILE]) : []; return $files; }
/** * Generate simple products to link with configurable * * @param \Magento\Catalog\Model\Product $parentProduct * @param array $productsData * @return array */ public function generateSimpleProducts($parentProduct, $productsData) { $this->_prepareAttributeSetToBeBaseForNewVariations($parentProduct); $generatedProductIds = []; foreach ($productsData as $simpleProductData) { $newSimpleProduct = $this->productFactory->create(); $configurableAttribute = $this->jsonHelper->jsonDecode($simpleProductData['configurable_attribute']); unset($simpleProductData['configurable_attribute']); $this->_fillSimpleProductData($newSimpleProduct, $parentProduct, array_merge($simpleProductData, $configurableAttribute)); $newSimpleProduct->save(); $generatedProductIds[] = $newSimpleProduct->getId(); } return $generatedProductIds; }
/** * @param string $entityType * @param object $product * @param array $arguments * @return object * @throws \Magento\Framework\Exception\LocalizedException * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute($entityType, $product, $arguments = []) { $attrCode = $this->getAttribute()->getAttributeCode(); $value = $product->getData($attrCode); if (!is_array($value) || !isset($value['images'])) { return $product; } if (!is_array($value['images']) && strlen($value['images']) > 0) { $value['images'] = $this->jsonHelper->jsonDecode($value['images']); } if (!is_array($value['images'])) { $value['images'] = []; } $clearImages = []; $newImages = []; $existImages = []; if ($product->getIsDuplicate() != true) { foreach ($value['images'] as &$image) { if (!empty($image['removed'])) { $clearImages[] = $image['file']; } elseif (empty($image['value_id'])) { $newFile = $this->moveImageFromTmp($image['file']); $image['new_file'] = $newFile; $newImages[$image['file']] = $image; $image['file'] = $newFile; } else { $existImages[$image['file']] = $image; } } } else { // For duplicating we need copy original images. $duplicate = []; foreach ($value['images'] as &$image) { if (empty($image['value_id']) || !empty($image['removed'])) { continue; } $duplicate[$image['value_id']] = $this->copyImage($image['file']); $image['new_file'] = $duplicate[$image['value_id']]; $newImages[$image['file']] = $image; } $value['duplicate'] = $duplicate; } /* @var $mediaAttribute \Magento\Catalog\Api\Data\ProductAttributeInterface */ foreach ($this->mediaConfig->getMediaAttributeCodes() as $mediaAttrCode) { $attrData = $product->getData($mediaAttrCode); if (in_array($attrData, $clearImages)) { $product->setData($mediaAttrCode, 'no_selection'); } if (in_array($attrData, array_keys($newImages))) { $product->setData($mediaAttrCode, $newImages[$attrData]['new_file']); $product->setData($mediaAttrCode . '_label', $newImages[$attrData]['label']); } if (in_array($attrData, array_keys($existImages))) { $product->setData($mediaAttrCode . '_label', $existImages[$attrData]['label']); } $product->addAttributeUpdate($mediaAttrCode, $product->getData($mediaAttrCode), $product->getStoreId()); } $product->setData($attrCode, $value); if ($product->getIsDuplicate() == true) { $this->duplicate($product); return $product; } if (!is_array($value) || !isset($value['images']) || $product->isLockedAttribute($attrCode)) { return $product; } $this->processDeletedImages($product, $value['images']); $this->processNewAndExistingImages($product, $value['images']); $product->setData($attrCode, $value); return $product; }