<?php namespace App; use PDO; class DB { private static $pdo; public static function init($config) { // PDO self::$pdo = new PDO("mysql:host={$config['host']};dbname={$config['database']}", $config['username'], $config['password']); // self::$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); } public static function selectOne($query) { $records = self::select($query); return array_shift($records); } public static function select($query) { $statement = self::$pdo->query($query); return $statement->fetchAll(); } public static function affectingStatement($query) { $statement = self::$pdo->query($query); return $statement->rowCount(); } public static function update($query) { $statement = self::$pdo->query($query); $statement->execute(); return $statement->rowCount(); } public static function insert($query) { $statement = self::$pdo->query($query); $success = $statement->execute(); return $success ? self::$pdo->lastInsertId() : null; } }
<?php namespace App\Type; use App\DB; use App\Types; use GraphQL\Type\Definition\ObjectType; class MutationType extends ObjectType { public function __construct() { $config = [ 'fields' => function() { return [ // ]; } ]; parent::__construct($config); } }
use App\Type\MutationType; private static $mutation; public static function mutation() { return self::$mutation ?: (self::$mutation = new MutationType()); }
$schema = new Schema([ 'query' => Types::query(), 'mutation' => Types::mutation() ]);
<?php namespace App\Type; use App\DB; use App\Types; use GraphQL\Type\Definition\ObjectType; class MutationType extends ObjectType { public function __construct() { $config = [ 'fields' => function() { return [ 'changeUserEmail' => [ 'type' => Types::user(), 'description' => ' E-mail ', 'args' => [ 'id' => Types::int(), 'email' => Types::string() ], 'resolve' => function ($root, $args) { // email DB::update("UPDATE users SET email = '{$args['email']}' WHERE id = {$args['id']}"); // "" $user = DB::selectOne("SELECT * from users WHERE id = {$args['id']}"); if (is_null($user)) { throw new \Exception(' id'); } return $user; } ] ]; } ]; parent::__construct($config); } }
$variables = isset($input['variables']) ? json_decode($input['variables'], true) : null;
$result = GraphQL::execute($schema, $query, null, null, $variables);
<?php require_once __DIR__ . '/vendor/autoload.php'; use App\DB; use App\Types; use GraphQL\GraphQL; use GraphQL\Schema; try { // $config = [ 'host' => 'localhost', 'database' => 'gql', 'username' => 'root', 'password' => 'root' ]; // DB::init($config); // $rawInput = file_get_contents('php://input'); $input = json_decode($rawInput, true); $query = $input['query']; // $variables = isset($input['variables']) ? json_decode($input['variables'], true) : null; // $schema = new Schema([ 'query' => Types::query(), 'mutation' => Types::mutation() ]); // $result = GraphQL::execute($schema, $query, null, null, $variables); } catch (\Exception $e) { $result = [ 'error' => [ 'message' => $e->getMessage() ] ]; } // header('Content-Type: application/json; charset=UTF-8'); echo json_encode($result);
mutation($userId: Int, $userEmail: String)
changeUserEmail (id: $userId, email: $userEmail)
<?php namespace App\Type; use App\Types; use GraphQL\Type\Definition\InputObjectType; class InputUserType extends InputObjectType { public function __construct() { $config = [ 'description' => ' ', 'fields' => function() { return [ 'name' => [ 'type' => Types::string(), 'description' => ' ' ], 'email' => [ 'type' => Types::string(), 'description' => 'E-mail ' ] ]; } ]; parent::__construct($config); } }
use App\Type\InputUserType; private static $inputUser; public static function inputUser() { return self::$inputUser ?: (self::$inputUser = new InputUserType()); }
'addUser' => [ 'type' => Types::user(), 'description' => ' ', 'args' => [ 'user' => Types::inputUser() ], 'resolve' => function ($root, $args) { // $userId = DB::insert("INSERT INTO users (name, email) VALUES ('{$args['user']['name']}', '{$args['user']['email']}')"); // return DB::selectOne("SELECT * from users WHERE id = $userId"); } ]
Types::inputUser()
) and returns the newly created user of type User ( Types::user()
). public static function nonNull($type) { return Type::nonNull($type); }
'fields' => function() { return [ 'name' => [ 'type' => Types::nonNull(Types::string()), 'description' => ' ' ], 'email' => [ 'type' => Types::nonNull(Types::string()), 'description' => 'E-mail ' ], ]; }
'args' => [ 'id' => Types::nonNull(Types::int()), 'email' => Types::nonNull(Types::string()) ]
<?php namespace App\Type\Scalar; use GraphQL\Type\Definition\ScalarType; class EmailType extends ScalarType { public function serialize($value) { return $value; } public function parseValue($value) { if (!filter_var($value, FILTER_VALIDATE_EMAIL)) { throw new \Exception(' E-mail'); } return $value; } public function parseLiteral($valueNode) { if (!filter_var($valueNode->value, FILTER_VALIDATE_EMAIL)) { throw new \Exception(' E-mail'); } return $valueNode->value; } }
use App\Type\Scalar\EmailType; private static $emailType; public static function email() { return self::$emailType ?: (self::$emailType = new EmailType()); }
Types::string()
) with Email ( Types::email()
). For example, the full code of MutationType.php will now be like this: <?php namespace App\Type; use App\DB; use App\Types; use GraphQL\Type\Definition\ObjectType; class MutationType extends ObjectType { public function __construct() { $config = [ 'fields' => function() { return [ 'changeUserEmail' => [ 'type' => Types::user(), 'description' => ' E-mail ', 'args' => [ 'id' => Types::nonNull(Types::int()), 'email' => Types::nonNull(Types::email()) ], 'resolve' => function ($root, $args) { // email DB::update("UPDATE users SET email = '{$args['email']}' WHERE id = {$args['id']}"); // "" $user = DB::selectOne("SELECT * from users WHERE id = {$args['id']}"); if (is_null($user)) { throw new \Exception(' id'); } return $user; } ], 'addUser' => [ 'type' => Types::user(), 'description' => ' ', 'args' => [ 'user' => Types::inputUser() ], 'resolve' => function ($root, $args) { // $userId = DB::insert("INSERT INTO users (name, email) VALUES ('{$args['user']['name']}', '{$args['user']['email']}')"); // return DB::selectOne("SELECT * from users WHERE id = $userId"); } ] ]; } ]; parent::__construct($config); } }
<?php namespace App\Type; use App\Types; use GraphQL\Type\Definition\InputObjectType; class InputUserType extends InputObjectType { public function __construct() { $config = [ 'description' => ' ', 'fields' => function() { return [ 'name' => [ 'type' => Types::nonNull(Types::string()), 'description' => ' ' ], 'email' => [ 'type' => Types::nonNull(Types::email()), 'description' => 'E-mail ' ], ]; } ]; parent::__construct($config); } }
$userEmail
variable we specify the type of Email, not String. We also add exclamation marks after specifying the type of all required query arguments.userFields
fragment for the User type, we can rewrite our query like this: use GraphQL\Validator\DocumentValidator; use GraphQL\Validator\Rules\QueryComplexity; use GraphQL\Validator\Rules\QueryDepth;
// 6 DocumentValidator::addRule('QueryComplexity', new QueryComplexity(6)); // 1 DocumentValidator::addRule('QueryDepth', new QueryDepth(1));
<?php require_once __DIR__ . '/vendor/autoload.php'; use App\DB; use App\Types; use GraphQL\GraphQL; use GraphQL\Schema; use GraphQL\Validator\DocumentValidator; use GraphQL\Validator\Rules\QueryComplexity; use GraphQL\Validator\Rules\QueryDepth; try { // $config = [ 'host' => 'localhost', 'database' => 'gql', 'username' => 'root', 'password' => 'root' ]; // DB::init($config); // $rawInput = file_get_contents('php://input'); $input = json_decode($rawInput, true); $query = $input['query']; // $variables = isset($input['variables']) ? json_decode($input['variables'], true) : null; // $schema = new Schema([ 'query' => Types::query(), 'mutation' => Types::mutation() ]); // 6 DocumentValidator::addRule('QueryComplexity', new QueryComplexity(6)); // 1 DocumentValidator::addRule('QueryDepth', new QueryDepth(1)); // $result = GraphQL::execute($schema, $query, null, null, $variables); } catch (\Exception $e) { $result = [ 'error' => [ 'message' => $e->getMessage() ] ]; } // header('Content-Type: application/json; charset=UTF-8'); echo json_encode($result);
Source: https://habr.com/ru/post/329238/
All Articles