• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP Helper\Data类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中Magento\Framework\Json\Helper\Data的典型用法代码示例。如果您正苦于以下问题:PHP Data类的具体用法?PHP Data怎么用?PHP Data使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Data类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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));
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:7,代码来源:DataTest.php


示例2: execute

 /**
  * Login registered users and initiate a session.
  *
  * Expects a POST. ex for JSON {"username":"[email protected]", "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);
 }
开发者ID:whoople,项目名称:magento2-testing,代码行数:37,代码来源:Login.php


示例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));
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:16,代码来源:RemoveItem.php


示例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());
 }
开发者ID:nblair,项目名称:magescotch,代码行数:11,代码来源:RemoveItemTest.php


示例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);
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:13,代码来源:AdminSaveVatexempt.php


示例6: execute

 /**
  * Login registered users and initiate a session.
  *
  * Expects a POST. ex for JSON {"username":"[email protected]", "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);
 }
开发者ID:rafaelstz,项目名称:magento2,代码行数:43,代码来源:Login.php


示例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;
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:66,代码来源:Media.php


示例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);
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:16,代码来源:DataTest.php


示例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;
 }
开发者ID:tingyeeh,项目名称:magento2,代码行数:41,代码来源:Plugin.php


示例10: testExecuteFailedPlaceOrder

 /**
  * @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();
 }
开发者ID:pradeep-wagento,项目名称:magento2,代码行数:16,代码来源:PlaceTest.php


示例11: execute

 /**
  * 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));
     }
 }
开发者ID:dotmailer,项目名称:dotmailer-magento2-extension,代码行数:23,代码来源:Ajaxvalidation.php


示例12: _afterLoad

 /**
  * 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;
 }
开发者ID:nja78,项目名称:magento2,代码行数:16,代码来源:Session.php


示例13: testJsonDecode

 public function testJsonDecode()
 {
     $expected = '"valueToDecode"';
     $valueToDecode = 'valueToDecode';
     $this->jsonDecoderMock->expects($this->once())->method('decode')->willReturn($expected);
     $this->assertEquals($expected, $this->helper->jsonDecode($valueToDecode));
 }
开发者ID:pradeep-wagento,项目名称:magento2,代码行数:7,代码来源:DataTest.php


示例14: 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);
 }
开发者ID:pradeep-wagento,项目名称:magento2,代码行数:7,代码来源:PriceBoxTest.php


示例15: _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);
     }
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:16,代码来源:Integration.php


示例16: 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));
 }
开发者ID:nblair,项目名称:magescotch,代码行数:16,代码来源:GetAttributes.php


示例17: 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));
 }
开发者ID:pradeep-wagento,项目名称:magento2,代码行数:18,代码来源:ListAction.php


示例18: 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));
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:28,代码来源:MessagePluginTest.php


示例19: getFiles

 /**
  * @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;
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:12,代码来源:AbstractTypeHandler.php


示例20: setFiles

 /**
  * 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);
     }
 }
开发者ID:hientruong90,项目名称:magento2_installer,代码行数:14,代码来源:SampleRepository.php



注:本文中的Magento\Framework\Json\Helper\Data类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP Locale\FormatInterface类代码示例发布时间:2022-05-23
下一篇:
PHP Json\EncoderInterface类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap