public function ViewsJsonQuery::fetchFile in Views Json Source 1.x
Same name and namespace in other branches
- 8 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 64
Class
- ViewsJsonQuery
- Base query handler for views_json_source.
Namespace
Drupal\views_json_source\Plugin\views\queryCode
public function fetchFile($uri) {
$parsed = parse_url($uri);
// Check for local file.
if (empty($parsed['host'])) {
if (!file_exists($uri)) {
throw new \Exception($this
->t('Local file not found.'));
}
return file_get_contents($uri);
}
$destination = 'public://views_json_source';
if (!file_prepare_directory($destination, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
throw new \Exception($this
->t('Files directory either cannot be created or is not writable.'));
}
$headers = [];
$cache_file = 'views_json_source_' . md5($uri);
if ($cache = \Drupal::cache()
->get($cache_file)) {
$last_headers = $cache->data;
if (!empty($last_headers['etag'])) {
$headers['If-None-Match'] = $last_headers['etag'];
}
if (!empty($last_headers['last-modified'])) {
$headers['If-Modified-Since'] = $last_headers['last-modified'];
}
}
$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);
}
$cache_file_uri = "{$destination}/{$cache_file}";
if ($result
->getStatusCode() == 304) {
if (file_exists($cache_file_uri)) {
return file_get_contents($cache_file_uri);
}
// We have the headers but no cache file. :(
// Run it back.
\Drupal::cache('bin')
->invalidate($cache_file);
return $this
->fetchFile($uri);
}
// As learned from Feeds caching mechanism, save to file.
file_save_data((string) $result
->getBody(), $cache_file_uri, FileSystemInterface::EXISTS_REPLACE);
\Drupal::cache()
->set($cache_file, $result
->getHeaders());
return (string) $result
->getBody();
}