You are here

public function TweetEmbedCodeConstraintValidator::validate in Lightning Media 8.3

Same name and namespace in other branches
  1. 8.4 modules/lightning_media_twitter/src/Plugin/Validation/Constraint/TweetEmbedCodeConstraintValidator.php \Drupal\lightning_media_twitter\Plugin\Validation\Constraint\TweetEmbedCodeConstraintValidator::validate()

File

modules/lightning_media_twitter/src/Plugin/Validation/Constraint/TweetEmbedCodeConstraintValidator.php, line 19

Class

TweetEmbedCodeConstraintValidator
Validates the TweetEmbedCode constraint.

Namespace

Drupal\lightning_media_twitter\Plugin\Validation\Constraint

Code

public function validate($value, Constraint $constraint) {
  $data = '';
  if (is_string($value)) {
    $data = $value;
  }
  elseif ($value instanceof FieldItemList) {
    $fieldtype = $value
      ->getFieldDefinition()
      ->getType();
    $field_value = $value
      ->getValue();
    if ($fieldtype == 'link') {
      $data = empty($field_value[0]['uri']) ? "" : $field_value[0]['uri'];
    }
    else {
      $data = empty($field_value[0]['value']) ? "" : $field_value[0]['value'];
    }
  }
  elseif ($value instanceof FieldItemInterface) {
    $class = get_class($value);
    $property = $class::mainPropertyName();
    if ($property) {
      $data = $value->{$property};
    }
  }
  if ($data) {
    $matches = [];
    foreach (Twitter::$validationRegexp as $pattern => $key) {
      if (preg_match($pattern, $data, $item_matches)) {
        $matches[] = $item_matches;
      }
    }
    if (empty($matches)) {
      $this->context
        ->addViolation($constraint->message);
    }
  }
}