PHP code example of maxxxam / graphql-yii
1. Go to this page and download the library: Download maxxxam/graphql-yii 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/ */
maxxxam / graphql-yii example snippets
'graphql' => [
'graphql' =>
$appNamespace = 'app\modules\graphql';
$graphqlDir = dirname(dirname(__DIR__)) . '/modules/graphql';
return [
'class' => 'GraphQLYii\GraphQL',
'namespace' => $appNamespace,
'graphqlDir' => $graphqlDir,
'types' => [
'UserType' => $appNamespace . '\types\UserType',
'AccessType' => $appNamespace . '\types\AccessType',
'ImageType' => $appNamespace . '\types\ImageType',
'EventType' => $appNamespace . '\types\EventType',
'TrophyType' => $appNamespace . '\types\TrophyType',
'TeamType' => $appNamespace . '\types\TeamType',
'AlbumType' => $appNamespace . '\types\AlbumType',
'FriendType' => $appNamespace . '\types\FriendType',
'SportType' => $appNamespace . '\types\SportType',
],
'queries' => [
'UsersQuery' => $appNamespace . '\query\user\UsersQuery',
'UserQuery' => $appNamespace . '\query\user\UserQuery'
],
'mutations' => [
'AddFriendMutation' => $appNamespace . '\mutation\user\AddFriendMutation',
'RemoveFriendMutation' => $appNamespace . '\mutation\user\RemoveFriendMutation',
'SignupMutation' => $appNamespace . '\mutation\user\SignupMutation',
],
'typesPath' => '/types',
'queriesPath' => '/queries',
'mutationsPath' => '/mutations',
'subscriptionPath' => '/subscription',
];
public function actionIndex(){
Yii::$app->response->format = Response::FORMAT_JSON;
$data = Yii::$app->request->post();
$query = isset($data['query']) ? str_replace(["\r","\n"], "", $data['query']) : null;
$params = isset($data['variables']) ? str_replace(["\r","\n"], "", $data['variables']) : null;
/** @var GraphQL $GraphQL */
$GraphQL = \Yii::$app->get('graphql');
$result = $GraphQL->query($query, $params);
if (!empty($result['errors'])){
Yii::$app->response->setStatusCode(400);
}
Yii::$app->response->headers->add('Content-Length', strlen(json_encode($result)));
Yii::$app->response->headers->add('Content-Type', 'application/json');
$stream = fopen('php://memory','wb');
fwrite($stream, json_encode($result));
rewind($stream);
Yii::$app->response->stream = $stream;
Yii::$app->response->send();
return true;
}
public function behaviors()
{
Yii::$app->controller->enableCsrfValidation = false;
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'class' => CompositeAuth::className(),
'authMethods' => [
['class' => HttpBearerAuth::className()],
['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],
]
],
'exceptionFilter' => [
'class' => ErrorToExceptionFilter::className()
],
]);
}