WidgetValidationBase.php in Entity Browser 8
File
src/WidgetValidationBase.php
View source
<?php
namespace Drupal\entity_browser;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\TypedDataManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\ConstraintViolationList;
abstract class WidgetValidationBase extends PluginBase implements WidgetValidationInterface, ContainerFactoryPluginInterface {
protected $label;
protected $typedDataManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, TypedDataManagerInterface $typed_data_manager) {
$plugin_definition += [
'constraint' => NULL,
];
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->typedDataManager = $typed_data_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('typed_data_manager'));
}
public function defaultConfiguration() {
return [];
}
public function label() {
$this->label;
}
public function validate(array $entities, array $options = []) {
$plugin_definition = $this
->getPluginDefinition();
$data_definition = $this
->getDataDefinition($plugin_definition['data_type'], $plugin_definition['constraint'], $options);
return $this
->validateDataDefinition($data_definition, $entities);
}
public function getConfiguration() {
return $this->configuration;
}
public function setConfiguration(array $configuration) {
$this->configuration = $configuration;
}
public function calculateDependencies() {
return [];
}
protected function getDataDefinition($data_type, $constraint_name = NULL, array $options = []) {
$data_definition = $this->typedDataManager
->createDataDefinition($data_type);
if ($constraint_name) {
$data_definition
->addConstraint($constraint_name, $options);
}
return $data_definition;
}
protected function validateDataDefinition(DataDefinitionInterface $data_definition, array $entities) {
$violations = new ConstraintViolationList();
foreach ($entities as $entity) {
$validation_result = $this->typedDataManager
->create($data_definition, $entity)
->validate();
$violations
->addAll($validation_result);
}
return $violations;
}
}