3 namespace Drupal\media_entity_twitter\Plugin\Validation\Constraint;
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Drupal\media_entity_twitter\Plugin\media\Source\Twitter;
7 use Drupal\Core\Field\FieldItemInterface;
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 {
19 * The HTTP client to fetch the feed data with.
21 * @var \GuzzleHttp\Client
23 protected $httpClient;
26 * Constructs a new TweetVisibleConstraintValidator.
28 * @param \GuzzleHttp\Client $http_client
29 * The http client service.
31 public function __construct(Client $http_client) {
32 $this->httpClient = $http_client;
38 public static function create(ContainerInterface $container) {
39 return new static($container->get('http_client'));
45 public function validate($value, Constraint $constraint) {
47 if (is_string($value)) {
50 elseif ($value instanceof FieldItemList) {
51 $fieldtype = $value->getFieldDefinition()->getType();
52 $field_value = $value->getValue();
53 if ($fieldtype == 'link') {
54 $data = empty($field_value[0]['uri']) ? "" : $field_value[0]['uri'];
57 $data = empty($field_value[0]['value']) ? "" : $field_value[0]['value'];
60 elseif ($value instanceof FieldItemInterface) {
61 $class = get_class($value);
62 $property = $class::mainPropertyName();
64 $data = $value->{$property};
67 foreach (Twitter::$validationRegexp as $pattern => $key) {
68 if (preg_match($pattern, $data, $item_matches)) {
69 $matches[] = $item_matches;
73 if (empty($matches[0][0])) {
74 // If there are no matches the URL is not correct, so stop validation.
78 // Fetch content from the given url.
79 $response = $this->httpClient->get($matches[0][0], ['allow_redirects' => FALSE]);
81 if ($response->getStatusCode() == 302 && ($location = $response->getHeader('location'))) {
82 $effective_url_parts = parse_url($location[0]);
83 if (!empty($effective_url_parts) && isset($effective_url_parts['query']) && $effective_url_parts['query'] == 'protected_redirect=true') {
84 $this->context->addViolation($constraint->message);