graphql_compose-1.0.0-beta20/src/Plugin/GraphQL/DataProducer/SchemaEnumValue.php

src/Plugin/GraphQL/DataProducer/SchemaEnumValue.php
<?php

declare(strict_types=1);

namespace Drupal\graphql_compose\Plugin\GraphQL\DataProducer;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\graphql\Attribute\DataProducer;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Drupal\graphql_compose\Plugin\GraphQLComposeSchemaTypeManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Get enum value.
 */
#[DataProducer(
  id: "schema_enum_value",
  name: new TranslatableMarkup("Schema enum value"),
  description: new TranslatableMarkup("Dig out a value from an enum"),
  produces: new ContextDefinition(
    data_type: "any",
    label: new TranslatableMarkup("FieldItemListInterface"),
  ),
  consumes: [
    "type" => new ContextDefinition(
      data_type: "string",
      label: new TranslatableMarkup("Schema type defined in graphql compose plugin"),
    ),
    "value" => new ContextDefinition(
      data_type: "any",
      label: new TranslatableMarkup("Enum(s) to return"),
    ),
  ],
)]
class SchemaEnumValue extends DataProducerPluginBase implements ContainerFactoryPluginInterface {

  /**
   * Schema type manager.
   *
   * @var \Drupal\graphql_compose\Plugin\GraphQLComposeSchemaTypeManager
   */
  protected GraphQLComposeSchemaTypeManager $gqlSchemaTypeManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
    );

    $instance->gqlSchemaTypeManager = $container->get('graphql_compose.schema_type_manager');

    return $instance;
  }

  /**
   * Finds the requested enum value.
   *
   * @param string $type
   *   The enum type to search.
   * @param string|array $value
   *   The value(s) to search for.
   *
   * @return string|array|null
   *   The found value(s).
   */
  public function resolve(string $type, string|array $value): string | array | null {

    $type = $this->gqlSchemaTypeManager->get($type);
    if (!$type || !$value) {
      return NULL;
    }

    /** @var \GraphQL\Type\Definition\EnumType $type */
    if (!is_array($value)) {
      return $type->getValue($value)?->value ?: NULL;
    }

    $result = [];
    foreach ($value as $key) {
      if (!is_string($key)) {
        continue;
      }
      if ($found = $type->getValue($key)?->value) {
        $result[] = $found;
      }
    }

    return $result ?: NULL;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc