本文整理汇总了PHP中Magento\Framework\Json\Helper\Data类的典型用法代码示例。如果您正苦于以下问题:PHP Data类的具体用法?PHP Data怎么用?PHP Data使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Data类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testJsonEncodeDecode
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));
}
示例2: execute
/**
* Login registered users and initiate a session.
*
* Expects a POST. ex for JSON {"username":"user@magento.com", "password":"userpassword"}
*
* @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);
}
示例3: jsonResponse
/**
* 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));
}
示例4: testExecuteWithException
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());
}
示例5: execute
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);
}
示例6: execute
/**
* Login registered users and initiate a session.
*
* Expects a POST. ex for JSON {"username":"user@magento.com", "password":"userpassword"}
*
* @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);
}
示例7: beforeSave
/**
* @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;
}
示例8: testGetRegionJson
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);
}
示例9: _validateProductVariations
/**
* 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;
}
示例10: testJsonDecode
public function testJsonDecode()
{
$expected = '"valueToDecode"';
$valueToDecode = 'valueToDecode';
$this->jsonDecoderMock->expects($this->once())->method('decode')->willReturn($expected);
$this->assertEquals($expected, $this->helper->jsonDecode($valueToDecode));
}
示例11: testJsonEncode
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);
}
示例12: _redirect
/**
* 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);
}
}
示例13: 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));
}
示例14: execute
/**
* @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));
}
示例15: testAfterRenderResultWithWrongArray
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));
}