/** * Post request into gateway * * @param Object $request * @param ConfigInterface $config * * @return Object * @throws \Exception */ public function postRequest(Object $request, ConfigInterface $config) { $result = new Object(); $clientConfig = ['maxredirects' => 5, 'timeout' => 30, 'verifypeer' => $config->getValue('verify_peer')]; if ($config->getValue('use_proxy')) { $clientConfig['proxy'] = $config->getValue('proxy_host') . ':' . $config->getValue('proxy_port'); $clientConfig['httpproxytunnel'] = true; $clientConfig['proxytype'] = CURLPROXY_HTTP; } /** @var ZendClient $client */ $client = $this->httpClientFactory->create(); $client->setUri((bool) $config->getValue('sandbox_flag') ? $config->getValue('transaction_url_test_mode') : $config->getValue('transaction_url')); $client->setConfig($clientConfig); $client->setMethod(\Zend_Http_Client::POST); $client->setParameterPost($request->getData()); $client->setHeaders(['X-VPS-VIT-CLIENT-CERTIFICATION-ID' => '33baf5893fc2123d8b191d2d011b7fdc', 'X-VPS-Request-ID' => $this->mathRandom->getUniqueHash(), 'X-VPS-CLIENT-TIMEOUT' => 45]); $client->setUrlEncodeBody(false); try { $response = $client->request(); $responseArray = []; parse_str(strstr($response->getBody(), 'RESULT'), $responseArray); $result->setData(array_change_key_case($responseArray, CASE_LOWER)); $result->setData('result_code', $result->getData('result')); } catch (\Exception $e) { $result->addData(['response_code' => -1, 'response_reason_code' => $e->getCode(), 'response_reason_text' => $e->getMessage()]); throw $e; } finally { $this->logger->debug(['request' => $request->getData(), 'result' => $result->getData()], (array) $config->getValue('getDebugReplacePrivateDataKeys'), (bool) $config->getValue('debug')); } return $result; }
/** * After save * * @param \Magento\Framework\Object $object * @return $this|void */ public function afterSave($object) { $value = $object->getData($this->getAttribute()->getName()); if (is_array($value) && !empty($value['delete'])) { $object->setData($this->getAttribute()->getName(), ''); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); return; } try { /** @var $uploader \Magento\Core\Model\File\Uploader */ $uploader = $this->_fileUploaderFactory->create(array('fileId' => $this->getAttribute()->getName())); $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png')); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); } catch (\Exception $e) { return $this; } $path = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem::MEDIA_DIR)->getAbsolutePath('catalog/product/'); $uploader->save($path); $fileName = $uploader->getUploadedFileName(); if ($fileName) { $object->setData($this->getAttribute()->getName(), $fileName); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); } return $this; }
/** * Save uploaded file and set its name to category * * @param \Magento\Framework\Object $object * @return \Magento\Catalog\Model\Category\Attribute\Backend\Image */ public function afterSave($object) { $value = $object->getData($this->getAttribute()->getName() . '_additional_data'); // if no image was set - nothing to do if (empty($value) && empty($_FILES)) { return $this; } if (is_array($value) && !empty($value['delete'])) { $object->setData($this->getAttribute()->getName(), ''); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); return $this; } $path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('catalog/category/'); try { /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */ $uploader = $this->_fileUploaderFactory->create(['fileId' => $this->getAttribute()->getName()]); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $uploader->setAllowRenameFiles(true); $result = $uploader->save($path); $object->setData($this->getAttribute()->getName(), $result['file']); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); } catch (\Exception $e) { if ($e->getCode() != \Magento\MediaStorage\Model\File\Uploader::TMP_NAME_EMPTY) { $this->_logger->critical($e); } } return $this; }
/** * Prepare data before save * * @param \Magento\Framework\Object $object * @return $this */ protected function _beforeSave($object) { if (!$object->getData($this->getAttribute()->getAttributeCode())) { $object->setData($this->getAttribute()->getAttributeCode(), $this->_storeManager->getStore()->getId()); } return $this; }
/** * @param string * @dataProvider validateProvider */ public function testValidate($data) { $object = new Object(); $object->setData($this->attributeName, $data); $this->assertTrue($this->model->validate($object)); $this->assertTrue($this->model->validate($object)); }
/** * Set attribute default value if value empty * * @param \Magento\Framework\Object $object * @return $this */ public function beforeSave($object) { $attributeCode = $this->getAttribute()->getName(); if ($object->getData('use_config_' . $attributeCode)) { $object->setData($attributeCode, ''); } return $this; }
/** * Restore old attribute value * * @param \Magento\Framework\Object $object * @param mixed $oldAttrValue * @return void */ protected function _restoreOldAttrValue($object, $oldAttrValue) { $attrCode = $this->getAttribute(); if (is_null($oldAttrValue)) { $object->unsetData($attrCode); } else { $object->setData($attrCode, $oldAttrValue); } }
/** * Formatting date value before save * * Should set (bool, string) correct type for empty value from html form, * necessary for further process, else date string * * @param \Magento\Framework\Object $object * @throws \Magento\Framework\Exception\LocalizedException * @return $this */ public function beforeSave($object) { $attributeName = $this->getAttribute()->getName(); $_formated = $object->getData($attributeName . '_is_formated'); if (!$_formated && $object->hasData($attributeName)) { try { $value = $this->formatDate($object->getData($attributeName)); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(__('Invalid date')); } if (is_null($value)) { $value = $object->getData($attributeName); } $object->setData($attributeName, $value); $object->setData($attributeName . '_is_formated', true); } return $this; }
/** * Tests \Magento\Framework\Object->debug() */ public function testDebug() { $data = ['key1' => 'value1', 'key2' => ['test'], 'key3' => $this->_object]; $this->_object->setData($data); $debug = $data; unset($debug['key3']); $debug['key3 (Magento\\Framework\\Object)'] = '*** RECURSION ***'; $this->assertEquals($debug, $this->_object->debug()); }
/** * Find an element in layout, render it and return string with its output * * @param string $name * @param bool $useCache * @return string */ public function renderElement($name, $useCache = true) { $this->build(); if (!isset($this->_renderElementCache[$name]) || !$useCache) { $this->_renderElementCache[$name] = $this->renderNonCachedElement($name); } $this->_renderingOutput->setData('output', $this->_renderElementCache[$name]); $this->_eventManager->dispatch('core_layout_render_element', ['element_name' => $name, 'layout' => $this, 'transport' => $this->_renderingOutput]); return $this->_renderingOutput->getData('output'); }
/** * Before save * * @param \Magento\Framework\Object $object * @return $this */ public function beforeSave($object) { $attributeName = $this->getAttribute()->getName(); $urlKey = $object->getData($attributeName); if ($urlKey == '') { $urlKey = $object->getName(); } $object->setData($attributeName, $object->formatUrlKey($urlKey)); return $this; }
/** * Before save * * @param \Magento\Framework\Object $object * @return $this */ public function beforeSave($object) { if ($object->getId()) { return $this; } if (!$object->hasData('website_id')) { $object->setData('website_id', $this->_storeManager->getStore()->getWebsiteId()); } return $this; }
/** * Prepare data for save * * @param \Magento\Framework\Object $object * @return \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend */ public function beforeSave($object) { $attributeCode = $this->getAttribute()->getAttributeCode(); $data = $object->getData($attributeCode); if (is_array($data)) { $data = array_filter($data); $object->setData($attributeCode, implode(',', $data)); } return parent::beforeSave($object); }
/** * Try to unserialize the attribute value * * @param \Magento\Framework\Object $object * @return $this */ protected function _unserialize(\Magento\Framework\Object $object) { $attrCode = $this->getAttribute()->getAttributeCode(); if ($object->getData($attrCode)) { try { $unserialized = unserialize($object->getData($attrCode)); $object->setData($attrCode, $unserialized); } catch (\Exception $e) { $object->unsetData($attrCode); } } return $this; }
/** * Before save * * @param \Magento\Framework\Object $object * @return $this */ public function beforeSave($object) { if ($object->getId()) { return $this; } if (!$object->hasStoreId()) { $object->setStoreId($this->_storeManager->getStore()->getId()); } if (!$object->hasData('created_in')) { $object->setData('created_in', $this->_storeManager->getStore($object->getStoreId())->getName()); } return $this; }
/** * Load an object by customer_id & coupon_id * * @param \Magento\Framework\Object $object * @param int $customerId * @param mixed $couponId * @return $this */ public function loadByCustomerCoupon(\Magento\Framework\Object $object, $customerId, $couponId) { $read = $this->_getReadAdapter(); if ($read && $couponId && $customerId) { $select = $read->select()->from($this->getMainTable())->where('customer_id =:customet_id')->where('coupon_id = :coupon_id'); $data = $read->fetchRow($select, [':coupon_id' => $couponId, ':customet_id' => $customerId]); if ($data) { $object->setData($data); } } if ($object instanceof \Magento\Framework\Model\AbstractModel) { $this->_afterLoad($object); } return $this; }
/** * Prepare existing row data object * * @param \Magento\Framework\Object $row * @return void */ protected function _prepareArrayRow(\Magento\Framework\Object $row) { $country = $row->getCountryId(); $options = []; if ($country) { $options['option_' . $this->getCountryRenderer()->calcOptionHash($country)] = 'selected="selected"'; $ccTypes = $row->getCcTypes(); if (!is_array($ccTypes)) { $ccTypes = [$ccTypes]; } foreach ($ccTypes as $cardType) { $options['option_' . $this->getCcTypesRenderer()->calcOptionHash($cardType)] = 'selected="selected"'; } } $row->setData('option_extra_attrs', $options); return; }
/** * Find an element in layout, render it and return string with its output * * @param string $name * @param bool $useCache * @return string */ public function renderElement($name, $useCache = true) { $this->build(); if (!isset($this->_renderElementCache[$name]) || !$useCache) { if ($this->isUiComponent($name)) { $result = $this->_renderUiComponent($name); } elseif ($this->isBlock($name)) { $result = $this->_renderBlock($name); } else { $result = $this->_renderContainer($name); } $this->_renderElementCache[$name] = $result; } $this->_renderingOutput->setData('output', $this->_renderElementCache[$name]); $this->_eventManager->dispatch('core_layout_render_element', ['element_name' => $name, 'layout' => $this, 'transport' => $this->_renderingOutput]); return $this->_renderingOutput->getData('output'); }
/** * @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; }
/** * Fills request object with Dhl config parameters * * @param \Magento\Framework\Object $requestObject * @return \Magento\Framework\Object */ protected function _addParams(\Magento\Framework\Object $requestObject) { foreach ($this->_requestVariables as $code => $objectCode) { if ($this->_request->getDhlId()) { $value = $this->_request->getData($objectCode['code']); } else { $value = $this->getConfigData($code); } $requestObject->setData($objectCode['setCode'], $value); } return $requestObject; }
/** * Initialize attribute value for object * * @param \Magento\Framework\Object $object * @param array $valueRow * @return $this */ protected function _setAttributeValue($object, $valueRow) { $attribute = $this->getAttribute($valueRow['attribute_id']); if ($attribute) { $attributeCode = $attribute->getAttributeCode(); $object->setData($attributeCode, $valueRow['value']); $attribute->getBackend()->setEntityValueId($object, $valueRow['value_id']); } return $this; }
/** * Post request to gateway and return response * * @param \Magento\Authorizenet\Model\Authorizenet\Request $request * @return \Magento\Authorizenet\Model\Authorizenet\Result * @throws \Magento\Framework\Model\Exception */ protected function _postRequest(\Magento\Framework\Object $request) { $debugData = array('request' => $request->getData()); $result = $this->_resultFactory->create(); $client = new \Magento\Framework\HTTP\ZendClient(); $uri = $this->getConfigData('cgi_url'); $client->setUri($uri ? $uri : self::CGI_URL); $client->setConfig(array('maxredirects' => 0, 'timeout' => 30)); foreach ($request->getData() as $key => $value) { $request->setData($key, str_replace(self::RESPONSE_DELIM_CHAR, '', $value)); } $request->setXDelimChar(self::RESPONSE_DELIM_CHAR); $client->setParameterPost($request->getData()); $client->setMethod(\Zend_Http_Client::POST); try { $response = $client->request(); } catch (\Exception $e) { $result->setResponseCode(-1)->setResponseReasonCode($e->getCode())->setResponseReasonText($e->getMessage()); $debugData['result'] = $result->getData(); $this->_debug($debugData); throw new \Magento\Framework\Model\Exception($this->_wrapGatewayError($e->getMessage())); } $responseBody = $response->getBody(); $r = explode(self::RESPONSE_DELIM_CHAR, $responseBody); if ($r) { $result->setResponseCode((int) str_replace('"', '', $r[0]))->setResponseSubcode((int) str_replace('"', '', $r[1]))->setResponseReasonCode((int) str_replace('"', '', $r[2]))->setResponseReasonText($r[3])->setApprovalCode($r[4])->setAvsResultCode($r[5])->setTransactionId($r[6])->setInvoiceNumber($r[7])->setDescription($r[8])->setAmount($r[9])->setMethod($r[10])->setTransactionType($r[11])->setCustomerId($r[12])->setMd5Hash($r[37])->setCardCodeResponseCode($r[38])->setCAVVResponseCode(isset($r[39]) ? $r[39] : null)->setSplitTenderId($r[52])->setAccNumber($r[50])->setCardType($r[51])->setRequestedAmount($r[53])->setBalanceOnCard($r[54]); } else { throw new \Magento\Framework\Model\Exception(__('Something went wrong in the payment gateway.')); } $debugData['result'] = $result->getData(); $this->_debug($debugData); return $result; }
/** * Sets data to transport * * @param \Magento\Framework\Object $transport * @param string $field * @param string $value * @return void */ protected function setDataToTransfer(\Magento\Framework\Object $transport, $field, $value) { $transport->setData((string) $this->getLabel($field), (string) $this->getValueView($field, $value)); }
/** * Set modified date * * @param \Magento\Framework\Object $object * @return $this */ public function beforeSave($object) { $object->setData($this->getAttribute()->getAttributeCode(), $this->dateTime->now()); return $this; }
/** * Unserialize \Magento\Framework\Object field in an object * * @param \Magento\Framework\Model\AbstractModel $object * @param string $field * @param mixed $defaultValue * @return void */ protected function _unserializeField(\Magento\Framework\Object $object, $field, $defaultValue = null) { $value = $object->getData($field); if (empty($value)) { $object->setData($field, $defaultValue); } elseif (!is_array($value) && !is_object($value)) { $object->setData($field, unserialize($value)); } }
/** * Prepare existing row data object * * @param \Magento\Framework\Object $row * @return void */ protected function _prepareArrayRow(\Magento\Framework\Object $row) { $optionExtraAttr = []; $optionExtraAttr['option_' . $this->_getGroupRenderer()->calcOptionHash($row->getData('customer_group_id'))] = 'selected="selected"'; $row->setData('option_extra_attrs', $optionExtraAttr); }
/** * Component data setter * * @param string|array $key * @param mixed $value * @return void */ public function setData($key, $value = null) { parent::setData($key, $value); }
/** * Create order action * * @return \Magento\Framework\Controller\ResultInterface * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function execute() { if (!$this->_formKeyValidator->validate($this->getRequest())) { return $this->resultRedirectFactory->create()->setPath('*/*/'); } if ($this->_expireAjax()) { return $this->_ajaxRedirectResponse(); } $result = new Object(); try { $agreementsValidator = $this->_objectManager->get('Magento\\Checkout\\Model\\Agreements\\AgreementsValidator'); if (!$agreementsValidator->isValid(array_keys($this->getRequest()->getPost('agreement', [])))) { $result->setData('success', false); $result->setData('error', true); $result->setData('error_messages', __('Please agree to all the terms and conditions before placing the order.')); return $this->resultJsonFactory->create()->setData($result->getData()); } $data = $this->getRequest()->getPost('payment', []); if ($data) { $data['checks'] = [\Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_CHECKOUT, \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_COUNTRY, \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_CURRENCY, \Magento\Payment\Model\Method\AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, \Magento\Payment\Model\Method\AbstractMethod::CHECK_ZERO_TOTAL]; $this->getOnepage()->getQuote()->getPayment()->setQuote($this->getOnepage()->getQuote()); $this->getOnepage()->getQuote()->getPayment()->importData($data); } $this->getOnepage()->saveOrder(); $redirectUrl = $this->getOnepage()->getCheckout()->getRedirectUrl(); $result->setData('success', true); $result->setData('error', false); } catch (PaymentException $e) { $message = $e->getMessage(); if (!empty($message)) { $result->setData('error_messages', $message); } $result->setData('goto_section', 'payment'); $result->setData('update_section', ['name' => 'payment-method', 'html' => $this->_getPaymentMethodsHtml()]); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); $this->_objectManager->get('Magento\\Checkout\\Helper\\Data')->sendPaymentFailedEmail($this->getOnepage()->getQuote(), $e->getMessage()); $result->setData('success', false); $result->setData('error', true); $result->setData('error_messages', $e->getMessage()); $gotoSection = $this->getOnepage()->getCheckout()->getGotoSection(); if ($gotoSection) { $result->setData('goto_section', $gotoSection); $this->getOnepage()->getCheckout()->setGotoSection(null); } $updateSection = $this->getOnepage()->getCheckout()->getUpdateSection(); if ($updateSection) { if (isset($this->_sectionUpdateFunctions[$updateSection])) { $updateSectionFunction = $this->_sectionUpdateFunctions[$updateSection]; $result->setData('update_section', ['name' => $updateSection, 'html' => $this->{$updateSectionFunction}()]); } $this->getOnepage()->getCheckout()->setUpdateSection(null); } } catch (\Exception $e) { $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); $this->_objectManager->get('Magento\\Checkout\\Helper\\Data')->sendPaymentFailedEmail($this->getOnepage()->getQuote(), $e->getMessage()); $result->setData('success', false); $result->setData('error', true); $result->setData('error_messages', __('Something went wrong while processing your order. Please try again later.')); } /** * when there is redirect to third party, we don't want to save order yet. * we will save the order in return action. */ if (isset($redirectUrl)) { $result->setData('redirect', $redirectUrl); } $this->_eventManager->dispatch('checkout_controller_onepage_saveOrder', ['result' => $result, 'action' => $this]); return $this->resultJsonFactory->create()->setData($result->getData()); }
/** * Export page style current settings to specified object * * @param \Magento\Framework\Object $to * @return void */ public function exportExpressCheckoutStyleSettings(\Magento\Framework\Object $to) { foreach ($this->_ecStyleConfigMap as $key => $exportKey) { $configValue = $this->getConfigValue($key); if ($configValue) { $to->setData($exportKey, $configValue); } } }
/** * Before save method * * @param \Magento\Framework\Object $object * @return $this */ public function beforeSave($object) { $attrCode = $this->getAttribute()->getAttributeCode(); if (!$object->hasData($attrCode) && $this->getDefaultValue()) { $object->setData($attrCode, $this->getDefaultValue()); } return $this; }