You are here

class ValidJSONConstraintValidator in JSON Field 8

Checks if JSON values are valid.

Hierarchy

Expanded class hierarchy of ValidJSONConstraintValidator

File

src/Plugin/Validation/Constraint/ValidJSONConstraintValidator.php, line 14

Namespace

Drupal\json_field\Plugin\Validation\Constraint
View source
class ValidJSONConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {

  /**
   * The serializer which serializes the views result.
   *
   * @var \Symfony\Component\Serializer\Encoder\DecoderInterface
   */
  protected $serializer;

  /**
   * Constructs a ValidJSONConstraintValidator object.
   *
   * @param \Symfony\Component\Serializer\Encoder\DecoderInterface $serializer
   */
  public function __construct(DecoderInterface $serializer) {
    $this->serializer = $serializer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('serializer'));
  }

  /**
   * {@inheritdoc}
   */
  public function validate($value, Constraint $constraint) {

    // Empty should be handled by the field settings.
    if (empty($value->value)) {
      return;
    }
    try {
      $this->serializer
        ->decode($value->value, 'json');
    } catch (\Exception $e) {

      // Add a constraint violation with the `json_decode` message on failure.
      $this->context
        ->addViolation($constraint->message, [
        '@error' => $e
          ->getMessage(),
      ]);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ValidJSONConstraintValidator::$serializer protected property The serializer which serializes the views result.
ValidJSONConstraintValidator::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create
ValidJSONConstraintValidator::validate public function Checks if the passed value is valid.
ValidJSONConstraintValidator::__construct public function Constructs a ValidJSONConstraintValidator object.