CvValidatorBase.php in Clientside Validation 8.2
File
src/CvValidatorBase.php
View source
<?php
namespace Drupal\clientside_validation;
use Drupal\Component\Plugin\PluginBase;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Component\Utility\NestedArray;
abstract class CvValidatorBase extends PluginBase implements CvValidatorInterface {
use StringTranslationTrait;
public function getName() {
return $this->pluginDefinition['name'];
}
protected abstract function getRules($element, FormStateInterface $form_state);
public function addValidation(array &$element, FormStateInterface $form_state) {
$rules = $this
->getRules($element, $form_state);
if (isset($rules['rules'])) {
foreach ($rules['rules'] as $rulename => $rulearg) {
$element['#attributes']['data-rule-' . mb_strtolower($rulename)] = is_object($rulearg) || is_array($rulearg) ? Json::encode($rulearg) : $rulearg;
}
}
if (isset($rules['messages'])) {
foreach ($rules['messages'] as $rulename => $message) {
$element['#attributes']['data-msg-' . mb_strtolower($rulename)] = $message;
}
}
if (isset($rules['messages']) || isset($rules['rules'])) {
if (!isset($element['#attached'])) {
$element['#attached'] = [];
}
$element['#attached'] = NestedArray::mergeDeep($element['#attached'], $this
->getPluginDefinition()['attachments']);
}
}
protected function getAttributeValue(array $element, $attribute) {
return isset($element['#' . $attribute]) ? $element['#' . $attribute] : (isset($element['#attributes'][$attribute]) ? $element['#attributes'][$attribute] : NULL);
}
protected function getElementTitle(array $element, $default = '') {
$title = $this
->getAttributeValue($element, 'title');
if (empty($title) && empty($default)) {
return t('This field');
}
return $title ? $title : $default;
}
}