DuplicateFieldConstraintValidator.php in JSON:API Extras 8
File
src/Plugin/Validation/Constraint/DuplicateFieldConstraintValidator.php
View source
<?php
namespace Drupal\jsonapi_extras\Plugin\Validation\Constraint;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class DuplicateFieldConstraintValidator extends ConstraintValidator {
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entityTypeManager = NULL) {
$this->entityTypeManager = $entityTypeManager ?: \Drupal::entityTypeManager();
}
public function validate($entity_data, Constraint $constraint) {
$resourceFields = $entity_data['resourceFields'];
$overrides = [];
foreach ($resourceFields as $field => $data) {
if ($data['fieldName'] != $data['publicName']) {
$overrides[$field] = $data['publicName'];
}
}
$deduped_overrides = array_unique($overrides);
$dupes = array_diff_assoc($overrides, $deduped_overrides);
if ($dupes) {
foreach ($dupes as $field => $value) {
$this->context
->buildViolation($constraint->message)
->atPath("resourceFields.{$field}.publicName")
->addViolation();
}
}
foreach ($overrides as $field => $override) {
if (array_key_exists($override, $resourceFields)) {
$this->context
->buildViolation($constraint->message)
->atPath("resourceFields.{$field}.publicName")
->addViolation();
}
}
$resource_types = $this->entityTypeManager
->getStorage('jsonapi_resource_config')
->loadByProperties([
'disabled' => FALSE,
]);
foreach ($resource_types as $id => $resource_type) {
if ($entity_data['id'] == $id) {
continue;
}
if ($resource_type
->get('resourceType') == $entity_data['resourceType']) {
$this->context
->buildViolation('There is already resource (@name) with this resource type.', [
'@name' => $resource_type
->id(),
])
->atPath('resourceType')
->addViolation();
}
if ($resource_type
->get('path') == $entity_data['path']) {
$this->context
->buildViolation('There is already resource (@name) with this path.', [
'@name' => $resource_type
->id(),
])
->atPath('resourceType')
->addViolation();
}
}
}
}