public function RequireOnPublishValidator::validate in Require on Publish 8
File
- src/
Plugin/ Validation/ Constraint/ RequireOnPublishValidator.php, line 73
Class
- RequireOnPublishValidator
- Validates the RequireOnPublish constraint.
Namespace
Drupal\require_on_publish\Plugin\Validation\ConstraintCode
public function validate($entity, Constraint $constraint) {
if (!isset($entity)) {
return;
}
$is_published = $entity
->isPublished();
// If the entity is a paragraph, we need to determine the publish status of
// its parent entity.
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();
}
}
/** @var \Drupal\Core\Field\FieldItemListInterface $field */
foreach ($entity
->getFields() as $field) {
/** @var \Drupal\Core\Field\FieldConfigInterface $field_config */
$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);
}
}
}