media_library_extend_crowdriff-1.x-dev/src/Plugin/Validation/Constraint/UniqueAssetIdValidator.php

src/Plugin/Validation/Constraint/UniqueAssetIdValidator.php
<?php

namespace Drupal\media_library_extend_crowdriff\Plugin\Validation\Constraint;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Drupal\media_library_extend_crowdriff\CrowdriffAssetService;

/**
 * Validates the UniqueAssetId constraint.
 */
class UniqueAssetIdValidator extends ConstraintValidator implements ContainerInjectionInterface {

  /**
   * The Crowdriff asset service.
   *
   * @var \Drupal\media_library_extend_crowdriff\CrowdriffAssetService
   */
  protected $crowdriffAssetService;

  /**
   * The constructor.
   *
   * @param \Drupal\media_library_extend_crowdriff\CrowdriffAssetService $crowdriff_asset_service
   *   The Crowdriff asset service.
   */
  public function __construct(CrowdriffAssetService $crowdriff_asset_service) {
    $this->crowdriffAssetService = $crowdriff_asset_service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): UniqueAssetIdValidator {
    return new static(
      $container->get('media_library_extend_crowdriff.crowdriff_asset_service')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    // Loop over values in field. Should only be one in this case.
    foreach ($items as $item) {
      // Check to see if asset id is unique. Add error message if not.
      if (!empty($item->value) && !$this->crowdriffAssetService->isAssetUnique($item->value, [$items->getEntity()->id()])) {
        $this->context->addViolation($constraint->message, ['%value' => $item->value]);
      }
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc