You are here

protected function Xml::fetchRemoteFile in Views XML Backend 8

Returns the contents of a remote file.

Parameters

string $uri: The remote file URL.

Return value

string The file contents.

1 call to Xml::fetchRemoteFile()
Xml::fetchFileContents in src/Plugin/views/query/Xml.php
Returns the contents of an XML file.

File

src/Plugin/views/query/Xml.php, line 624
Contains \Drupal\views_xml_backend\Plugin\views\query\Xml.

Class

Xml
Views query plugin for an XML query.

Namespace

Drupal\views_xml_backend\Plugin\views\query

Code

protected function fetchRemoteFile($uri) {
  $destination = Settings::get('views_xml_backend_cache_directory', static::DEFAULT_CACHE_DIR);
  if (!file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
    if ($this->livePreview) {
      $this->messenger
        ->setMessage($this
        ->t('File cache directory either cannot be created or is not writable.'), 'error');
    }
    $this->logger
      ->error('File cache directory either cannot be created or is not writable.');
    return (string) $this
      ->doGetRequest($uri)
      ->getBody();
  }
  $cache_key = hash('sha256', $uri);
  $cache_file = "{$destination}/{$cache_key}";
  $options = [];

  // Add cached headers if requested.
  if ($cache = $this->cacheBackend
    ->get($cache_key)) {
    if (isset($cache->data['etag'])) {
      $options[RequestOptions::HEADERS]['If-None-Match'] = $cache->data['etag'];
    }
    if (isset($cache->data['last-modified'])) {
      $options[RequestOptions::HEADERS]['If-Modified-Since'] = $cache->data['last-modified'];
    }
  }
  $response = $this
    ->doGetRequest($uri, $options);
  if ($response
    ->getStatusCode() === 304) {
    if (file_exists($cache_file)) {
      return file_get_contents($cache_file);
    }

    // We have the headers but no cache file. Run it again.
    $this->cacheBackend
      ->delete($cache_key);
    return $this
      ->fetchRemoteFile($uri);
  }

  // We had a failed requset. Try to return the old result.
  if ($response
    ->getStatusCode() === -100) {
    if (file_exists($cache_file)) {
      return file_get_contents($cache_file);
    }
  }
  $data = trim($response
    ->getBody());
  file_unmanaged_save_data($data, $cache_file, FILE_EXISTS_REPLACE);
  $this->cacheBackend
    ->set($cache_key, array_change_key_case($response
    ->getHeaders()));
  return $data;
}