RequireOnPublishValidator.php in Require on Publish 8
File
src/Plugin/Validation/Constraint/RequireOnPublishValidator.php
View source
<?php
namespace Drupal\require_on_publish\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\field\FieldConfigInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class RequireOnPublishValidator extends ConstraintValidator implements ContainerInjectionInterface {
use StringTranslationTrait;
protected $moduleHandler;
protected $request;
protected $messenger;
public function __construct(ModuleHandlerInterface $module_handler, RequestStack $request_stack, MessengerInterface $messenger) {
$this->moduleHandler = $module_handler;
$this->messenger = $messenger;
$this->request = $request_stack
->getCurrentRequest();
}
public static function create(ContainerInterface $container) {
return new static($container
->get('module_handler'), $container
->get('request_stack'), $container
->get('messenger'));
}
public function validate($entity, Constraint $constraint) {
if (!isset($entity)) {
return;
}
$is_published = $entity
->isPublished();
if ($this->moduleHandler
->moduleExists('paragraphs') && $entity
->getEntityTypeId() == 'paragraph') {
if ($this->request) {
$status = $this->request->request
->get('status', [
'value' => 0,
]);
$is_published = $status['value'];
}
else {
$is_published = $entity
->getParentEntity()
->isPublished();
}
}
foreach ($entity
->getFields() as $field) {
$field_config = $field
->getFieldDefinition();
if (!$field_config instanceof FieldConfigInterface) {
continue;
}
if (!$field
->isEmpty()) {
continue;
}
if (!$field_config
->getThirdPartySetting('require_on_publish', 'require_on_publish', FALSE)) {
continue;
}
if ($is_published) {
$message = $this
->t($constraint->message, [
'%field_label' => $field_config
->getLabel(),
]);
$this->context
->buildViolation($message)
->atPath($field
->getName())
->addViolation();
}
else {
if (!$field_config
->getThirdPartySetting('require_on_publish', 'warn_on_empty', FALSE)) {
continue;
}
$message = $this
->t('%label can not be empty on publication', [
'%label' => $field_config
->getLabel(),
]);
$this->messenger
->addWarning($message);
}
}
}
}