PHP code example of x-graphql / schema-gateway

1. Go to this page and download the library: Download x-graphql/schema-gateway library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

x-graphql / schema-gateway example snippets




raphQL\GraphQL;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Utils\SchemaPrinter;
use GraphQL\Type\Schema;
use XGraphQL\HttpSchema\HttpDelegator;
use XGraphQL\HttpSchema\HttpSchemaFactory;
use XGraphQL\SchemaGateway\MandatorySelectionSetProviderInterface;
use XGraphQL\SchemaGateway\Relation;
use XGraphQL\SchemaGateway\RelationArgumentResolverInterface;
use XGraphQL\SchemaGateway\RelationOperation;
use XGraphQL\SchemaGateway\SchemaGatewayFactory;
use XGraphQL\SchemaGateway\SubSchema;

$localSchema = new Schema([
    'query' => new ObjectType([
        'name' => 'Query',
        'fields' => [
            'person' => [
                'type' => new ObjectType([
                    'name' => 'Person',
                    'fields' => [
                        'name' => Type::nonNull(Type::string()),
                        'fromCountry' => Type::nonNull(Type::string()),
                    ],

                ]),
                'resolve' => fn() => ['name' => 'John Doe', 'fromCountry' => 'VN']
            ],
        ],
    ]),
]);
$localSubSchema = new SubSchema('local', $localSchema);

$remoteSchema = HttpSchemaFactory::createFromIntrospectionQuery(
    new HttpDelegator('https://countries.trevorblades.com/'),
);
$remoteSubSchema = new SubSchema('remote', $remoteSchema);

$countryRelation = new Relation(
    'Person',
    'remoteCountry',
    RelationOperation::QUERY,
    'country',
    new class implements RelationArgumentResolverInterface, MandatorySelectionSetProviderInterface {
        public function shouldKeep(string $argumentName, Relation $relation): bool
        {
            return false;
        }

        public function resolve(array $objectValue, array $currentArgs, Relation $relation): array
        {
            return ['code' => $objectValue['fromCountry']];
        }

        public function getMandatorySelectionSet(Relation $relation): string
        {
            return '{ fromCountry }';
        }
    }
);

$schemaGateway = SchemaGatewayFactory::create([$localSubSchema, $remoteSubSchema], [$countryRelation]);

$query = <<<'GQL'
query {
  continents {
    name
  }

  person {
    name
    remoteCountry {
      name
      code
    }
  }
}
GQL;

var_dump(SchemaPrinter::doPrint($schemaGateway));
var_dump(GraphQL::executeQuery($schemaGateway, $query)->toArray());