/** * {@inheritdoc} * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function validateValue($value) { $errors = []; $attribute = $this->getAttribute(); $label = __($attribute->getStoreLabel()); if ($value === false) { // try to load original value and validate it $value = $this->_value; } if ($attribute->isRequired() && empty($value) && $value !== '0') { $errors[] = __('"%1" is a required value.', $label); } if (!$errors && !$attribute->isRequired() && empty($value)) { return true; } // validate length $length = $this->_string->strlen(trim($value)); $validateRules = $attribute->getValidationRules(); $minTextLength = ArrayObjectSearch::getArrayElementByName($validateRules, 'min_text_length'); if ($minTextLength !== null && $length < $minTextLength) { $errors[] = __('"%1" length must be equal or greater than %2 characters.', $label, $minTextLength); } $maxTextLength = ArrayObjectSearch::getArrayElementByName($validateRules, 'max_text_length'); if ($maxTextLength !== null && $length > $maxTextLength) { $errors[] = __('"%1" length must be equal or less than %2 characters.', $label, $maxTextLength); } $result = $this->_validateInputRule($value); if ($result !== true) { $errors = array_merge($errors, $result); } if (count($errors) == 0) { return true; } return $errors; }
/** * Validate data * Return true or array of errors * * @param array|string $value * @return bool|array * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function validateValue($value) { $errors = []; $attribute = $this->getAttribute(); $label = __($attribute->getStoreLabel()); if ($value === false) { // try to load original value and validate it $value = $this->getEntity()->getDataUsingMethod($attribute->getAttributeCode()); } if ($attribute->getIsRequired() && empty($value) && $value !== '0') { $errors[] = __('"%1" is a required value.', $label); } if (!$errors && !$attribute->getIsRequired() && empty($value)) { return true; } // validate length $length = $this->_string->strlen(trim($value)); $validateRules = $attribute->getValidateRules(); if (!empty($validateRules['min_text_length']) && $length < $validateRules['min_text_length']) { $v = $validateRules['min_text_length']; $errors[] = __('"%1" length must be equal or greater than %2 characters.', $label, $v); } if (!empty($validateRules['max_text_length']) && $length > $validateRules['max_text_length']) { $v = $validateRules['max_text_length']; $errors[] = __('"%1" length must be equal or less than %2 characters.', $label, $v); } $result = $this->_validateInputRule($value); if ($result !== true) { $errors = array_merge($errors, $result); } if (count($errors) == 0) { return true; } return $errors; }
/** * Draw item line * * @return void */ public function draw() { $item = $this->getItem(); $pdf = $this->getPdf(); $page = $this->getPage(); $lines = []; // draw Product name $lines[0] = [['text' => $this->string->split($item->getName(), 60, true, true), 'feed' => 100]]; // draw QTY $lines[0][] = ['text' => $item->getQty() * 1, 'feed' => 35]; // draw SKU $lines[0][] = ['text' => $this->string->split($this->getSku($item), 25), 'feed' => 565, 'align' => 'right']; // Custom options $options = $this->getItemOptions(); if ($options) { foreach ($options as $option) { // draw options label $lines[][] = ['text' => $this->string->split($this->filterManager->stripTags($option['label']), 70, true, true), 'font' => 'italic', 'feed' => 110]; // draw options value if ($option['value']) { $printValue = isset($option['print_value']) ? $option['print_value'] : $this->filterManager->stripTags($option['value']); $values = explode(', ', $printValue); foreach ($values as $value) { $lines[][] = ['text' => $this->string->split($value, 50, true, true), 'feed' => 115]; } } } } $lineBlock = ['lines' => $lines, 'height' => 20]; $page = $pdf->drawLineBlocks($page, [$lineBlock], ['table_header' => true]); $this->setPage($page); }
/** * Draw item line * * @return void */ public function draw() { $order = $this->getOrder(); $item = $this->getItem(); $pdf = $this->getPdf(); $page = $this->getPage(); $lines = []; // draw Product name $lines[0] = [['text' => $this->string->split($item->getName(), 35, true, true), 'feed' => 35]]; // draw SKU $lines[0][] = ['text' => $this->string->split($this->getSku($item), 17), 'feed' => 290, 'align' => 'right']; // draw QTY $lines[0][] = ['text' => $item->getQty() * 1, 'feed' => 435, 'align' => 'right']; // draw item Prices $i = 0; $prices = $this->getItemPricesForDisplay(); $feedPrice = 395; $feedSubtotal = $feedPrice + 170; foreach ($prices as $priceData) { if (isset($priceData['label'])) { // draw Price label $lines[$i][] = ['text' => $priceData['label'], 'feed' => $feedPrice, 'align' => 'right']; // draw Subtotal label $lines[$i][] = ['text' => $priceData['label'], 'feed' => $feedSubtotal, 'align' => 'right']; $i++; } // draw Price $lines[$i][] = ['text' => $priceData['price'], 'feed' => $feedPrice, 'font' => 'bold', 'align' => 'right']; // draw Subtotal $lines[$i][] = ['text' => $priceData['subtotal'], 'feed' => $feedSubtotal, 'font' => 'bold', 'align' => 'right']; $i++; } // draw Tax $lines[0][] = ['text' => $order->formatPriceTxt($item->getTaxAmount()), 'feed' => 495, 'font' => 'bold', 'align' => 'right']; // custom options $options = $this->getItemOptions(); if ($options) { foreach ($options as $option) { // draw options label $lines[][] = ['text' => $this->string->split($this->filterManager->stripTags($option['label']), 40, true, true), 'font' => 'italic', 'feed' => 35]; if ($option['value']) { if (isset($option['print_value'])) { $printValue = $option['print_value']; } else { $printValue = $this->filterManager->stripTags($option['value']); } $values = explode(', ', $printValue); foreach ($values as $value) { $lines[][] = ['text' => $this->string->split($value, 30, true, true), 'feed' => 40]; } } } } $lineBlock = ['lines' => $lines, 'height' => 20]; $page = $pdf->drawLineBlocks($page, [$lineBlock], ['table_header' => true]); $this->setPage($page); }
/** * Renders grid column * * @param \Magento\Framework\DataObject $row * @return string */ public function render(\Magento\Framework\DataObject $row) { $line = parent::_getValue($row); $wrappedLine = ''; $lineLength = $this->getColumn()->getData('lineLength') ? $this->getColumn()->getData('lineLength') : $this->_defaultMaxLineLength; for ($i = 0, $n = floor($this->string->strlen($line) / $lineLength); $i <= $n; $i++) { $wrappedLine .= $this->string->substr($line, $lineLength * $i, $lineLength) . "<br />"; } return $wrappedLine; }
/** * Renders a column * * @param \Magento\Framework\DataObject $row * @return string */ public function render(\Magento\Framework\DataObject $row) { $value = $row->getData($this->getColumn()->getIndex()); if ($this->stringHelper->strlen($value) > 30) { $value = '<span title="' . $this->escapeHtml($value) . '">' . $this->escapeHtml($this->filterManager->truncate($value, ['length' => 30])) . '</span>'; } else { $value = $this->escapeHtml($value); } return $value; }
/** * Get attribute type based on its backend model. * * @param \Magento\Eav\Api\Data\AttributeInterface $attribute * @param string $serviceClass * @param $serviceBackendModelDataInterfaceMap array * @return string|null */ public function getType($attribute, $serviceClass, $serviceBackendModelDataInterfaceMap) { $backendModel = $attribute->getBackendModel(); //If empty backend model, check if it can be derived if (empty($backendModel)) { $backendModelClass = sprintf('Magento\\Eav\\Model\\Attribute\\Data\\%s', $this->stringUtility->upperCaseWords($attribute->getFrontendInput())); $backendModel = class_exists($backendModelClass) ? $backendModelClass : null; } $dataInterface = isset($serviceBackendModelDataInterfaceMap[$serviceClass][$backendModel]) ? $serviceBackendModelDataInterfaceMap[$serviceClass][$backendModel] : null; return $dataInterface; }
/** * Validate SKU * * @param Product $object * @return bool * @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Exception\LocalizedException */ public function validate($object) { $attrCode = $this->getAttribute()->getAttributeCode(); $value = $object->getData($attrCode); if ($this->getAttribute()->getIsRequired() && strlen($value) === 0) { throw new \Magento\Framework\Exception\LocalizedException(__('The value of attribute "%1" must be set', $attrCode)); } if ($this->string->strlen($object->getSku()) > self::SKU_MAX_LENGTH) { throw new \Magento\Framework\Exception\LocalizedException(__('SKU length should be %1 characters maximum.', self::SKU_MAX_LENGTH)); } return true; }
/** * @dataProvider queryTextDataProvider */ public function testGetEscapedQueryText($queryText, $maxQueryLength, $expected) { $this->requestMock->expects($this->once())->method('getParam')->willReturn($queryText); $this->stringMock->expects($this->any())->method('cleanString')->willReturnArgument(0); $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturn($maxQueryLength); $this->stringMock->expects($this->any())->method('strlen')->will($this->returnCallback(function ($queryText) { return strlen($queryText); })); $this->stringMock->expects($this->any())->method('substr')->with($queryText, 0, $maxQueryLength)->willReturn($expected); $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnArgument(0); $this->assertEquals($expected, $this->model->getEscapedQueryText()); }
/** * @param mixed $attrCode * @param string $type * @return bool */ protected function textValidation($attrCode, $type) { $val = $this->string->cleanString($this->_rowData[$attrCode]); if ($type == 'text') { $valid = $this->string->strlen($val) < Product::DB_MAX_TEXT_LENGTH; } else { $valid = $this->string->strlen($val) < Product::DB_MAX_VARCHAR_LENGTH; } if (!$valid) { $this->_addMessages([RowValidatorInterface::ERROR_EXCEEDED_MAX_LENGTH]); } return $valid; }
/** * Special processing before attribute save: * a) check some rules for password * b) transform temporary attribute 'password' into real attribute 'password_hash' * * @param \Magento\Framework\DataObject $object * @return void * @throws \Magento\Framework\Exception\LocalizedException */ public function beforeSave($object) { $password = $object->getPassword(); $length = $this->string->strlen($password); if ($length > 0) { if ($length < self::MIN_PASSWORD_LENGTH) { throw new LocalizedException(__('Please enter a password with at least %1 characters.', self::MIN_PASSWORD_LENGTH)); } if (trim($password) != $password) { throw new LocalizedException(__('The password can not begin or end with a space.')); } $object->setPasswordHash($object->hashPassword($password)); } }
/** * Load search results * * @return $this */ public function load() { $result = []; if (!$this->hasStart() || !$this->hasLimit() || !$this->hasQuery()) { $this->setResults($result); return $this; } $collection = $this->queryFactory->get()->getSearchCollection()->addAttributeToSelect('name')->addAttributeToSelect('description')->addBackendSearchFilter($this->getQuery())->setCurPage($this->getStart())->setPageSize($this->getLimit())->load(); foreach ($collection as $product) { $description = strip_tags($product->getDescription()); $result[] = ['id' => 'product/1/' . $product->getId(), 'type' => __('Product'), 'name' => $product->getName(), 'description' => $this->string->substr($description, 0, 30), 'url' => $this->_adminhtmlData->getUrl('catalog/product/edit', ['id' => $product->getId()])]; } $this->setResults($result); return $this; }
public function testGetTooLongQuery() { $queryId = 123; $this->mapScopeConfig([self::XML_PATH_MAX_QUERY_LENGTH => 12]); $rawQueryText = 'This is very long search query text'; $preparedQueryText = 'This is very'; $this->stringMock->expects($this->once())->method('substr')->with($this->equalTo($rawQueryText))->will($this->returnValue($preparedQueryText)); $this->requestMock->expects($this->once())->method('getParam')->with($this->equalTo(self::QUERY_VAR_NAME))->will($this->returnValue($rawQueryText)); $this->objectManagerMock->expects($this->once())->method('create')->with($this->equalTo('Magento\\Search\\Model\\Query'))->will($this->returnValue($this->queryMock)); $this->queryMock->expects($this->once())->method('loadByQuery')->with($this->equalTo($preparedQueryText))->will($this->returnSelf()); $this->queryMock->expects($this->once())->method('getId')->will($this->returnValue($queryId)); $this->queryMock->expects($this->once())->method('setIsQueryTextExceeded')->with($this->equalTo(true))->will($this->returnSelf()); $query = $this->queryFactory->get(); $this->assertSame($this->queryMock, $query); }
/** * Create Form Element * * @param \Magento\Customer\Api\Data\AttributeMetadataInterface $attribute * @param string|int|bool $value * @param string $entityTypeCode * @param bool $isAjax * @return \Magento\Customer\Model\Metadata\Form\AbstractData */ public function create(\Magento\Customer\Api\Data\AttributeMetadataInterface $attribute, $value, $entityTypeCode, $isAjax = false) { $dataModelClass = $attribute->getDataModel(); $params = ['entityTypeCode' => $entityTypeCode, 'value' => is_null($value) ? false : $value, 'isAjax' => $isAjax, 'attribute' => $attribute]; /** TODO fix when Validation is implemented MAGETWO-17341 */ if ($dataModelClass == 'Magento\\Customer\\Model\\Attribute\\Data\\Postcode') { $dataModelClass = 'Magento\\Customer\\Model\\Metadata\\Form\\Postcode'; } if (!empty($dataModelClass)) { $dataModel = $this->_objectManager->create($dataModelClass, $params); } else { $dataModelClass = sprintf('Magento\\Customer\\Model\\Metadata\\Form\\%s', $this->_string->upperCaseWords($attribute->getFrontendInput())); $dataModel = $this->_objectManager->create($dataModelClass, $params); } return $dataModel; }
/** * Save rule labels for different store views * * @param int $ruleId * @param array $labels * @throws \Exception * @return $this */ public function saveStoreLabels($ruleId, $labels) { $deleteByStoreIds = []; $table = $this->getTable('salesrule_label'); $connection = $this->getConnection(); $data = []; foreach ($labels as $storeId => $label) { if ($this->string->strlen($label)) { $data[] = ['rule_id' => $ruleId, 'store_id' => $storeId, 'label' => $label]; } else { $deleteByStoreIds[] = $storeId; } } $connection->beginTransaction(); try { if (!empty($data)) { $connection->insertOnDuplicate($table, $data, ['label']); } if (!empty($deleteByStoreIds)) { $connection->delete($table, ['rule_id=?' => $ruleId, 'store_id IN (?)' => $deleteByStoreIds]); } } catch (\Exception $e) { $connection->rollback(); throw $e; } $connection->commit(); return $this; }
/** * Return variable value for var construction * * @param string $value raw parameters * @param string $default default value * @return string * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function getVariable($value, $default = '{no_value_defined}') { \Magento\Framework\Profiler::start('email_template_processing_variables'); $tokenizer = new Template\Tokenizer\Variable(); $tokenizer->setString($value); $stackVars = $tokenizer->tokenize(); $result = $default; $last = 0; for ($i = 0; $i < count($stackVars); $i++) { if ($i == 0 && isset($this->templateVars[$stackVars[$i]['name']])) { // Getting of template value $stackVars[$i]['variable'] =& $this->templateVars[$stackVars[$i]['name']]; } elseif (isset($stackVars[$i - 1]['variable']) && $stackVars[$i - 1]['variable'] instanceof \Magento\Framework\DataObject) { // If object calling methods or getting properties if ($stackVars[$i]['type'] == 'property') { $caller = 'get' . $this->string->upperCaseWords($stackVars[$i]['name'], '_', ''); $stackVars[$i]['variable'] = method_exists($stackVars[$i - 1]['variable'], $caller) ? $stackVars[$i - 1]['variable']->{$caller}() : $stackVars[$i - 1]['variable']->getData($stackVars[$i]['name']); } elseif ($stackVars[$i]['type'] == 'method') { // Calling of object method if (method_exists($stackVars[$i - 1]['variable'], $stackVars[$i]['name']) || substr($stackVars[$i]['name'], 0, 3) == 'get') { $stackVars[$i]['args'] = $this->getStackArgs($stackVars[$i]['args']); $stackVars[$i]['variable'] = call_user_func_array([$stackVars[$i - 1]['variable'], $stackVars[$i]['name']], $stackVars[$i]['args']); } } $last = $i; } } if (isset($stackVars[$last]['variable'])) { // If value for construction exists set it $result = $stackVars[$last]['variable']; } \Magento\Framework\Profiler::stop('email_template_processing_variables'); return $result; }
/** * Custom save logic for section * * @return void */ protected function _saveSection() { $method = '_save' . $this->string->upperCaseWords($this->getRequest()->getParam('section'), '_', ''); if (method_exists($this, $method)) { $this->{$method}(); } }
/** * Return formatted option value ready to edit, ready to parse * * @param string $optionValue Prepared for cart option value * @return string */ public function getEditableOptionValue($optionValue) { $option = $this->getOption(); $result = ''; if (!$this->_isSingleSelection()) { foreach (explode(',', $optionValue) as $_value) { $_result = $option->getValueById($_value); if ($_result) { $result .= $_result->getTitle() . ', '; } else { if ($this->getListener()) { $this->getListener()->setHasError(true)->setMessage($this->_getWrongConfigurationMessage()); $result = ''; break; } } } $result = $this->string->substr($result, 0, -2); } elseif ($this->_isSingleSelection()) { $_result = $option->getValueById($optionValue); if ($_result) { $result = $_result->getTitle(); } else { if ($this->getListener()) { $this->getListener()->setHasError(true)->setMessage($this->_getWrongConfigurationMessage()); } $result = ''; } } else { $result = $optionValue; } return $result; }
/** * Add meta information from product to head block * * @return \Magento\Catalog\Block\Product\View */ protected function _prepareLayout() { $this->getLayout()->createBlock('Magento\\Catalog\\Block\\Breadcrumbs'); $product = $this->getProduct(); if (!$product) { return parent::_prepareLayout(); } $title = $product->getMetaTitle(); if ($title) { $this->pageConfig->getTitle()->set($title); } $keyword = $product->getMetaKeyword(); $currentCategory = $this->_coreRegistry->registry('current_category'); if ($keyword) { $this->pageConfig->setKeywords($keyword); } elseif ($currentCategory) { $this->pageConfig->setKeywords($product->getName()); } $description = $product->getMetaDescription(); if ($description) { $this->pageConfig->setDescription($description); } else { $this->pageConfig->setDescription($this->string->substr($product->getDescription(), 0, 255)); } if ($this->_productHelper->canUseCanonicalTag()) { $this->pageConfig->addRemotePageAsset($product->getUrlModel()->getUrl($product, ['_ignore_category' => true]), 'canonical', ['attributes' => ['rel' => 'canonical']]); } $pageMainTitle = $this->getLayout()->getBlock('page.main.title'); if ($pageMainTitle) { $pageMainTitle->setPageTitle($product->getName()); } return parent::_prepareLayout(); }
/** * Group model factory * * @param string $type Option type * @return \Magento\Catalog\Model\Product\Option\Type\DefaultType * @throws LocalizedException */ public function groupFactory($type) { $group = $this->getGroupByType($type); if (!empty($group)) { return $this->_optionFactory->create('Magento\\Catalog\\Model\\Product\\Option\\Type\\' . $this->string->upperCaseWords($group)); } throw new LocalizedException(__('The option type to get group instance is incorrect.')); }
/** * @param string $name * @param string $content * @return mixed */ protected function processMetadataContent($name, $content) { $method = 'get' . $this->string->upperCaseWords($name, '_', ''); if (method_exists($this->pageConfig, $method)) { $content = $this->pageConfig->{$method}(); } return $content; }
/** * Retrieve HTTP "clean" value * * @param string $var * @param boolean $clean clean non UTF-8 characters * @return string */ protected function _getHttpCleanValue($var, $clean = true) { $value = $this->_request->getServer($var, ''); if ($clean) { $value = $this->_converter->cleanString($value); } return $value; }
/** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function testCreateAccountWithPassword() { $websiteId = 1; $storeId = null; $defaultStoreId = 1; $customerId = 1; $customerEmail = '*****@*****.**'; $password = '******'; $hash = '4nj54lkj5jfi03j49f8bgujfgsd'; $newLinkToken = '2jh43j5h2345jh23lh452h345hfuzasd96ofu'; $templateIdentifier = 'Template Identifier'; $sender = 'Sender'; $this->string->expects($this->any())->method('strlen')->willReturnCallback(function ($string) { return strlen($string); }); $this->encryptor->expects($this->once())->method('getHash')->with($password, true)->willReturn($hash); $address = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AddressInterface')->disableOriginalConstructor()->getMock(); $address->expects($this->once())->method('setCustomerId')->with($customerId); $store = $this->getMockBuilder('Magento\\Store\\Model\\Store')->disableOriginalConstructor()->getMock(); $store->expects($this->once())->method('getId')->willReturn($defaultStoreId); $website = $this->getMockBuilder('Magento\\Store\\Model\\Website')->disableOriginalConstructor()->getMock(); $website->expects($this->atLeastOnce())->method('getStoreIds')->willReturn([1, 2, 3]); $website->expects($this->once())->method('getDefaultStore')->willReturn($store); $customer = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMock(); $customer->expects($this->atLeastOnce())->method('getId')->willReturn($customerId); $customer->expects($this->atLeastOnce())->method('getEmail')->willReturn($customerEmail); $customer->expects($this->atLeastOnce())->method('getWebsiteId')->willReturn($websiteId); $customer->expects($this->atLeastOnce())->method('getStoreId')->willReturn($storeId); $customer->expects($this->once())->method('setStoreId')->with($defaultStoreId); $customer->expects($this->once())->method('getAddresses')->willReturn([$address]); $customer->expects($this->once())->method('setAddresses')->with(null); $this->customerRepository->expects($this->once())->method('get')->with($customerEmail)->willReturn($customer); $this->share->expects($this->once())->method('isWebsiteScope')->willReturn(true); $this->storeManager->expects($this->atLeastOnce())->method('getWebsite')->with($websiteId)->willReturn($website); $this->customerRepository->expects($this->atLeastOnce())->method('save')->willReturn($customer); $this->addressRepository->expects($this->atLeastOnce())->method('save')->with($address); $this->customerRepository->expects($this->once())->method('getById')->with($customerId)->willReturn($customer); $this->random->expects($this->once())->method('getUniqueHash')->willReturn($newLinkToken); $customerSecure = $this->getMockBuilder('Magento\\Customer\\Model\\Data\\CustomerSecure')->setMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash'])->disableOriginalConstructor()->getMock(); $customerSecure->expects($this->any())->method('setRpToken')->with($newLinkToken); $customerSecure->expects($this->any())->method('setRpTokenCreatedAt'); $customerSecure->expects($this->any())->method('getPasswordHash')->willReturn($hash); $this->customerRegistry->expects($this->atLeastOnce())->method('retrieveSecureData')->willReturn($customerSecure); $this->dataObjectProcessor->expects($this->once())->method('buildOutputDataArray')->willReturn([]); $this->scopeConfig->expects($this->at(1))->method('getValue')->with(AccountManagement::XML_PATH_REGISTER_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $defaultStoreId)->willReturn($templateIdentifier); $this->scopeConfig->expects($this->at(2))->method('getValue')->willReturn($sender); $transport = $this->getMockBuilder('Magento\\Framework\\Mail\\TransportInterface')->getMock(); $this->transportBuilder->expects($this->once())->method('setTemplateIdentifier')->with($templateIdentifier)->willReturnSelf(); $this->transportBuilder->expects($this->once())->method('setTemplateOptions')->willReturnSelf(); $this->transportBuilder->expects($this->once())->method('setTemplateVars')->willReturnSelf(); $this->transportBuilder->expects($this->once())->method('setFrom')->with($sender)->willReturnSelf(); $this->transportBuilder->expects($this->once())->method('addTo')->willReturnSelf(); $this->transportBuilder->expects($this->once())->method('getTransport')->willReturn($transport); $transport->expects($this->once())->method('sendMessage'); $this->accountManagement->createAccount($customer, $password); }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.NPathComplexity) */ public function getType($attributeCode, $serviceClass) { if (!$serviceClass || !$attributeCode || !isset($this->serviceEntityTypeMap[$serviceClass]) || !isset($this->serviceBackendModelDataInterfaceMap[$serviceClass])) { return null; } try { $attribute = $this->attributeRepository->get($this->serviceEntityTypeMap[$serviceClass], $attributeCode); $backendModel = $attribute->getBackendModel(); } catch (NoSuchEntityException $e) { return null; } //If empty backend model, check if it can be derived if (empty($backendModel)) { $backendModelClass = sprintf('Magento\\Eav\\Model\\Attribute\\Data\\%s', $this->stringUtility->upperCaseWords($attribute->getFrontendInput())); $backendModel = class_exists($backendModelClass) ? $backendModelClass : null; } $dataInterface = isset($this->serviceBackendModelDataInterfaceMap[$serviceClass][$backendModel]) ? $this->serviceBackendModelDataInterfaceMap[$serviceClass][$backendModel] : null; return $dataInterface; }
public function testRenderMetadata() { $metadata = ['charset' => 'charsetValue', 'metadataName' => 'metadataValue', 'content_type' => 'content_type_value', 'x_ua_compatible' => 'x_ua_compatible_value', 'media_type' => 'media_type_value']; $metadataValueCharset = 'newCharsetValue'; $expected = '<meta charset="newCharsetValue"/>' . "\n" . '<meta name="metadataName" content="metadataValue"/>' . "\n" . '<meta http-equiv="Content-Type" content="content_type_value"/>' . "\n" . '<meta http-equiv="X-UA-Compatible" content="x_ua_compatible_value"/>' . "\n"; $this->stringMock->expects($this->at(0))->method('upperCaseWords')->with('charset', '_', '')->willReturn('Charset'); $this->pageConfigMock->expects($this->once())->method('getCharset')->willReturn($metadataValueCharset); $this->pageConfigMock->expects($this->once())->method('getMetadata')->will($this->returnValue($metadata)); $this->assertEquals($expected, $this->renderer->renderMetadata()); }
/** * Validate user input for option * * @param array $values All product option values, i.e. array (option_id => mixed, option_id => mixed...) * @return $this * @throws \Magento\Framework\Exception\LocalizedException */ public function validateUserValue($values) { parent::validateUserValue($values); $option = $this->getOption(); $value = trim($this->getUserValue()); // Check requires option to have some value if (strlen($value) == 0 && $option->getIsRequire() && !$this->getSkipCheckRequiredOption()) { $this->setIsValid(false); throw new LocalizedException(__('Please specify product\'s required option(s).')); } // Check maximal length limit $maxCharacters = $option->getMaxCharacters(); if ($maxCharacters > 0 && $this->string->strlen($value) > $maxCharacters) { $this->setIsValid(false); throw new LocalizedException(__('The text is too long.')); } $this->setUserValue($value); return $this; }
/** * Accept option value and return its formatted view * * @param string|array $optionValue * Method works well with these $optionValue format: * 1. String * 2. Indexed array e.g. array(val1, val2, ...) * 3. Associative array, containing additional option info, including option value, e.g. * array * ( * [label] => ..., * [value] => ..., * [print_value] => ..., * [option_id] => ..., * [option_type] => ..., * [custom_view] =>..., * ) * @param array $params * All keys are options. Following supported: * - 'maxLength': truncate option value if needed, default: do not truncate * - 'cutReplacer': replacer for cut off value part when option value exceeds maxLength * * @return array * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function getFormattedOptionValue($optionValue, $params = null) { // Init params if (!$params) { $params = []; } $maxLength = isset($params['max_length']) ? $params['max_length'] : null; $cutReplacer = isset($params['cut_replacer']) ? $params['cut_replacer'] : '...'; // Proceed with option $optionInfo = []; // Define input data format if (is_array($optionValue)) { if (isset($optionValue['option_id'])) { $optionInfo = $optionValue; if (isset($optionInfo['value'])) { $optionValue = $optionInfo['value']; } } elseif (isset($optionValue['value'])) { $optionValue = $optionValue['value']; } } // Render customized option view if (isset($optionInfo['custom_view']) && $optionInfo['custom_view']) { $_default = ['value' => $optionValue]; if (isset($optionInfo['option_type'])) { try { $group = $this->_productOptionFactory->create()->groupFactory($optionInfo['option_type']); return ['value' => $group->getCustomizedView($optionInfo)]; } catch (\Exception $e) { return $_default; } } return $_default; } // Truncate standard view if (is_array($optionValue)) { $truncatedValue = implode("\n", $optionValue); $truncatedValue = nl2br($truncatedValue); return ['value' => $truncatedValue]; } else { if ($maxLength) { $truncatedValue = $this->filter->truncate($optionValue, ['length' => $maxLength, 'etc' => '']); } else { $truncatedValue = $optionValue; } $truncatedValue = nl2br($truncatedValue); } $result = ['value' => $truncatedValue]; if ($maxLength && $this->string->strlen($optionValue) > $maxLength) { $result['value'] = $result['value'] . $cutReplacer; $optionValue = nl2br($optionValue); $result['full_view'] = $optionValue; } return $result; }
/** * Retrieve HTTP HOST * * @param bool $trimPort * @return string * * @todo getHttpHost should return only string (currently method return boolean value too) */ public function getHttpHost($trimPort = true) { $httpHost = $this->getServer('HTTP_HOST'); $httpHost = $this->converter->cleanString($httpHost); if (empty($httpHost)) { return false; } if ($trimPort) { $host = explode(':', $httpHost); return $host[0]; } return $httpHost; }
/** * Draw process * * @return void */ public function draw() { $order = $this->getOrder(); $item = $this->getItem(); $pdf = $this->getPdf(); $page = $this->getPage(); $lines = []; // draw Product name $lines[0] = [['text' => $this->string->split($item->getName(), 35, true, true), 'feed' => 35]]; // draw SKU $lines[0][] = ['text' => $this->string->split($this->getSku($item), 17), 'feed' => 255, 'align' => 'right']; // draw Total (ex) $lines[0][] = ['text' => $order->formatPriceTxt($item->getRowTotal()), 'feed' => 330, 'font' => 'bold', 'align' => 'right']; // draw Discount $lines[0][] = ['text' => $order->formatPriceTxt(-$item->getDiscountAmount()), 'feed' => 380, 'font' => 'bold', 'align' => 'right']; // draw QTY $lines[0][] = ['text' => $item->getQty() * 1, 'feed' => 445, 'font' => 'bold', 'align' => 'right']; // draw Tax $lines[0][] = ['text' => $order->formatPriceTxt($item->getTaxAmount()), 'feed' => 495, 'font' => 'bold', 'align' => 'right']; // draw Total (inc) $subtotal = $item->getRowTotal() + $item->getTaxAmount() + $item->getDiscountTaxCompensationAmount() - $item->getDiscountAmount(); $lines[0][] = ['text' => $order->formatPriceTxt($subtotal), 'feed' => 565, 'font' => 'bold', 'align' => 'right']; // draw options $options = $this->getItemOptions(); if ($options) { foreach ($options as $option) { // draw options label $lines[][] = ['text' => $this->string->split($this->filterManager->stripTags($option['label']), 40, true, true), 'font' => 'italic', 'feed' => 35]; // draw options value $printValue = isset($option['print_value']) ? $option['print_value'] : $this->filterManager->stripTags($option['value']); $lines[][] = ['text' => $this->string->split($printValue, 30, true, true), 'feed' => 40]; } } $lineBlock = ['lines' => $lines, 'height' => 20]; $page = $pdf->drawLineBlocks($page, [$lineBlock], ['table_header' => true]); $this->setPage($page); }
/** * Set many options at once * * @param array $options * @param array $default * @return $this */ public function setOptions($options, $default = []) { $options = !is_array($options) && !$options instanceof \Traversable ? $default : $options; if (is_array($options) || $options instanceof \Traversable) { foreach ($options as $option => $value) { $setter = 'set' . $this->_stringHelper->upperCaseWords($option, '_', ''); if (method_exists($this, $setter)) { $this->{$setter}($value); } else { $this->setOption($option, $value); } } } return $this; }