PHP code example of phps-cans / psr7-middleware-graphql

1. Go to this page and download the library: Download phps-cans/psr7-middleware-graphql 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/ */

    

phps-cans / psr7-middleware-graphql example snippets



use Zend\Stratigility\MiddlewarePipe;
use Zend\Diactoros\Server;
use PsCs\Psr7\Middleware\Graphql\WebonyxGraphqlMiddleware;
use GraphQL\Server\StandardServer;
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\FieldDefinition;
use GraphQL\Type\Definition\Type;
use Psr7Middlewares\Middleware\Payload;
use Zend\Stratigility\Middleware\NotFoundHandler;
use Zend\Diactoros\Response;
use Zend\Stratigility\NoopFinalHandler;

// Create fields
$field = FieldDefinition::create([
            "name" => "billPerYear",
            "type" => Type::string(),
            'args'    => [
                'id' => Type::nonNull(Type::id())
            ],
            "resolve" => function($rootValue, $args) {
                return "success on ".$args["id"];
            }

        ]);
//create the schema
$schema = new Schema([
            "query" => new ObjectType([
                'name'   => 'Query',
                'fields' => [
                    $field
                ]
            ])
        ]);
$defaultUri = '/graphql'; 
$debug = false;
// create the standardServer of webonyx
$standardServer = new StandardServer(["schema" => $schema]);
// let instantiate our php server
$pipe = new MiddlewarePipe();
// Register the middleware which decode JSON body
$pipe->pipe(new \Psr7Middlewares\Middleware\Payload());
/* Instantiate and register our middleware
Params are:
- $standardServer : webonyx's graphql server: [`StandardServer`](http://webonyx.github.io/graphql-php/executing-queries/#using-server) 
- $defaultUri = This middleware will be executed for each request matching the default URI and for each request having the content-type set to "application/graphql"
- $debug = IF false, minimal error will be reported (as specified in [handling error](http://webonyx.github.io/graphql-php/error-handling/). The value of $debug must be the same as specified in [`$debug`](http://webonyx.github.io/graphql-php/error-handling/#debugging-tools)

**/
$pipe->pipe(new WebonyxGraphqlMiddleware($standardServer, $defaultUri, $debug)); 
// Add the notFoundHandler
$pipe->pipe(new NotFoundHandler(new Response()));
// Instantiate our server
$server = Server::createServer($pipe, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES);
// let tell to the server that we are ready
$server->listen(new NoopFinalHandler());