View source
<?php
namespace Drupal\commerce_number_pattern\Plugin\Commerce\NumberPattern;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Utility\Token;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class NumberPatternBase extends PluginBase implements NumberPatternInterface, ContainerFactoryPluginInterface {
protected $token;
protected $parentEntity;
public function __construct(array $configuration, $plugin_id, $plugin_definition, Token $token) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->token = $token;
if (array_key_exists('_entity', $configuration)) {
$this->parentEntity = $configuration['_entity'];
unset($configuration['_entity']);
}
$this
->setConfiguration($configuration);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('token'));
}
public function getConfiguration() {
return $this->configuration;
}
public function setConfiguration(array $configuration) {
$this->configuration = NestedArray::mergeDeep($this
->defaultConfiguration(), $configuration);
}
public function defaultConfiguration() {
return [
'pattern' => '',
];
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$entity_type_id = $form_state
->get('target_entity_type');
$token_types = [
'pattern',
];
if ($entity_type_id) {
$token_types[] = $entity_type_id;
}
$form['pattern'] = [
'#title' => $this
->t('Pattern'),
'#type' => 'textfield',
'#description' => $this
->t('Allows adding a prefix (such as "INV-") or a suffix to the number.'),
'#default_value' => $this->configuration['pattern'],
'#required' => TRUE,
'#element_validate' => [
'token_element_validate',
],
'#token_types' => $token_types,
];
$form['pattern_help'] = [
'#theme' => 'token_tree_link',
'#token_types' => $token_types,
'#global_types' => FALSE,
];
return $form;
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
if (!$form_state
->getErrors()) {
$values = $form_state
->getValue($form['#parents']);
$this->configuration = [];
$this->configuration['pattern'] = $values['pattern'];
}
}
public function generate(ContentEntityInterface $entity) {
$number = $this->token
->replace($this->configuration['pattern'], [
'pattern' => [],
$entity
->getEntityTypeId() => $entity,
]);
return $number;
}
}