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 testJsonEncode() { $expectedValue = 'string'; $this->jsonHelperMock->expects($this->once())->method('jsonEncode')->with($this->equalTo($expectedValue))->will($this->returnValue($expectedValue)); $result = $this->object->jsonEncode($expectedValue); $this->assertEquals($expectedValue, $result); }
/** * 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)); }
public function testExecuteWithException() { $this->requestMock->expects($this->once())->method('getParam')->with('item_id', null)->willReturn('1'); $exception = new \Exception('Error message!'); $this->sidebarMock->expects($this->once())->method('checkQuoteItem')->with(1)->willThrowException($exception); $this->loggerMock->expects($this->once())->method('critical')->with($exception)->willReturn(null); $this->sidebarMock->expects($this->once())->method('getResponseData')->with('Error message!')->willReturn(['success' => false, 'error_message' => 'Error message!']); $this->jsonHelperMock->expects($this->once())->method('jsonEncode')->with(['success' => false, 'error_message' => 'Error message!'])->willReturn('json encoded'); $this->responseMock->expects($this->once())->method('representJson')->with('json encoded')->willReturn('json represented'); $this->assertEquals('json represented', $this->removeItem->executeInternal()); }
/** * 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)); }
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); }
/** * @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)); }
/** * 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); }
/** * @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; }
public function testGetRegionJson() { $countries = [new \Magento\Framework\DataObject(['country_id' => 'Country1']), new \Magento\Framework\DataObject(['country_id' => 'Country2'])]; $countryIterator = new \ArrayIterator($countries); $this->_countryCollection->expects($this->atLeastOnce())->method('getIterator')->will($this->returnValue($countryIterator)); $regions = [new \Magento\Framework\DataObject(['country_id' => 'Country1', 'region_id' => 'r1', 'code' => 'r1-code', 'name' => 'r1-name']), new \Magento\Framework\DataObject(['country_id' => 'Country1', 'region_id' => 'r2', 'code' => 'r2-code', 'name' => 'r2-name']), new \Magento\Framework\DataObject(['country_id' => 'Country2', 'region_id' => 'r3', 'code' => 'r3-code', 'name' => 'r3-name'])]; $regionIterator = new \ArrayIterator($regions); $this->_regionCollection->expects($this->once())->method('addCountryFilter')->with(['Country1', 'Country2'])->will($this->returnSelf()); $this->_regionCollection->expects($this->once())->method('load'); $this->_regionCollection->expects($this->once())->method('getIterator')->will($this->returnValue($regionIterator)); $expectedDataToEncode = ['config' => ['show_all_regions' => false, 'regions_required' => []], 'Country1' => ['r1' => ['code' => 'r1-code', 'name' => 'r1-name'], 'r2' => ['code' => 'r2-code', 'name' => 'r2-name']], 'Country2' => ['r3' => ['code' => 'r3-code', 'name' => 'r3-name']]]; $this->jsonHelperMock->expects($this->once())->method('jsonEncode')->with(new \PHPUnit_Framework_Constraint_IsIdentical($expectedDataToEncode))->will($this->returnValue('encoded_json')); // Test $result = $this->_object->getRegionJson(); $this->assertEquals('encoded_json', $result); }
public function testAfterRenderResultWithWrongArray() { $messageType = 'message1type'; $messageText = 'message1text'; $messages = [['type' => $messageType, 'text' => $messageText]]; /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $resultMock */ $resultMock = $this->getMockBuilder(Redirect::class)->disableOriginalConstructor()->getMock(); /** @var PublicCookieMetadata|\PHPUnit_Framework_MockObject_MockObject $cookieMetadataMock */ $cookieMetadataMock = $this->getMockBuilder(PublicCookieMetadata::class)->disableOriginalConstructor()->getMock(); $this->cookieMetadataFactoryMock->expects($this->once())->method('createPublicCookieMetadata')->willReturn($cookieMetadataMock); $this->cookieManagerMock->expects($this->once())->method('setPublicCookie')->with(MessagePlugin::MESSAGES_COOKIES_NAME, \Zend_Json::encode($messages), $cookieMetadataMock); $this->cookieManagerMock->expects($this->once())->method('getCookie')->with(MessagePlugin::MESSAGES_COOKIES_NAME, \Zend_Json::encode([]))->willReturn(\Zend_Json::encode('string')); $this->dataMock->expects($this->any())->method('jsonDecode')->willReturnCallback(function ($data) { return \Zend_Json::decode($data); }); $this->dataMock->expects($this->any())->method('jsonEncode')->willReturnCallback(function ($data) { return \Zend_Json::encode($data); }); /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject $messageMock */ $messageMock = $this->getMockBuilder(MessageInterface::class)->getMock(); $messageMock->expects($this->once())->method('getType')->willReturn($messageType); $this->interpretationStrategyMock->expects($this->once())->method('interpret')->with($messageMock)->willReturn($messageText); /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */ $collectionMock = $this->getMockBuilder(Collection::class)->disableOriginalConstructor()->getMock(); $collectionMock->expects($this->once())->method('getItems')->willReturn([$messageMock]); $this->managerMock->expects($this->once())->method('getMessages')->with(true, null)->willReturn($collectionMock); $this->assertEquals($resultMock, $this->model->afterRenderResult($resultMock, $resultMock)); }
/** * 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 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; }
/** * 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); } }
/** * 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); }
/** * 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; }
public function decodeShippingDetails($shippingDetailsEnc) { $decoded = array(); if (!is_null($shippingDetailsEnc) && $shippingDetailsEnc != '') { $decoded = $this->jsonHelper->jsonDecode($shippingDetailsEnc); } return $decoded; }
/** * 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; }
/** * @param $paymentMethod * @param $controller * @param $quoteId * @param $result * @dataProvider textExecuteFailedPlaceOrderDataProvider */ public function testExecuteFailedPlaceOrder($paymentMethod, $controller, $quoteId, $result) { $this->requestMock->expects($this->at(0))->method('getParam')->with('payment')->will($this->returnValue($paymentMethod)); $this->requestMock->expects($this->at(1))->method('getParam')->with('controller')->will($this->returnValue($controller)); $this->quoteMock->expects($this->any())->method('getId')->will($this->returnValue($quoteId)); $this->cartManagementMock->expects($this->once())->method('placeOrder')->willThrowException(new \Exception()); $this->jsonHelperMock->expects($this->any())->method('jsonEncode')->with($result); $this->placeOrderController->execute(); }
/** * 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); }
/** * @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'); }
/** * 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)); } }
/** * 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; }
/** * Returns all set custom parameters as JSON string * * @return string */ protected function getJsonForResponse() { $json = ['eventType' => 'Cron', 'appName' => $this->config->getNewRelicAppName(), 'appId' => $this->config->getNewRelicAppId()]; $jsonArrayKeys = array_keys($json); foreach ($jsonArrayKeys as $jsonKey) { if (array_key_exists($jsonKey, $this->customParameters)) { unset($this->customParameters[$jsonKey]); } } $json = array_merge($json, $this->customParameters); return $this->jsonEncoder->encode($json); }
/** * 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; }