CpfCnpjBase.php in Brazilian IDs 8
File
src/Element/CpfCnpjBase.php
View source
<?php
namespace Drupal\brazilian_ids\Element;
use Drupal\Core\Render\Element\Textfield;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CpfCnpjBase extends Textfield implements ContainerFactoryPluginInterface {
private $moduleHandler;
public function __construct(array $configuration, $plugin_id, $plugin_definition, ModuleHandlerInterface $module_handler) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->moduleHandler = $module_handler;
}
public function getInfo() {
$info = parent::getInfo();
$info['#size'] = 20;
$info['#element_validate'] = [
[
get_class($this),
'validateElement',
],
];
$mask = $this
->getMaskDefaults();
if ($mask && $this->moduleHandler
->moduleExists('mask')) {
$helper = new \Drupal\mask\Helper\ElementHelper();
$helper
->elementInfoAlter($info, $mask);
}
return $info;
}
protected function getMaskDefaults() {
return [];
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('module_handler'));
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
$value = parent::valueCallback($element, $input, $form_state);
return \Drupal::service('brazilian_ids')
->clean($value);
}
public static function validateElement(&$element, FormStateInterface $form_state, &$complete_form) {
$value = $element['#value'];
$error = [];
if ($value !== '' && !static::validateValue($value, $error)) {
$form_state
->setError($element, $error['message']);
}
}
protected static function validateValue($value, array &$error = []) {
return \Drupal::service('brazilian_ids')
->validateCpfCnpj($value, $error);
}
}