View source
<?php
namespace Drupal\commerce_order\Plugin\Commerce\Condition;
use Drupal\commerce\EntityUuidMapperInterface;
use Drupal\commerce\Plugin\Commerce\Condition\ConditionBase;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class OrderCustomer extends ConditionBase implements ContainerFactoryPluginInterface {
protected $entityTypeManager;
protected $entityUuidMapper;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityUuidMapperInterface $entity_uuid_mapper) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->entityUuidMapper = $entity_uuid_mapper;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('commerce.entity_uuid_mapper'));
}
public function defaultConfiguration() {
return [
'entities' => [],
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$entities = NULL;
$entity_ids = $this->entityUuidMapper
->mapToIds('user', $this->configuration['entities']);
if (count($entity_ids) > 0) {
$entities = $this->entityTypeManager
->getStorage('user')
->loadMultiple($entity_ids);
}
$form['entities'] = [
'#type' => 'entity_autocomplete',
'#title' => $this
->t('Customers'),
'#default_value' => $entities,
'#target_type' => 'user',
'#selection_settings' => [
'include_anonymous' => FALSE,
],
'#tags' => TRUE,
'#required' => TRUE,
'#maxlength' => NULL,
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$values = $form_state
->getValue($form['#parents']);
$customer_ids = array_column($values['entities'], 'target_id');
$this->configuration['entities'] = $this->entityUuidMapper
->mapFromIds('user', $customer_ids);
}
public function evaluate(EntityInterface $entity) {
$this
->assertEntity($entity);
assert($entity instanceof OrderInterface);
return in_array($entity
->getCustomer()
->uuid(), $this->configuration['entities'], TRUE);
}
}