JsonQueryMapQueryProvider.php in GraphQL 8.3
File
src/GraphQL/QueryProvider/JsonQueryMapQueryProvider.php
View source
<?php
namespace Drupal\graphql\GraphQL\QueryProvider;
use Drupal\Component\FileSystem\RegexDirectoryIterator;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use GraphQL\Server\OperationParams;
class JsonQueryMapQueryProvider implements QueryProviderInterface {
protected $cacheBackend;
protected $lookupPaths;
public function __construct(CacheBackendInterface $cacheBackend, ConfigFactoryInterface $configFactory) {
$this->lookupPaths = $configFactory
->get('graphql.query_map_json.config')
->get('lookup_paths') ?: [];
$this->cacheBackend = $cacheBackend;
}
public function getQuery($id, OperationParams $operation) {
list($version, $id) = explode(':', $id);
if (empty($version) || empty($id)) {
return NULL;
}
if (!(($cache = $this->cacheBackend
->get('graphql_query_map_json_versions')) && ($versions = $cache->data) !== NULL)) {
$this->cacheBackend
->set('graphql_query_map_json_versions', $versions = $this
->discoverQueryMaps());
}
if (isset($versions) && isset($versions[$version]) && file_exists($versions[$version])) {
$contents = json_decode(file_get_contents($versions[$version]), TRUE);
if ($query = array_search($id, $contents)) {
return $query;
}
}
return NULL;
}
protected function discoverQueryMaps() {
$maps = [];
foreach ($this->lookupPaths as $path) {
if (is_dir($path)) {
$iterator = new RegexDirectoryIterator($path, '/\\.json/i');
foreach ($iterator as $file) {
$hash = sha1(file_get_contents($file
->getPathname()));
$maps[$hash] = $file
->getPathname();
}
}
if (is_file($path)) {
$file = new \SplFileInfo($path);
$hash = sha1(file_get_contents($file
->getPathname()));
$maps[$hash] = $file
->getPathname();
}
}
return $maps;
}
}