You are here

class PinEmbedCodeConstraintValidator in Media entity Pinterest 8.2

Same name and namespace in other branches
  1. 8 src/Plugin/Validation/Constraint/PinEmbedCodeConstraintValidator.php \Drupal\media_entity_pinterest\Plugin\Validation\Constraint\PinEmbedCodeConstraintValidator

Validates the PinEmbedCode constraint.

Hierarchy

  • class \Drupal\media_entity_pinterest\Plugin\Validation\Constraint\PinEmbedCodeConstraintValidator extends \Symfony\Component\Validator\ConstraintValidator

Expanded class hierarchy of PinEmbedCodeConstraintValidator

1 file declares its use of PinEmbedCodeConstraintValidator
ConstraintsTest.php in tests/src/Unit/ConstraintsTest.php

File

src/Plugin/Validation/Constraint/PinEmbedCodeConstraintValidator.php, line 13

Namespace

Drupal\media_entity_pinterest\Plugin\Validation\Constraint
View source
class PinEmbedCodeConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($value, Constraint $constraint) {
    $value = $this
      ->getEmbedCode($value);
    if (!isset($value)) {
      return;
    }
    $matches = [];
    foreach (Pinterest::$validationRegexp as $pattern => $key) {

      // URLs will sometimes have urlencoding, so we decode for safety.
      if (preg_match($pattern, urldecode($value), $item_matches)) {
        $matches[] = $item_matches;
      }
    }
    if (empty($matches)) {
      $this->context
        ->addViolation($constraint->message);
    }
  }

  /**
   * Extracts the raw embed code from input which may or may not be wrapped.
   *
   * @param mixed $value
   *   The input value. Can be a normal string or a value wrapped by the
   *   Typed Data API.
   *
   * @return string|null
   *   The raw embed code.
   */
  protected function getEmbedCode($value) {
    if (is_string($value)) {
      return $value;
    }
    elseif ($value instanceof FieldItemInterface) {
      $class = get_class($value);
      $property = $class::mainPropertyName();
      if ($property) {
        return $value->{$property};
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
PinEmbedCodeConstraintValidator::getEmbedCode protected function Extracts the raw embed code from input which may or may not be wrapped.
PinEmbedCodeConstraintValidator::validate public function Checks if the passed value is valid.