699a819416639accfb0f82221d05e101bb512620
[yaffs-website] / web / modules / contrib / media_entity_twitter / src / Plugin / Validation / Constraint / TweetEmbedCodeConstraintValidator.php
1 <?php
2
3 namespace Drupal\media_entity_twitter\Plugin\Validation\Constraint;
4
5 use Drupal\media_entity_twitter\Plugin\media\Source\Twitter;
6 use Drupal\Core\Field\FieldItemList;
7 use Drupal\Core\Field\FieldItemInterface;
8 use Symfony\Component\Validator\Constraint;
9 use Symfony\Component\Validator\ConstraintValidator;
10
11 /**
12  * Validates the TweetEmbedCode constraint.
13  */
14 class TweetEmbedCodeConstraintValidator extends ConstraintValidator {
15
16   /**
17    * {@inheritdoc}
18    */
19   public function validate($value, Constraint $constraint) {
20     $data = '';
21     if (is_string($value)) {
22       $data = $value;
23     }
24     elseif ($value instanceof FieldItemList) {
25       $fieldtype = $value->getFieldDefinition()->getType();
26       $field_value = $value->getValue();
27       if ($fieldtype == 'link') {
28         $data = empty($field_value[0]['uri']) ? "" : $field_value[0]['uri'];
29       }
30       else {
31         $data = empty($field_value[0]['value']) ? "" : $field_value[0]['value'];
32       }
33     }
34     elseif ($value instanceof FieldItemInterface) {
35       $class = get_class($value);
36       $property = $class::mainPropertyName();
37       if ($property) {
38         $data = $value->{$property};
39       }
40     }
41     if ($data) {
42       $matches = [];
43       foreach (Twitter::$validationRegexp as $pattern => $key) {
44         if (preg_match($pattern, $data, $item_matches)) {
45           $matches[] = $item_matches;
46         }
47       }
48       if (empty($matches)) {
49         $this->context->addViolation($constraint->message);
50       }
51     }
52   }
53
54 }