8843f6f644741dbd862f8864bf89f2bdd6efee14
[yaffs-website] / web / modules / contrib / media_entity_twitter / src / Plugin / Validation / Constraint / TweetVisibleConstraintValidator.php
1 <?php
2
3 namespace Drupal\media_entity_twitter\Plugin\Validation\Constraint;
4
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Drupal\media_entity\EmbedCodeValueTrait;
7 use Drupal\media_entity_twitter\Plugin\MediaEntity\Type\Twitter;
8 use GuzzleHttp\Client;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use Symfony\Component\Validator\Constraint;
11 use Symfony\Component\Validator\ConstraintValidator;
12
13 /**
14  * Validates the TweetVisible constraint.
15  */
16 class TweetVisibleConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
17
18   use EmbedCodeValueTrait;
19
20   /**
21    * The HTTP client to fetch the feed data with.
22    *
23    * @var \GuzzleHttp\Client
24    */
25   protected $httpClient;
26
27   /**
28    * Constructs a new TweetVisibleConstraintValidator.
29    *
30    * @param \GuzzleHttp\Client $http_client
31    *   The http client service.
32    */
33   public function __construct(Client $http_client) {
34     $this->httpClient = $http_client;
35   }
36
37   /**
38    * {@inheritdoc}
39    */
40   public static function create(ContainerInterface $container) {
41     return new static($container->get('http_client'));
42   }
43
44   /**
45    * {@inheritdoc}
46    */
47   public function validate($value, Constraint $constraint) {
48     $value = $this->getEmbedCode($value);
49     if (!isset($value)) {
50       return;
51     }
52
53     $matches = [];
54
55     foreach (Twitter::$validationRegexp as $pattern => $key) {
56       if (preg_match($pattern, $value, $item_matches)) {
57         $matches[] = $item_matches;
58       }
59     }
60
61     if (empty($matches[0][0])) {
62       // If there are no matches the URL is not correct, so stop validation.
63       return;
64     }
65
66     // Fetch content from the given url.
67     $response = $this->httpClient->get($matches[0][0], ['allow_redirects' => FALSE]);
68
69     if ($response->getStatusCode() == 302 && ($location = $response->getHeader('location'))) {
70       $effective_url_parts = parse_url($location[0]);
71       if (!empty($effective_url_parts) && isset($effective_url_parts['query']) && $effective_url_parts['query'] == 'protected_redirect=true') {
72         $this->context->addViolation($constraint->message);
73       }
74     }
75   }
76
77 }