3 namespace Drupal\media_entity_twitter\Plugin\Validation\Constraint;
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Drupal\media_entity\EmbedCodeValueTrait;
7 use Drupal\media_entity_twitter\Plugin\MediaEntity\Type\Twitter;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use Symfony\Component\Validator\Constraint;
11 use Symfony\Component\Validator\ConstraintValidator;
14 * Validates the TweetVisible constraint.
16 class TweetVisibleConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
18 use EmbedCodeValueTrait;
21 * The HTTP client to fetch the feed data with.
23 * @var \GuzzleHttp\Client
25 protected $httpClient;
28 * Constructs a new TweetVisibleConstraintValidator.
30 * @param \GuzzleHttp\Client $http_client
31 * The http client service.
33 public function __construct(Client $http_client) {
34 $this->httpClient = $http_client;
40 public static function create(ContainerInterface $container) {
41 return new static($container->get('http_client'));
47 public function validate($value, Constraint $constraint) {
48 $value = $this->getEmbedCode($value);
55 foreach (Twitter::$validationRegexp as $pattern => $key) {
56 if (preg_match($pattern, $value, $item_matches)) {
57 $matches[] = $item_matches;
61 if (empty($matches[0][0])) {
62 // If there are no matches the URL is not correct, so stop validation.
66 // Fetch content from the given url.
67 $response = $this->httpClient->get($matches[0][0], ['allow_redirects' => FALSE]);
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);