You are here

public function ViewsJsonQuery::fetchFile in Views Json Source 8

Same name and namespace in other branches
  1. 1.x src/Plugin/views/query/ViewsJsonQuery.php \Drupal\views_json_source\Plugin\views\query\ViewsJsonQuery::fetchFile()

Fetch file.

1 call to ViewsJsonQuery::fetchFile()
ViewsJsonQuery::execute in src/Plugin/views/query/ViewsJsonQuery.php
Executes the query and fills the associated view object with according values.

File

src/Plugin/views/query/ViewsJsonQuery.php, line 131

Class

ViewsJsonQuery
Base query handler for views_json_source.

Namespace

Drupal\views_json_source\Plugin\views\query

Code

public function fetchFile($uri) {
  $parsed = parse_url($uri);

  // Check for local file.
  if (empty($parsed['host'])) {
    if (!file_exists(DRUPAL_ROOT . $uri)) {
      throw new \Exception($this
        ->t('Local file not found.'));
    }
    return file_get_contents(DRUPAL_ROOT . $uri);
  }
  $cache_id = 'views_json_source_' . md5($uri);
  if ($cache = $this->cache
    ->get($cache_id)) {
    $json_content = $cache->data;
  }
  else {

    // Add the request headers if available.
    $headers = $this->options['headers'] ? json_decode($this->options['headers'], TRUE) ?? [] : [];
    $result = \Drupal::httpClient()
      ->get($uri, [
      'headers' => $headers,
    ]);
    if (isset($result->error)) {
      $args = [
        '%error' => $result->error,
        '%uri' => $uri,
      ];
      $message = $this
        ->t('HTTP response: %error. URI: %uri', $args);
      throw new \Exception($message);
    }

    // Save to file.
    $config = $this->config
      ->get('views_json_source.settings');
    $cache_duration = $config
      ->get('cache_ttl');
    $json_content = (string) $result
      ->getBody();
    $cache_ttl = \Drupal::time()
      ->getRequestTime() + $cache_duration;

    // Dispatch event before caching json_content.
    $event = new PreCacheEvent($this->view, $json_content);
    $this->eventDispatcher
      ->dispatch(PreCacheEvent::VIEWS_JSON_SOURCE_PRE_CACHE, $event);
    $json_content = $event
      ->getViewData();
    $this->cache
      ->set($cache_id, $json_content, $cache_ttl);
  }
  return $json_content;
}