PHP code example of pomelchenko / yii2-graphql

1. Go to this page and download the library: Download pomelchenko/yii2-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/ */

    

pomelchenko / yii2-graphql example snippets


'schema' => [
    'query' => [
        'me' => [
            'type' => GraphQL::type(UserType::class),
            'args' => [
                'id' => ['type' => Type::id()],
            ],
            'resolve' => [UserResolver::class, 'resolveMe'],
        ],
    ],
],

//...
'id' => [
    'type' => Type::id(),
],
//...

//...
'id' => Type::id(),
//...

'components' => [
    'request' => [
        'parsers' => [
            'application/json' => \yii\web\JsonParser::class,
        ],
    ],
];

class MyModule extends \yii\graphql\GraphQLModule
{
}

'modules'=>[
    'moduleName ' => [
        'class' => 'path\to\module'
        //graphql config
        'schema' => [
            'query' => [
                'user' => \app\graphql\query\UsersQuery::class
            ],
            'mutation' => [
                'login'
            ],
            // you do not need to set the types if your query contains interfaces or fragments
            // the key must same as your defined class
            'types' => [
                'Story' => \yiiunit\extensions\graphql\objects\types\StoryType::class
            ],
        ],
    ],
];

class MyController extends Controller
{
    function actions()
    {
        return [
            'index' => [
                'class' => \yii\graphql\GraphQLAction::class,
            ],
        ];
    }
}

'components' => [
    'componentsName' => [
        'class' => 'path\to\components'
        //graphql config
        'schema' => [
            'query' => [
                'user' => \app\graphql\query\UsersQuery::class
            ],
            'mutation' => [
                'login'
            ],
            // you do not need to set the types if your query contains interfaces or fragments
            // the key must same as your defined class
            'types'=>[
                'Story' => \yiiunit\extensions\graphql\objects\types\StoryType::class,
            ],
        ],
    ],
];

public function rules() 
{
    return [
        ['password', 'boolean'],
    ];
}

use yii\graphql\base\GraphQLMutation;
use GraphQL\Type\Definition\Type;

class UpdatePasswordMutation extends GraphQLMutation
{
    public function type()
    {
        return Type::boolean();
    }

    public function args()
    {
        return [
            'password' => ['type' => Type::nonNull(Type::string())],
        ];
    }

    public function rules()
    {
        return [
            ['password', 'string', 'min' => 12],
        ];
    }

    public function resolve($root, $args)
    {
        // Arguments are already validated here.
        // ...
        return true;
    }
}

function behaviors() 
{
    return [
        'authenticator' => [
            'class' => \yii\graphql\filter\auth\CompositeAuth::class,
            'authMethods' => [
                \yii\filters\auth\QueryParamAuth::class,
            ],
            'except' => ['hello'],
        ],
    ];
}

class GraphqlController extends Controller
{
    public function actions() 
    {
        return [
            'index' => [
                'class' => \yii\graphql\GraphQLAction::class,
                'checkAccess'=> [$this,'checkAccess'],
            ]
        ];
    }

    /**
     * authorization
     * @param $actionName
     * @throws \yii\web\ForbiddenHttpException
     */
     public function checkAccess($actionName)
     {
         $permissionName = $this->module->id . '/' . $actionName;
         $pass = Yii::$app->getAuthManager()->checkAccess(Yii::$app->user->id, $permissionName);
         if (!$pass) {
             throw new \yii\web\ForbiddenHttpException('Access Denied');
         }
    }
}

'index' => [
    'class' => \yii\graphql\GraphQLAction::class,
    'checkAccess' => [$this, 'checkAccess'],
    '

class UserQuery extends GraphQLQuery
{
    public function type()
    {
        return GraphQL::type(UserType::class);
    }

    public function args()
    {
        return [
            'id'=>[
                'type' => Type::nonNull(Type::id())
            ],
        ];
    }

    public function resolve($value, $args, $context, ResolveInfo $info)
    {
        return DataSource::findUser($args['id']);
    }
}

class UserType extends GraphQLType
{
    protected $attributes = [
        'name'=>'user',
        'description'=>'user is user'
    ];

    public function fields()
    {
        $result = [
            'id' => [
                'type'=>Type::id()
            ],
            'email' => Types::email(),
            'email2' => Types::email(),
            'photo' => [
                'type' => GraphQL::type(ImageType::class),
                'description' => 'User photo URL',
                'args' => [
                    'size' => Type::nonNull(GraphQL::type(ImageSizeEnumType::class)),
                ]
            ],
            'firstName' => [
                'type' => Type::string(),
            ],
            'lastName' => [
                'type' => Type::string(),
            ],
            'lastStoryPosted' => GraphQL::type(StoryType::class),
            'fieldWithError' => [
                'type' => Type::string(),
                'resolve' => function() {
                    throw new \Exception("This is error field");
                }
            ]
        ];
        return $result;
    }

    public function resolvePhotoField(User $user,$args)
    {
        return DataSource::getUserPhoto($user->id, $args['size']);
    }

    public function resolveIdField(User $user, $args)
    {
        return $user->id.'test';
    }

    public function resolveEmail2Field(User $user, $args)
    {
        return $user->email2.'test';
    }
}

'hello' => '
    query hello {
        hello
    }
',
'singleObject' => '
    query user {
        user(id:"2") {
            id
            email
            email2
            photo(size:ICON) {
                id
                url
            }
            firstName
            lastName
        }
    }
',
'multiObject' => '
    query multiObject {
        user(id: "2") {
            id
            email
            photo(size:ICON) {
                id
                url
            }
        }
        stories(after: "1") {
            id
            author{
                id
            }
            body
        }
    }
',
'updateObject' => '
    mutation updateUserPwd{
        updateUserPwd(id: "1001", password: "123456") {
            id,
            username
        }
    }
'

'modules' => [
    'moduleName' => [
       'class' => 'path\to\module'
       'errorFormatter' => [\yii\graphql\ErrorFormatter::class, 'formatError'],
    ],
];