You are here

public function ApiDocFileLinkConstraintValidator::validate in Apigee API Catalog 8.2

Same name and namespace in other branches
  1. 8 src/Plugin/Validation/Constraint/ApiDocFileLinkConstraintValidator.php \Drupal\apigee_api_catalog\Plugin\Validation\Constraint\ApiDocFileLinkConstraintValidator::validate()

File

src/Plugin/Validation/Constraint/ApiDocFileLinkConstraintValidator.php, line 63

Class

ApiDocFileLinkConstraintValidator
Class ApiDocFileLinkConstraintValidator.

Namespace

Drupal\apigee_api_catalog\Plugin\Validation\Constraint

Code

public function validate($items, Constraint $constraint) {

  /** @var \Drupal\Core\Field\FieldItemListInterface $items */
  if (!isset($items)) {
    return;
  }
  foreach ($items as $item) {
    if ($item
      ->isEmpty()) {
      continue;
    }

    // Try to resolve the given URI to a URL. It may fail if it's scheme-less.
    try {
      $url = Url::fromUri($item
        ->getValue()['uri'], [
        'absolute' => TRUE,
      ])
        ->toString();
    } catch (\InvalidArgumentException $e) {
      $this->context
        ->addViolation($constraint->urlParseError, [
        '@error' => $e
          ->getMessage(),
      ]);
      return;
    }
    try {
      $options = [
        'allow_redirects' => [
          'strict' => TRUE,
        ],
      ];

      // Perform only a HEAD method to save bandwidth.

      /* @var $response \Psr\Http\Message\ResponseInterface */
      $response = $this->httpClient
        ->head($url, $options);
    } catch (RequestException $request_exception) {
      $this->context
        ->addViolation($constraint->notValid, [
        '%value' => $url,
      ]);
    }
  }
}