public function testIsDevAllowed() { $store = 'some store'; $result = 'result'; $this->helperMock->expects($this->once())->method('isDevAllowed')->with($store)->will($this->returnValue($result)); $this->assertEquals($result, $this->model->isDevAllowed($store)); }
/** * @param string|null $request * @param string|null|false $config * @param string|null $default * @dataProvider getConfigurationCountryCodeFromDefaultDataProvider */ public function testGetConfigurationCountryCodeFromDefault($request, $config, $default) { $this->_configurationCountryCodePrepareRequest($request); $this->_configurationCountryCodePrepareConfig($config); $this->_coreHelper->expects($this->once())->method('getDefaultCountry')->will($this->returnValue($default)); $this->_configurationCountryCodeAssertResult($default); }
/** * Test render method. */ public function testRender() { $arrayToRender = array('key' => 'value'); /** Assert that jsonEncode method in mocked helper will run once */ $this->_helperMock->expects($this->once())->method('jsonEncode'); $this->_restJsonRenderer->render($arrayToRender); }
public function testJsonEncode() { $expectedValue = 'string'; $this->coreHelper->expects($this->once())->method('jsonEncode')->with($this->equalTo($expectedValue))->will($this->returnValue($expectedValue)); $result = $this->object->jsonEncode($expectedValue); $this->assertEquals($expectedValue, $result); }
/** * Get selected merchant country code in system configuration * * @return string */ public function getConfigurationCountryCode() { $countryCode = $this->_request->getParam(\Magento\Paypal\Model\Config\StructurePlugin::REQUEST_PARAM_COUNTRY); if (is_null($countryCode) || preg_match('/^[a-zA-Z]{2}$/', $countryCode) == 0) { $countryCode = $this->_backendConfig->getConfigDataValue(\Magento\Paypal\Block\Adminhtml\System\Config\Field\Country::FIELD_CONFIG_PATH); } if (empty($countryCode)) { $countryCode = $this->_coreHelper->getDefaultCountry(); } return $countryCode; }
/** * Retrieve switch currency url * * @param array $params Additional url params * @return string */ public function getSwitchCurrencyUrl($params = array()) { $params = is_array($params) ? $params : array(); if ($this->_getRequest()->getAlias('rewrite_request_path')) { $url = $this->_storeManager->getStore()->getBaseUrl() . $this->_getRequest()->getAlias('rewrite_request_path'); } else { $url = $this->_urlBuilder->getCurrentUrl(); } $params[\Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED] = $this->_coreData->urlEncode($url); return $this->_getUrl('directory/currency/switch', $params); }
/** * Initialize cache management form * * @return $this */ public function initForm() { /** @var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(); $fieldset = $form->addFieldset('cache_enable', array('legend' => __('Cache Control'))); $fieldset->addField('all_cache', 'select', array('name' => 'all_cache', 'label' => '<strong>' . __('All Cache') . '</strong>', 'value' => 1, 'options' => array('' => __('No change'), 'refresh' => __('Refresh'), 'disable' => __('Disable'), 'enable' => __('Enable')))); foreach ($this->_coreData->getCacheTypes() as $type => $label) { $fieldset->addField('enable_' . $type, 'checkbox', array('name' => 'enable[' . $type . ']', 'label' => __($label), 'value' => 1, 'checked' => (int) $this->_cacheState->isEnabled($type))); } $this->setForm($form); return $this; }
protected function setUp() { $this->_fixtureCustomerId = 1; $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->_customerSession = $this->_objectManager->create('Magento\\Customer\\Model\\Session'); $this->_coreData = $this->_objectManager->create('Magento\\Core\\Helper\\Data'); $this->_contextHelper = $this->_objectManager->create('Magento\\Framework\\App\\Helper\\Context'); $request = $this->_contextHelper->getRequest(); $request->setParam('data', $this->_coreData->urlEncode($this->_fixtureCustomerId)); $this->_wishlistHelper = $this->_objectManager->create('Magento\\Rss\\Helper\\WishlistRss', ['context' => $this->_contextHelper, 'customerSession' => $this->_customerSession]); $this->_customerSession->loginById($this->_fixtureCustomerId); }
/** * Substitute empty value with Default country. * * @return void */ protected function _afterLoad() { $value = (string) $this->getValue(); if (empty($value)) { if ($this->getWebsite()) { $defaultCountry = $this->_storeManager->getWebsite($this->getWebsite())->getConfig(\Magento\Core\Helper\Data::XML_PATH_DEFAULT_COUNTRY); } else { $defaultCountry = $this->_coreData->getDefaultCountry($this->getStore()); } $this->setValue($defaultCountry); } }
/** * Prepare fees info * * @return void */ protected function _prepareLayout() { parent::_prepareLayout(); $this->_shouldRenderInfo = true; $this->_addInfo(array('label' => $this->_fields->getFieldLabel('currency_code'), 'value' => $this->_recurringPayment->getCurrencyCode())); $params = array('init_amount', 'trial_billing_amount', 'billing_amount', 'tax_amount', 'shipping_amount'); foreach ($params as $key) { $value = $this->_recurringPayment->getData($key); if ($value) { $this->_addInfo(array('label' => $this->_fields->getFieldLabel($key), 'value' => $this->_coreHelper->formatCurrency($value, false), 'is_amount' => true)); } } }
/** * Get JSON encoded configuration array which can be used for JS dynamic * price calculation depending on product options * * @return string */ public function getJsonConfig() { $config = array(); if (!$this->hasOptions()) { return $this->_jsonEncoder->encode($config); } $customerId = $this->getCustomerId(); /* @var $product \Magento\Catalog\Model\Product */ $product = $this->getProduct(); $defaultTax = $this->taxCalculationService->getDefaultCalculatedRate($product->getTaxClassId(), $customerId); $currentTax = $this->taxCalculationService->getCalculatedRate($product->getTaxClassId(), $customerId); $tierPrices = array(); $tierPricesList = $product->getPriceInfo()->getPrice('tier_price')->getTierPriceList(); foreach ($tierPricesList as $tierPrice) { $tierPrices[] = $this->_coreData->currency($tierPrice['price']->getValue(), false, false); } $config = array('productId' => $product->getId(), 'priceFormat' => $this->_localeFormat->getPriceFormat(), 'includeTax' => $this->_taxData->priceIncludesTax() ? 'true' : 'false', 'showIncludeTax' => $this->_taxData->displayPriceIncludingTax(), 'showBothPrices' => $this->_taxData->displayBothPrices(), 'productPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('final_price')->getValue(), false, false), 'productOldPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(), false, false), 'inclTaxPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(), false, false), 'exclTaxPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('final_price')->getAmount()->getBaseAmount(), false, false), 'defaultTax' => $defaultTax, 'currentTax' => $currentTax, 'idSuffix' => '_clone', 'oldPlusDisposition' => 0, 'plusDisposition' => 0, 'plusDispositionTax' => 0, 'oldMinusDisposition' => 0, 'minusDisposition' => 0, 'tierPrices' => $tierPrices); $responseObject = new \Magento\Framework\Object(); $this->_eventManager->dispatch('catalog_product_view_config', array('response_object' => $responseObject)); if (is_array($responseObject->getAdditionalOptions())) { foreach ($responseObject->getAdditionalOptions() as $option => $value) { $config[$option] = $value; } } return $this->_jsonEncoder->encode($config); }
/** * @param \Magento\Framework\Object $object * @return $this|void */ 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->_coreData->jsonDecode($value['images']); } if (!is_array($value['images'])) { $value['images'] = array(); } $clearImages = array(); $newImages = array(); $existImages = array(); 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 = array(); 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; }
/** * Retrieve tracking url with params * * @param string $key * @param \Magento\Sales\Model\Order|\Magento\Sales\Model\Order\Shipment|\Magento\Sales\Model\Order\Shipment\Track $model * @param string $method Optional - method of a model to get id * @return string */ protected function _getTrackingUrl($key, $model, $method = 'getId') { $urlPart = "{$key}:{$model->{$method}()}:{$model->getProtectCode()}"; $param = array('hash' => $this->_coreData->urlEncode($urlPart)); $storeModel = $this->_storeManager->getStore($model->getStoreId()); return $storeModel->getUrl('shipping/tracking/popup', $param); }
/** * 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', array('product' => $parentProduct, 'variations' => $products)); $validationResult = array(); 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($productData); $product->setCollectExceptionMessages(true); $configurableAttribute = $this->coreHelper->jsonDecode($productData['configurable_attribute']); $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; }
public function testGetRegionJson() { $countries = array(new \Magento\Framework\Object(array('country_id' => 'Country1')), new \Magento\Framework\Object(array('country_id' => 'Country2'))); $countryIterator = new \ArrayIterator($countries); $this->_countryCollection->expects($this->atLeastOnce())->method('getIterator')->will($this->returnValue($countryIterator)); $regions = array(new \Magento\Framework\Object(array('country_id' => 'Country1', 'region_id' => 'r1', 'code' => 'r1-code', 'name' => 'r1-name')), new \Magento\Framework\Object(array('country_id' => 'Country1', 'region_id' => 'r2', 'code' => 'r2-code', 'name' => 'r2-name')), new \Magento\Framework\Object(array('country_id' => 'Country2', 'region_id' => 'r3', 'code' => 'r3-code', 'name' => 'r3-name'))); $regionIterator = new \ArrayIterator($regions); $this->_regionCollection->expects($this->once())->method('addCountryFilter')->with(array('Country1', 'Country2'))->will($this->returnSelf()); $this->_regionCollection->expects($this->once())->method('load'); $this->_regionCollection->expects($this->once())->method('getIterator')->will($this->returnValue($regionIterator)); $expectedDataToEncode = array('config' => array('show_all_regions' => false, 'regions_required' => array()), 'Country1' => array('r1' => array('code' => 'r1-code', 'name' => 'r1-name'), 'r2' => array('code' => 'r2-code', 'name' => 'r2-name')), 'Country2' => array('r3' => array('code' => 'r3-code', 'name' => 'r3-name'))); $this->_coreHelper->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); }
/** * Retrieve credit cards info * * @return array */ public function getCards() { $cardsData = $this->getMethod()->getCardsStorage()->getCards(); $cards = array(); if (is_array($cardsData)) { foreach ($cardsData as $cardInfo) { $data = array(); if ($cardInfo->getProcessedAmount()) { $amount = $this->_coreData->currency($cardInfo->getProcessedAmount(), true, false); $data[__('Processed Amount')] = $amount; } if ($cardInfo->getBalanceOnCard() && is_numeric($cardInfo->getBalanceOnCard())) { $balance = $this->_coreData->currency($cardInfo->getBalanceOnCard(), true, false); $data[__('Remaining Balance')] = $balance; } $cardInfo->setMethodInstance($this->getInfo()->getMethodInstance()); $this->setCardInfoObject($cardInfo); $cards[] = array_merge($this->getSpecificInformation(), $data); $this->unsCardInfoObject(); $this->_paymentSpecificInformation = null; } } if ($this->getInfo()->getCcType() && $this->_isCheckoutProgressBlockFlag) { $cards[] = $this->getSpecificInformation(); } return $cards; }
/** * 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; }
/** * Parse Request body into array of params. * * @param string $encodedBody Posted content from request. * @return array|null Return NULL if content is invalid. * @throws \InvalidArgumentException * @throws \Magento\Webapi\Exception If decoding error was encountered. */ public function deserialize($encodedBody) { if (!is_string($encodedBody)) { throw new \InvalidArgumentException(sprintf('"%s" data type is invalid. String is expected.', gettype($encodedBody))); } try { $decodedBody = $this->_helper->jsonDecode($encodedBody); } catch (\Zend_Json_Exception $e) { if ($this->_appState->getMode() !== State::MODE_DEVELOPER) { throw new \Magento\Webapi\Exception(__('Decoding error.')); } else { throw new \Magento\Webapi\Exception(__('Decoding error: %1%2%3%4', PHP_EOL, $e->getMessage(), PHP_EOL, $e->getTraceAsString())); } } return $decodedBody; }
/** * @param \Magento\Framework\App\Helper\Context $context * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Framework\App\State $appState * @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency * @param Data $persistentData * @param \Magento\Checkout\Model\Session $checkoutSession * @param \Magento\Persistent\Model\SessionFactory $sessionFactory * @param bool $dbCompatibleMode */ public function __construct(\Magento\Framework\App\Helper\Context $context, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\App\State $appState, \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency, \Magento\Persistent\Helper\Data $persistentData, \Magento\Checkout\Model\Session $checkoutSession, \Magento\Persistent\Model\SessionFactory $sessionFactory, $dbCompatibleMode = true) { $this->_persistentData = $persistentData; $this->_checkoutSession = $checkoutSession; $this->_sessionFactory = $sessionFactory; parent::__construct($context, $scopeConfig, $storeManager, $appState, $priceCurrency, $dbCompatibleMode); }
public function testDeserializeInvalidEncodedBodyExceptionDeveloperModeOn() { /** Prepare mocks for SUT constructor. */ $this->_helperMock->expects($this->once())->method('jsonDecode')->will($this->throwException(new \Zend_Json_Exception('Decoding error:' . PHP_EOL . 'Decoding failed: Syntax error'))); $this->_appStateMock->expects($this->once())->method('getMode')->will($this->returnValue('developer')); /** Initialize SUT. */ $inputInvalidJson = '{"key1":"test1"."key2":"test2"}'; try { $this->_jsonDeserializer->deserialize($inputInvalidJson); $this->fail("Exception is expected to be raised"); } catch (\Magento\Webapi\Exception $e) { $this->assertInstanceOf('Magento\\Webapi\\Exception', $e, 'Exception type is invalid'); $this->assertContains('Decoding error:', $e->getMessage(), 'Exception message is invalid'); $this->assertEquals(\Magento\Webapi\Exception::HTTP_BAD_REQUEST, $e->getHttpCode(), 'HTTP code is invalid'); } }
/** * @param \Magento\Framework\App\Helper\Context $context * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Framework\App\State $appState * @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency * @param \Magento\Framework\App\Filesystem $filesystem * @param \Magento\Framework\Convert\Xml $xmlConverter * @param bool $dbCompatibleMode */ public function __construct(\Magento\Framework\App\Helper\Context $context, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\App\State $appState, \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency, \Magento\Framework\App\Filesystem $filesystem, \Magento\Framework\Convert\Xml $xmlConverter, $dbCompatibleMode = true) { $this->filesystem = $filesystem; $this->readDirectory = $this->filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem::VAR_DIR); $this->_xmlConverter = $xmlConverter; parent::__construct($context, $scopeConfig, $storeManager, $appState, $priceCurrency, $dbCompatibleMode); }
/** * @dataProvider dataProviderGetBmlDisplay */ public function testGetBmlDisplay($section, $expectedValue, $expectedFlag, $expected) { $this->_model->setStoreId(1); $this->_coreData->expects($this->any())->method('getDefaultCountry')->with(1)->will($this->returnValue('US')); $this->_scopeConfig->expects($this->any())->method('isSetFlag')->will($this->returnValue($expectedFlag)); $this->_scopeConfig->expects($this->any())->method('getValue')->will($this->returnValueMap([['payment/' . Config::METHOD_WPP_BML . '/' . $section . '_display', 'store', 1, $expectedValue], ['payment/' . Config::METHOD_WPP_BML . '/active', 'store', 1, $expectedValue], ['payment/' . Config::METHOD_WPP_PE_BML . '/active', 'store', 1, $expectedValue]])); $this->assertEquals($expected, $this->_model->getBmlDisplay($section)); }
/** * Test default render format is JSON. */ public function testRenderDefaultFormat() { /** Set undefined rendering format. */ $_SERVER['HTTP_ACCEPT'] = 'undefined'; /** Assert that jsonEncode method will be executed at least once. */ $this->_helperMock->expects($this->atLeastOnce())->method('jsonEncode'); $this->_errorProcessor->render('Message'); }
public function testFormatPrice() { $amount = '120'; $includeContainer = false; $result = '10grn.'; $this->priceCurrency->expects($this->once())->method('format')->with($amount, $includeContainer)->will($this->returnValue($result)); $this->assertEquals($result, $this->model->formatPrice($amount, $includeContainer)); }
/** * @return string */ public function getCountryId() { $countryId = $this->getData('country_id'); if (is_null($countryId)) { $countryId = $this->_coreData->getDefaultCountry(); } return $countryId; }
/** * 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; }
/** * 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); }
/** * @param string $type * @return string */ public function getCountryHtmlSelect($type) { $countryId = $this->getAddress()->getCountryId(); if (is_null($countryId)) { $countryId = $this->_coreData->getDefaultCountry(); } $select = $this->getLayout()->createBlock('Magento\\Framework\\View\\Element\\Html\\Select')->setName($type . '[country_id]')->setId($type . ':country_id')->setTitle(__('Country'))->setClass('validate-select')->setValue($countryId)->setOptions($this->getCountryOptions()); return $select->getHtml(); }
/** * 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); } }
/** * 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); }