public function testFormatUrlKey() { $strIn = 'Some string'; $resultString = 'some'; $this->filter->expects($this->once())->method('translitUrl')->with($strIn)->will($this->returnValue($resultString)); $this->assertEquals($resultString, $this->model->formatUrlKey($strIn)); }
/** * {@inheritdoc} */ protected function _beforeSave(AbstractModel $tag) { /** @var \Mirasvit\Blog\Model\Tag $tag */ if (!$tag->getData('url_key')) { $tag->setData('url_key', $this->filter->translitUrl($tag->getName())); } return parent::_beforeSave($tag); }
/** * Format address in a specific way * * @param DataObject $storeInfo * @param string $type * @return string */ public function format(DataObject $storeInfo, $type = 'html') { $this->eventManager->dispatch('store_address_format', ['type' => $type, 'store_info' => $storeInfo]); $address = $this->filterManager->template("{{var name}}\n{{var street_line1}}\n{{depend street_line2}}{{var street_line2}}\n{{/depend}}" . "{{var city}}, {{var region}} {{var postcode}},\n{{var country}}", ['variables' => $storeInfo->getData()]); if ($type == 'html') { $address = nl2br($address); } return $address; }
/** * Method to run before save * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { // format height $height = $object->getContentHeight(); $height = $this->filterManager->stripTags($height); if (!$height) { $height = ''; } if ($height && preg_match('/[0-9]$/', $height)) { $height .= 'px'; } $object->setContentHeight($height); return parent::_beforeSave($object); }
/** * Retrieve processed template subject * * @param array $variables * @return string */ public function getProcessedTemplateSubject(array $variables) { if (!$this->_preprocessFlag) { $variables['this'] = $this; } return $this->_filterManager->template($this->getTemplateSubject(), ['variables' => $variables]); }
public function testExecute() { $firstElement = 'firstElement'; $symbolsDataArray = [$firstElement]; $redirectUrl = 'redirectUrl'; $this->requestMock->expects($this->once())->method('getParam')->with('custom_currency_symbol')->willReturn($symbolsDataArray); $this->helperMock->expects($this->once())->method('getUrl')->with('*'); $this->redirectMock->expects($this->once())->method('getRedirectUrl')->willReturn($redirectUrl); $this->currencySymbolMock->expects($this->once())->method('setCurrencySymbolsData')->with($symbolsDataArray); $this->responseMock->expects($this->once())->method('setRedirect'); $this->filterManagerMock->expects($this->once())->method('stripTags')->with($firstElement)->willReturn($firstElement); $this->objectManagerMock->expects($this->once())->method('create')->with('Magento\\CurrencySymbol\\Model\\System\\Currencysymbol')->willReturn($this->currencySymbolMock); $this->objectManagerMock->expects($this->once())->method('get')->with('Magento\\Framework\\Filter\\FilterManager')->willReturn($this->filterManagerMock); $this->messageManagerMock->expects($this->once())->method('addSuccess')->with(__('You applied the custom currency symbols.')); $this->action->execute(); }
/** * Process page data before saving * * @param \Magento\Framework\Model\AbstractModel $object * @return $this * @throws \Magento\Framework\Model\Exception */ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { /* * For two attributes which represent timestamp data in DB * we should make converting such as: * If they are empty we need to convert them into DB * type NULL so in DB they will be empty and not some default value */ foreach (array('custom_theme_from', 'custom_theme_to') as $field) { $value = !$object->getData($field) ? null : $object->getData($field); $object->setData($field, $this->dateTime->formatDate($value)); } if (!$object->getData('identifier')) { $object->setData('identifier', $this->filter->translitUrl($object->getData('title'))); } if (!$this->getIsUniquePageToStores($object)) { throw new \Magento\Framework\Model\Exception(__('A page URL key for specified store already exists.')); } if (!$this->isValidPageIdentifier($object)) { throw new \Magento\Framework\Model\Exception(__('The page URL key contains capital letters or disallowed symbols.')); } if ($this->isNumericPageIdentifier($object)) { throw new \Magento\Framework\Model\Exception(__('The page URL key cannot be made of only numbers.')); } // modify create / update dates if ($object->isObjectNew() && !$object->hasCreationTime()) { $object->setCreationTime($this->_date->gmtDate()); } $object->setUpdateTime($this->_date->gmtDate()); return parent::_beforeSave($object); }
/** * Auto generate slug if empty * * @param \Magento\Framework\Model\AbstractModel $object * * @return bool */ protected function isSlugEmpty(\Magento\Framework\Model\AbstractModel $object) { if (empty($object->getData('slug'))) { $slug = $this->filter->translitUrl($object->getData('title')); $object->setData('slug', $slug); } return true; }
/** * {@inheritdoc} */ public function normalize($string) { //@codingStandardsIgnoreStart $table = ['Š' => 'S', 'š' => 's', 'Đ' => 'Dj', 'đ' => 'dj', 'Ž' => 'Z', 'ž' => 'z', 'Č' => 'C', 'č' => 'c', 'Ć' => 'C', 'ć' => 'c', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'Ae', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'Oe', 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'ae', 'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y', 'Ŕ' => 'R', 'ŕ' => 'r', 'ü' => 'ue', '/' => '', '&' => '', '(' => '', ')' => '']; //@codingStandardsIgnoreStop $string = strtr($string, $table); $string = $this->filter->translitUrl($string); return $string; }
/** * 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 */ public function getFormattedOptionValue($optionValue, $params = null) { // Init params if (!$params) { $params = array(); } $maxLength = isset($params['max_length']) ? $params['max_length'] : null; $cutReplacer = isset($params['cut_replacer']) ? $params['cut_replacer'] : '...'; // Proceed with option $optionInfo = array(); // Define input data format if (is_array($optionValue)) { if (isset($optionValue['option_id'])) { $optionInfo = $optionValue; if (isset($optionInfo['value'])) { $optionValue = $optionInfo['value']; } } else { if (isset($optionValue['value'])) { $optionValue = $optionValue['value']; } } } // Render customized option view if (isset($optionInfo['custom_view']) && $optionInfo['custom_view']) { $_default = array('value' => $optionValue); if (isset($optionInfo['option_type'])) { try { $group = $this->_productOptionFactory->create()->groupFactory($optionInfo['option_type']); return array('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 array('value' => $truncatedValue); } else { if ($maxLength) { $truncatedValue = $this->filter->truncate($optionValue, array('length' => $maxLength, 'etc' => '')); } else { $truncatedValue = $optionValue; } $truncatedValue = nl2br($truncatedValue); } $result = array('value' => $truncatedValue); if ($maxLength && $this->string->strlen($optionValue) > $maxLength) { $result['value'] = $result['value'] . $cutReplacer; $optionValue = nl2br($optionValue); $result['full_view'] = $optionValue; } return $result; }
/** * Generate code from label * * @param string $label * @return string */ protected function generateCode($label) { $code = substr(preg_replace('/[^a-z_0-9]/', '_', $this->filterManager->translitUrl($label)), 0, 30); $validatorAttrCode = new \Zend_Validate_Regex(['pattern' => '/^[a-z][a-z_0-9]{0,29}[a-z0-9]$/']); if (!$validatorAttrCode->isValid($code)) { $code = 'attr_' . ($code ?: substr(md5(time()), 0, 8)); } return $code; }
public function testCall() { $value = 'testValue'; $this->initMocks(); $filterMock = $this->getMock('FactoryInterface', ['filter']); $filterMock->expects($this->atLeastOnce())->method('filter')->with($this->equalTo($value))->will($this->returnValue($value)); $this->configureFactoryMock($filterMock, 'alias', ['123']); $this->assertEquals($value, $this->_filterManager->alias($value, ['123'])); }
/** * {@inheritdoc} */ protected function _beforeSave(DataObject $post) { /** @var \Mirasvit\Blog\Model\Post $post */ if (!$post->hasData('type')) { $post->setData('type', \Mirasvit\Blog\Model\Post::TYPE_POST); } if (!$post->getData('url_key')) { $post->setData('url_key', $this->filter->translitUrl($post->getName())); } $this->saveImage($post); return parent::_beforeSave($post); }
/** * {@inheritdoc} */ protected function _beforeSave(DataObject $category) { /** @var \Mirasvit\Blog\Model\Category $category */ parent::_beforeSave($category); if (!$category->getChildrenCount()) { $category->setChildrenCount(0); } if (!$category->getData('url_key')) { $category->setData('url_key', $this->filter->translitUrl($category->getName())); } if ($category->isObjectNew()) { if (!$category->hasParentId()) { $category->setParentId(1); } /** @var \Mirasvit\Blog\Model\Category $parent */ $parent = ObjectManager::getInstance()->create('Mirasvit\\Blog\\Model\\Category')->load($category->getParentId()); $category->setPath($parent->getPath()); if ($category->getPosition() === null) { $category->setPosition($this->getMaxPosition($category->getPath()) + 1); } $path = explode('/', $category->getPath()); $level = count($path) - ($category->getId() ? 1 : 0); $toUpdateChild = array_diff($path, [$category->getId()]); if (!$category->hasPosition()) { $category->setPosition($this->getMaxPosition(implode('/', $toUpdateChild)) + 1); } if (!$category->hasLevel()) { $category->setLevel($level); } if (!$category->getId() && $category->getPath()) { $category->setPath($category->getPath() . '/'); } $this->getConnection()->update($this->getEntityTable(), ['children_count' => new \Zend_Db_Expr('children_count+1')], ['entity_id IN(?)' => $toUpdateChild]); } return $this; }
/** * Format option value process * * @param array|string $value * @return string */ protected function _formatOptionValue($value) { $order = $this->getOrder(); $resultValue = ''; if (is_array($value)) { if (isset($value['qty'])) { $resultValue .= $this->filterManager->sprintf($value['qty'], array('format' => '%d')) . ' x '; } $resultValue .= $value['title']; if (isset($value['price'])) { $resultValue .= " " . $order->formatPrice($value['price']); } return $resultValue; } else { return $value; } }
/** * Prepare results for query * * @param \Magento\CatalogSearch\Model\Fulltext $object * @param string $queryText * @param \Magento\CatalogSearch\Model\Query $query * @return $this */ public function prepareResult($object, $queryText, $query) { $adapter = $this->_getWriteAdapter(); if (!$query->getIsProcessed()) { $searchType = $object->getSearchType($query->getStoreId()); $bind = array(); $like = array(); $likeCond = ''; if ($searchType == \Magento\CatalogSearch\Model\Fulltext::SEARCH_TYPE_LIKE || $searchType == \Magento\CatalogSearch\Model\Fulltext::SEARCH_TYPE_COMBINE) { $words = $this->filter->splitWords($queryText, array('uniqueOnly' => true, 'wordsQty' => $query->getMaxQueryWords())); foreach ($words as $word) { $like[] = $this->_resourceHelper->getCILike('s.data_index', $word, array('position' => 'any')); } if ($like) { $likeCond = '(' . join(' OR ', $like) . ')'; } } $mainTableAlias = 's'; $fields = array('query_id' => new \Zend_Db_Expr($query->getId()), 'product_id'); $select = $adapter->select()->from(array($mainTableAlias => $this->getMainTable()), $fields)->joinInner(array('e' => $this->getTable('catalog_product_entity')), 'e.entity_id = s.product_id', array())->where($mainTableAlias . '.store_id = ?', (int) $query->getStoreId()); $where = ''; if ($searchType == \Magento\CatalogSearch\Model\Fulltext::SEARCH_TYPE_FULLTEXT || $searchType == \Magento\CatalogSearch\Model\Fulltext::SEARCH_TYPE_COMBINE) { $preparedTerms = $this->_resourceHelper->prepareTerms($queryText, $query->getMaxQueryWords()); $bind[':query'] = implode(' ', $preparedTerms[0]); $where = $this->_resourceHelper->chooseFulltext($this->getMainTable(), $mainTableAlias, $select); } if ($likeCond != '' && $searchType == \Magento\CatalogSearch\Model\Fulltext::SEARCH_TYPE_COMBINE) { $where .= ($where ? ' OR ' : '') . $likeCond; } elseif ($likeCond != '' && $searchType == \Magento\CatalogSearch\Model\Fulltext::SEARCH_TYPE_LIKE) { $select->columns(array('relevance' => new \Zend_Db_Expr(0))); $where = $likeCond; } if ($where != '') { $select->where($where); } $sql = $adapter->insertFromSelect($select, $this->getTable('catalogsearch_result'), array(), \Magento\Framework\DB\Adapter\AdapterInterface::INSERT_ON_DUPLICATE); $adapter->query($sql, $bind); $query->setIsProcessed(1); } return $this; }
/** * Generate CMS page url key based on url_key entered by merchant or page title * * @param \Magento\Cms\Model\Page $cmsPage * @return string */ public function generateUrlKey($cmsPage) { $urlKey = $cmsPage->getIdentifier(); return $this->filterManager->translitUrl($urlKey === '' || $urlKey === null ? $cmsPage->getTitle() : $urlKey); }
/** * Check query of a warnings * * @param mixed $store * @return $this */ public function checkNotes($store = null) { if ($this->_isMaxLength) { $this->addNoteMessage(__('Your search query can\'t be longer than %1, so we had to shorten your query.', $this->getMaxQueryLength())); } $searchType = $this->_scopeConfig->getValue(Fulltext::XML_PATH_CATALOG_SEARCH_TYPE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); if ($searchType == Fulltext::SEARCH_TYPE_COMBINE || $searchType == Fulltext::SEARCH_TYPE_LIKE) { $wordsFull = $this->filter->splitWords($this->getQueryText(), array('uniqueOnly' => true)); $wordsLike = $this->filter->splitWords($this->getQueryText(), array('uniqueOnly' => true, 'wordsQty' => $this->getMaxQueryWords())); if (count($wordsFull) > count($wordsLike)) { $wordsCut = array_map(array($this->_escaper, 'escapeHtml'), array_diff($wordsFull, $wordsLike)); $this->addNoteMessage(__('Sorry, but the maximum word count is %1. We left out this part of your search: %2.', $this->getMaxQueryWords(), join(' ', $wordsCut))); } } return $this; }
/** * Get contents of the included template for template directive * * @param string $configPath * @param array $variables * @return string */ public function getTemplateContent($configPath, array $variables) { $template = $this->getTemplateInstance(); // Ensure child templates have the same area/store context as parent $template->setDesignConfig($this->getDesignConfig()->toArray())->loadByConfigPath($configPath, $variables)->setTemplateType($this->getType())->setIsChildTemplate(true); // automatically strip tags if in a plain-text parent if ($this->isPlain()) { $templateText = $this->filterManager->stripTags($template->getTemplateText()); $template->setTemplateText(trim($templateText)); } $processedTemplate = $template->getProcessedTemplate($variables); if ($this->isPlain()) { $processedTemplate = trim($processedTemplate); } return $processedTemplate; }
/** * @return \Magento\Backend\Model\View\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function execute() { $data = $this->getRequest()->getPostValue(); $resultRedirect = $this->resultRedirectFactory->create(); if ($data) { $setId = $this->getRequest()->getParam('set'); $attributeSet = null; if (!empty($data['new_attribute_set_name'])) { $name = $this->filterManager->stripTags($data['new_attribute_set_name']); $name = trim($name); try { /** @var $attributeSet \Magento\Eav\Model\Entity\Attribute\Set */ $attributeSet = $this->buildFactory->create()->setEntityTypeId($this->_entityTypeId)->setSkeletonId($setId)->setName($name)->getAttributeSet(); } catch (AlreadyExistsException $alreadyExists) { $this->messageManager->addError(__('An attribute set named \'%1\' already exists.', $name)); $this->messageManager->setAttributeData($data); return $resultRedirect->setPath('catalog/*/edit', ['_current' => true]); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('Something went wrong while saving the attribute.')); } } $redirectBack = $this->getRequest()->getParam('back', false); /* @var $model \Magento\Catalog\Model\ResourceModel\Eav\Attribute */ $model = $this->attributeFactory->create(); $attributeId = $this->getRequest()->getParam('attribute_id'); $attributeCode = $this->getRequest()->getParam('attribute_code'); $frontendLabel = $this->getRequest()->getParam('frontend_label'); $attributeCode = $attributeCode ?: $this->generateCode($frontendLabel[0]); if (strlen($this->getRequest()->getParam('attribute_code')) > 0) { $validatorAttrCode = new \Zend_Validate_Regex(['pattern' => '/^[a-z][a-z_0-9]{0,30}$/']); if (!$validatorAttrCode->isValid($attributeCode)) { $this->messageManager->addError(__('Attribute code "%1" is invalid. Please use only letters (a-z), ' . 'numbers (0-9) or underscore(_) in this field, first character should be a letter.', $attributeCode)); return $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $attributeId, '_current' => true]); } } $data['attribute_code'] = $attributeCode; //validate frontend_input if (isset($data['frontend_input'])) { /** @var $inputType \Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\Validator */ $inputType = $this->validatorFactory->create(); if (!$inputType->isValid($data['frontend_input'])) { foreach ($inputType->getMessages() as $message) { $this->messageManager->addError($message); } return $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $attributeId, '_current' => true]); } } if ($attributeId) { $model->load($attributeId); if (!$model->getId()) { $this->messageManager->addError(__('This attribute no longer exists.')); return $resultRedirect->setPath('catalog/*/'); } // entity type check if ($model->getEntityTypeId() != $this->_entityTypeId) { $this->messageManager->addError(__('We can\'t update the attribute.')); $this->_session->setAttributeData($data); return $resultRedirect->setPath('catalog/*/'); } $data['attribute_code'] = $model->getAttributeCode(); $data['is_user_defined'] = $model->getIsUserDefined(); $data['frontend_input'] = $model->getFrontendInput(); } else { /** * @todo add to helper and specify all relations for properties */ $data['source_model'] = $this->productHelper->getAttributeSourceModelByInputType($data['frontend_input']); $data['backend_model'] = $this->productHelper->getAttributeBackendModelByInputType($data['frontend_input']); } $data += ['is_filterable' => 0, 'is_filterable_in_search' => 0, 'apply_to' => []]; if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) { $data['backend_type'] = $model->getBackendTypeByInput($data['frontend_input']); } $defaultValueField = $model->getDefaultValueByInput($data['frontend_input']); if ($defaultValueField) { $data['default_value'] = $this->getRequest()->getParam($defaultValueField); } if (!$model->getIsUserDefined() && $model->getId()) { // Unset attribute field for system attributes unset($data['apply_to']); } $model->addData($data); if (!$attributeId) { $model->setEntityTypeId($this->_entityTypeId); $model->setIsUserDefined(1); } $groupCode = $this->getRequest()->getParam('group'); if ($setId && $groupCode) { // For creating product attribute on product page we need specify attribute set and group $attributeSetId = $attributeSet ? $attributeSet->getId() : $setId; $groupCollection = $attributeSet ? $attributeSet->getGroups() : $this->groupCollectionFactory->create()->setAttributeSetFilter($attributeSetId)->load(); foreach ($groupCollection as $group) { if ($group->getAttributeGroupCode() == $groupCode) { $attributeGroupId = $group->getAttributeGroupId(); break; } } $model->setAttributeSetId($attributeSetId); $model->setAttributeGroupId($attributeGroupId); } try { $model->save(); $this->messageManager->addSuccess(__('You saved the product attribute.')); $this->_attributeLabelCache->clean(); $this->_session->setAttributeData(false); if ($this->getRequest()->getParam('popup')) { $requestParams = ['attributeId' => $this->getRequest()->getParam('product'), 'attribute' => $model->getId(), '_current' => true, 'product_tab' => $this->getRequest()->getParam('product_tab')]; if (!is_null($attributeSet)) { $requestParams['new_attribute_set_id'] = $attributeSet->getId(); } $resultRedirect->setPath('catalog/product/addAttribute', $requestParams); } elseif ($redirectBack) { $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $model->getId(), '_current' => true]); } else { $resultRedirect->setPath('catalog/*/'); } return $resultRedirect; } catch (\Exception $e) { $this->messageManager->addError($e->getMessage()); $this->_session->setAttributeData($data); return $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $attributeId, '_current' => true]); } } return $resultRedirect->setPath('catalog/*/'); }
/** * Wrapper for standard strip_tags() function with extra functionality for html entities * * @param string $data * @param string|null $allowableTags * @param bool $allowHtmlEntities * @return string */ public function stripTags($data, $allowableTags = null, $allowHtmlEntities = false) { return $this->filterManager->stripTags($data, ['allowableTags' => $allowableTags, 'escape' => $allowHtmlEntities]); }
/** * Format URL key from name or defined key * * @param string $str * @return string */ public function formatUrlKey($str) { return $this->filter->translitUrl($str); }
/** * Return short detail info in HTML * * @param string $origDetail Full detail info * @return string */ public function getDetailHtml($origDetail) { return nl2br($this->filter->truncate($this->_escaper->escapeHtml($origDetail), ['length' => 50])); }