You are here

public function ViewsSchemaProvider::getQuerySchema in GraphQL 8

Same name and namespace in other branches
  1. 8.2 src/SchemaProvider/ViewsSchemaProvider.php \Drupal\graphql\SchemaProvider\ViewsSchemaProvider::getQuerySchema()

Return value

array

Overrides SchemaProviderBase::getQuerySchema

File

src/SchemaProvider/ViewsSchemaProvider.php, line 86

Class

ViewsSchemaProvider
Generates a GraphQL Schema for views.

Namespace

Drupal\graphql\SchemaProvider

Code

public function getQuerySchema() {

  // Do not attempt to generate the schema if the views module is not enabled.
  if (!$this->moduleHandler
    ->moduleExists('views')) {
    return [];
  }
  $fields = [];
  $map = $this
    ->getDataTableMap();

  /** @var \Drupal\views\ViewEntityInterface $view */
  foreach ($this->entityManager
    ->getStorage('view')
    ->loadMultiple() as $view) {
    $baseTable = $view
      ->get('base_table');
    if (!isset($map[$baseTable])) {
      continue;
    }
    $viewId = $view
      ->id();
    foreach ($view
      ->get('display') as $displayId => $display) {
      if ($display['display_plugin'] !== 'graphql') {
        continue;
      }
      $executable = $view
        ->getExecutable();
      $executable
        ->setDisplay($displayId);
      $filters = $executable
        ->getDisplay()
        ->getOption('filters');
      $filters = array_reduce(array_filter($filters, function (array $filter) {
        return !empty($filter['exposed']);
      }), function (array $carry, array $filter) {
        $type = $filter['expose']['required'] ? new NonNullModifier(Type::stringType()) : Type::stringType();
        $type = $filter['expose']['multiple'] ? new ListModifier($type) : $type;
        $type = $filter['expose']['required'] ? new NonNullModifier($type) : $type;
        $carry[$filter['expose']['identifier']] = [
          'type' => $type,
        ];
        return $carry;
      }, []);
      $definition = $this->typedDataManager
        ->createDataDefinition("entity:{$map[$baseTable]}");
      if (!($resolved = $this->typeResolver
        ->resolveRecursive($definition))) {
        continue;
      }
      $fields["{$viewId}:{$displayId}"] = [
        'type' => new ListModifier($resolved),
        'resolve' => [
          __CLASS__,
          'getViewResults',
        ],
        'args' => $filters,
        'resolveData' => [
          'view' => $viewId,
          'display' => $displayId,
        ],
      ];
    }
  }
  $names = StringHelper::formatPropertyNameList(array_keys($fields));
  return array_combine($names, $fields);
}