/** * {@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; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * @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)); } }
/** * 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; }
/** * 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; }
/** * Filter value * * @param string $string * @return string */ public function filter($string) { $length = $this->length; $this->remainder = ''; if (0 == $length) { return ''; } $originalLength = $this->string->strlen($string); if ($originalLength > $length) { $length -= $this->string->strlen($this->etc); if ($length <= 0) { return ''; } $preparedString = $string; $preparedLength = $length; if (!$this->breakWords) { $preparedString = preg_replace('/\\s+?(\\S+)?$/u', '', $this->string->substr($string, 0, $length + 1)); $preparedLength = $this->string->strlen($preparedString); } $this->remainder = $this->string->substr($string, $preparedLength, $originalLength); return $this->string->substr($preparedString, 0, $length) . $this->etc; } return $string; }
/** * Accept option value and return its formatted view * * @param mixed $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] =>..., * ) * * @return array * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function getFormatedOptionValue($optionValue) { $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 $result = []; if (is_array($optionValue)) { $truncatedValue = implode("\n", $optionValue); $truncatedValue = nl2br($truncatedValue); return ['value' => $truncatedValue]; } else { $truncatedValue = $this->filterManager->truncate($optionValue, ['length' => 55, 'etc' => '']); $truncatedValue = nl2br($truncatedValue); } $result = ['value' => $truncatedValue]; if ($this->string->strlen($optionValue) > 55) { $result['value'] = $result['value'] . ' <a href="#" class="dots tooltip toggle" onclick="return false">...</a>'; $optionValue = nl2br($optionValue); $result = array_merge($result, ['full_view' => $optionValue]); } return $result; }
/** * Get data array for building attribute filter items * * @throws \Magento\Framework\Exception\LocalizedException * @return array */ protected function _getItemsData() { $attribute = $this->getAttributeModel(); $this->_requestVar = $attribute->getAttributeCode(); $options = $attribute->getFrontend()->getSelectOptions(); $optionsCount = $this->_getResource()->getCount($this); foreach ($options as $option) { if (is_array($option['value'])) { continue; } if ($this->string->strlen($option['value'])) { // Check filter type if ($this->getAttributeIsFilterable($attribute) == self::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS) { if (!empty($optionsCount[$option['value']])) { $this->itemDataBuilder->addItemData($this->tagFilter->filter($option['label']), $option['value'], $optionsCount[$option['value']]); } } else { $this->itemDataBuilder->addItemData($this->tagFilter->filter($option['label']), $option['value'], isset($optionsCount[$option['value']]) ? $optionsCount[$option['value']] : 0); } } } return $this->itemDataBuilder->build(); }
/** * Make sure that password complies with minimum security requirements. * * @param string $password * @return void * @throws InputException */ protected function checkPasswordStrength($password) { $length = $this->stringHelper->strlen($password); if ($length < self::MIN_PASSWORD_LENGTH) { throw new InputException(__('Please enter a password with at least %1 characters.', self::MIN_PASSWORD_LENGTH)); } if ($this->stringHelper->strlen(trim($password)) != $length) { throw new InputException(__('The password can\'t begin or end with a space.')); } }
/** * @param string $queryText * @param int|string $maxQueryLength * @return bool */ private function isQueryTooLong($queryText, $maxQueryLength) { return $maxQueryLength !== '' && $this->string->strlen($queryText) > $maxQueryLength; }
/** * Make sure that password complies with minimum security requirements. * * @param string $password * @return void * @throws InputException */ protected function checkPasswordStrength($password) { $length = $this->stringHelper->strlen($password); if ($length > self::MAX_PASSWORD_LENGTH) { throw new InputException(__('Please enter a password with at most %1 characters.', self::MAX_PASSWORD_LENGTH)); } $configMinPasswordLength = $this->getMinPasswordLength(); if ($length < $configMinPasswordLength) { throw new InputException(__('Please enter a password with at least %1 characters.', $configMinPasswordLength)); } if ($this->stringHelper->strlen(trim($password)) != $length) { throw new InputException(__('The password can\'t begin or end with a space.')); } $requiredCharactersCheck = $this->makeRequiredCharactersCheck($password); if ($requiredCharactersCheck !== 0) { throw new InputException(__('Minimum of different classes of characters in password is %1.' . ' Classes of characters: Lower Case, Upper Case, Digits, Special Characters.', $requiredCharactersCheck)); } }
/** * @param string $queryText * @param int|string $minQueryLength * @return bool */ private function isQueryTooShort($queryText, $minQueryLength) { return $this->string->strlen($queryText) < $minQueryLength; }
/** * Check one attribute. Can be overridden in child. * * @param string $attrCode Attribute code * @param array $attrParams Attribute params * @param array $rowData Row data * @param int $rowNum * @return boolean * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function isAttributeValid($attrCode, array $attrParams, array $rowData, $rowNum) { switch ($attrParams['type']) { case 'varchar': $val = $this->string->cleanString($rowData[$attrCode]); $valid = $this->string->strlen($val) < self::DB_MAX_VARCHAR_LENGTH; break; case 'decimal': $val = trim($rowData[$attrCode]); $valid = (double) $val == $val; break; case 'select': case 'multiselect': $valid = isset($attrParams['options'][strtolower($rowData[$attrCode])]); break; case 'int': $val = trim($rowData[$attrCode]); $valid = (int) $val == $val; break; case 'datetime': $val = trim($rowData[$attrCode]); $valid = strtotime($val) !== false; break; case 'text': $val = $this->string->cleanString($rowData[$attrCode]); $valid = $this->string->strlen($val) < self::DB_MAX_TEXT_LENGTH; break; default: $valid = true; break; } if (!$valid) { $this->addRowError(self::ERROR_CODE_ATTRIBUTE_NOT_VALID, $rowNum, $attrCode); } elseif (!empty($attrParams['is_unique'])) { if (isset($this->_uniqueAttributes[$attrCode][$rowData[$attrCode]])) { $this->addRowError(self::ERROR_CODE_DUPLICATE_UNIQUE_ATTRIBUTE, $rowNum, $attrCode); return false; } $this->_uniqueAttributes[$attrCode][$rowData[$attrCode]] = true; } return (bool) $valid; }
/** * Check one attribute can be overridden in child * * @param string $attributeCode Attribute code * @param array $attributeParams Attribute params * @param array $rowData Row data * @param int $rowNumber * @return bool * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function isAttributeValid($attributeCode, array $attributeParams, array $rowData, $rowNumber) { $message = ''; switch ($attributeParams['type']) { case 'varchar': $value = $this->string->cleanString($rowData[$attributeCode]); $valid = $this->string->strlen($value) < self::DB_MAX_VARCHAR_LENGTH; $message = self::ERROR_EXCEEDED_MAX_LENGTH; break; case 'decimal': $value = trim($rowData[$attributeCode]); $valid = (double) $value == $value && is_numeric($value); $message = self::ERROR_INVALID_ATTRIBUTE_TYPE; break; case 'select': case 'multiselect': $valid = isset($attributeParams['options'][strtolower($rowData[$attributeCode])]); $message = self::ERROR_INVALID_ATTRIBUTE_OPTION; break; case 'int': $value = trim($rowData[$attributeCode]); $valid = (int) $value == $value && is_numeric($value); $message = self::ERROR_INVALID_ATTRIBUTE_TYPE; break; case 'datetime': $value = trim($rowData[$attributeCode]); $valid = strtotime($value) !== false; $message = self::ERROR_INVALID_ATTRIBUTE_TYPE; break; case 'text': $value = $this->string->cleanString($rowData[$attributeCode]); $valid = $this->string->strlen($value) < self::DB_MAX_TEXT_LENGTH; $message = self::ERROR_EXCEEDED_MAX_LENGTH; break; default: $valid = true; break; } if (!$valid) { if ($message == self::ERROR_INVALID_ATTRIBUTE_TYPE) { $message = sprintf($this->errorMessageTemplates[$message], $attributeCode, $attributeParams['type']); } $this->addRowError($message, $rowNumber, $attributeCode); } elseif (!empty($attributeParams['is_unique'])) { if (isset($this->_uniqueAttributes[$attributeCode][$rowData[$attributeCode]])) { $this->addRowError(self::ERROR_CODE_DUPLICATE_UNIQUE_ATTRIBUTE, $rowNumber, $attributeCode); return false; } $this->_uniqueAttributes[$attributeCode][$rowData[$attributeCode]] = true; } return (bool) $valid; }