Skip to content

Commit 4ccbfcf

Browse files
committed
Generator for schema class added
Dependencies updated Controller has been updated for the Symfony v3 Additional checks were implemented GraphQL Schema class was moved to the config file as parameter and is now being used inside the controller
1 parent 62ae4b4 commit 4ccbfcf

File tree

6 files changed

+168
-31
lines changed

6 files changed

+168
-31
lines changed

Command/GenerateSchemaCommand.php

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
<?php
2+
3+
namespace AppBundle\Command;
4+
5+
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
6+
use Symfony\Component\Console\Input\InputArgument;
7+
use Symfony\Component\Console\Input\InputInterface;
8+
use Symfony\Component\Console\Input\InputOption;
9+
use Symfony\Component\Console\Output\OutputInterface;
10+
use Symfony\Component\Console\Question\ConfirmationQuestion;
11+
12+
class GenerateSchemaCommand extends ContainerAwareCommand
13+
{
14+
protected function configure()
15+
{
16+
$this
17+
->setName('graphql:generate-schema')
18+
->setDescription('Generates GraphQL Schema class')
19+
->addArgument('bundle', InputArgument::REQUIRED, 'Bundle to generate class to');
20+
}
21+
22+
protected function execute(InputInterface $input, OutputInterface $output)
23+
{
24+
$bundleName = $input->getArgument('bundle');
25+
if (strpos($bundleName, -6) != 'Bundle') $bundleName .= 'Bundle';
26+
27+
$srcPath = realpath($this->getContainer()->getParameter('kernel.root_dir') . '/../src');
28+
$activeBundles = $this->getContainer()->getParameter('kernel.bundles');
29+
if (!array_key_exists($bundleName, $activeBundles)) {
30+
$output->writeln('There is no active bundleName: ' . $bundleName);
31+
}
32+
33+
$graphqlPath = $srcPath . '/' . $bundleName . '/GraphQL';
34+
$className = 'Schema';
35+
$classPath = $graphqlPath . '/' . $className . '.php';
36+
37+
$inputHelper = $this->getHelper('question');
38+
$question = new ConfirmationQuestion(sprintf('Confirm creating class at %s ?', $classPath), false);
39+
if (!$inputHelper->ask($input, $output, $question)) {
40+
return;
41+
}
42+
43+
if (!is_dir($graphqlPath)) {
44+
mkdir($graphqlPath, 0777, true);
45+
}
46+
file_put_contents($classPath, $this->getSchemaClassTemplate($bundleName, $className));
47+
48+
$output->writeln('Schema file has been created at');
49+
$output->writeln($classPath . "\n");
50+
$output->writeln('Update your app/config/config.yml with the parameter:');
51+
$output->writeln('graph_ql:');
52+
$output->writeln(sprintf(' schema_class: %s\GraphQL\%s', $bundleName, $className));
53+
}
54+
55+
protected function getSchemaClassTemplate($bundleName, $className = 'Schema')
56+
{
57+
$tpl = <<<TEXT
58+
<?php
59+
/**
60+
* This class was automatically generated by GraphQL Schema generator
61+
*/
62+
63+
namespace $bundleName\GraphQL;
64+
65+
use Youshido\GraphQL\AbstractSchema;
66+
use Youshido\GraphQL\Type\Config\Schema\SchemaConfig;
67+
use Youshido\GraphQL\Type\Scalar\StringType;
68+
69+
class $className extends AbstractSchema
70+
{
71+
public function build(SchemaConfig \$config)
72+
{
73+
\$config->getQuery()->addFields([
74+
'hello' => [
75+
'type' => new StringType(),
76+
'resolve' => function () {
77+
return 'world!';
78+
}
79+
]
80+
]);
81+
}
82+
83+
}
84+
85+
TEXT;
86+
87+
return $tpl;
88+
}
89+
90+
}

Controller/GraphQLController.php

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,27 +10,27 @@
1010

1111
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
1212
use Symfony\Component\HttpFoundation\JsonResponse;
13-
use Symfony\Component\HttpFoundation\Request;
1413
use Symfony\Component\Routing\Annotation\Route;
14+
use Youshido\GraphQL\Validator\Exception\ConfigurationException;
1515

1616
class GraphQLController extends Controller
1717
{
1818

1919
/**
20-
* @param Request $request
20+
* @Route("/graphql")
2121
*
22+
* @throws ConfigurationException
2223
* @return JsonResponse
23-
*
24-
* @Route("/graphql")
2524
*/
26-
public function apiAction(Request $request)
25+
public function defaultAction()
2726
{
27+
$request = $this->get('request_stack')->getCurrentRequest();
2828
$query = $request->get('query', null);
2929
$variables = $request->get('variables', null);
3030

3131
$variables = json_decode($variables, true) ?: [];
3232

33-
$content = $this->get("request")->getContent();
33+
$content = $request->getContent();
3434
if (!empty($content)) {
3535
$params = json_decode($content, true);
3636

@@ -41,8 +41,13 @@ public function apiAction(Request $request)
4141
}
4242

4343
$processor = $this->get('youshido.graphql.processor');
44-
45-
$processor->processQuery($query, $variables);
44+
if ($schemaClass = $this->getParameter('youshido.graphql.schema_class')) {
45+
if (!class_exists($schemaClass)) {
46+
throw new ConfigurationException('Schema class ' . $schemaClass . ' does not exist');
47+
}
48+
$processor->setSchema(new $schemaClass());
49+
}
50+
$processor->processRequest($query, $variables);
4651

4752
return new JsonResponse($processor->getResponseData(), 200, $this->getParameter('youshido.graphql.response_headers'));
4853
}

DependencyInjection/GraphQLExtension.php

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,26 +14,39 @@
1414
*/
1515
class GraphQLExtension extends Extension
1616
{
17+
private $config = [];
18+
1719
/**
1820
* {@inheritdoc}
1921
*/
2022
public function load(array $configs, ContainerBuilder $container)
2123
{
2224
$configuration = new Configuration();
23-
$config = $this->processConfiguration($configuration, $configs);
25+
$this->config = $this->processConfiguration($configuration, $configs);
2426

2527
$responseHeaders = [];
26-
if (isset($config['response_headers']) && is_array($config['response_headers'])) {
27-
foreach ($config['response_headers'] as $responseHeader) {
28-
$responseHeaders[$responseHeader['name']] = $responseHeader['value'];
29-
}
28+
foreach ($this->getConfig('response_headers', $this->getDefaultHeaders()) as $responseHeader) {
29+
$responseHeaders[$responseHeader['name']] = $responseHeader['value'];
3030
}
3131

32-
$container->setParameter('youshido.graphql.project_schema', $config['query_schema']);
32+
$container->setParameter('youshido.graphql.project_schema', $this->getConfig('query_schema', null));
3333
$container->setParameter('youshido.graphql.response_headers', $responseHeaders);
34-
$container->setParameter('youshido.graphql.logger', isset($config['logger']) ? $config['logger'] : null);
34+
$container->setParameter('youshido.graphql.logger', $this->getConfig('logger', null));
3535

3636
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
3737
$loader->load('services.yml');
3838
}
39+
40+
private function getDefaultHeaders()
41+
{
42+
return [
43+
['name' => 'Access-Control-Allow-Origin', 'value' => '*'],
44+
];
45+
}
46+
47+
private function getConfig($key, $default = null)
48+
{
49+
return array_key_exists($key, $this->config) ? $this->config[$key] : $default;
50+
}
51+
3952
}

Processor/Processor.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,13 @@ public function setContainer(ContainerInterface $container = null)
3030
$this->container = $container;
3131
}
3232

33-
public function processQuery($queryString, $variables = [])
33+
public function processRequest($queryString, $variables = [])
3434
{
3535
if ($this->logger) {
3636
$this->logger->debug(sprintf('GraphQL query: %s', $queryString), (array) $variables);
3737
}
3838

39-
parent::processQuery($queryString, $variables);
39+
parent::processRequest($queryString, $variables);
4040
}
4141

4242
/**

README.md

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,58 @@ This bundle provides you with:
1414
## Installing GraphQL Bundle
1515

1616
We assume you have `composer`, but if you're not – install it from the [official website](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx).
17-
After you've done with that, simply run
18-
```
19-
$> composer require youshido/graphql-bundle
17+
Once you have your composer up and running – you're ready to install the GraphQL Bundle
18+
```sh
19+
composer require youshido/graphql-bundle
2020
```
2121

22-
Than add bundle to your `app/AppKernel.php`
23-
```
24-
...
22+
Than enable bundle in your `app/AppKernel.php`
23+
```php
2524
new Youshido\GraphQLBundle\GraphQLBundle(),
26-
...
2725
```
2826

29-
And finally add the routing reference to the `app/config/routing.yml`:
30-
```
27+
Add the routing reference to the `app/config/routing.yml`:
28+
```yaml
3129
graphql:
3230
resource: "@GraphQLBundle/Controller/"
3331
```
3432
33+
Let's check if you've done everything right so far – try to access the `localhost:8000/graphql` url.
34+
You should get a JSON response with the following error:
35+
```js
36+
{"errors":[{"message":"You have to set GraphQL Schema to process"}]}
37+
```
38+
39+
That's because there was no GraphQL Schema specified for the processor yet.
40+
You need to create a GraphQL Schema class and set it inside your `app/config/config.yml` file.
41+
42+
> THere is a way where you can use inline approach, in order to do that you have to define your own GraphQL controller and use a `->setSchema` method of the processor to set the Schema
43+
44+
The fastest way to create a Schema class is to use a generator shipped with this bundle:
45+
```sh
46+
php bin/console graphql:schema:generate App
47+
```
48+
Here *App* is a name of the bundle where the class will be generated in.
49+
You will be requested for a confirmation to create a class and then presented with instructions to update your config file.
50+
51+
```sh
52+
Update your app/config/config.yml with the parameter:
53+
graph_ql:
54+
schema_class: AppBundle\GraphQL\Schema
55+
```
56+
57+
After you've added parameters to config file, try to access the following link in the browser – 'http://localhost:8000/graphql?query={hello}'
58+
59+
> Alternatively, you can execute the same request using CURL client in your console
60+
> `curl http://localhost:8000/graphql --data "query={ hello }"`
61+
62+
Successful response from a test Schema will be displayed:
63+
```js
64+
{"data":{"hello":"world!"}}
65+
```
66+
67+
That means you have GraphQL Bundle for the Symfony Framework configured and now can architect your GraphQL Schema:
68+
3569
## Documentation
3670

3771
Detailed documentation is available on the main GraphQL repository – http://github.com/youshido/graphql/.

Resources/config/services.yml

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
parameters:
22
youshido.graphql.processor.class: Youshido\GraphQLBundle\Processor\Processor
3-
youshido.graphql.validator.class: Youshido\GraphQL\Validator\ResolveValidator\ResolveValidator
43

54
services:
65

76
youshido.graphql.processor:
87
class: %youshido.graphql.processor.class%
9-
arguments: [ @youshido.graphql.validator ]
108
calls:
119
- [ setSchema, [@youshido.graphql.schema]]
1210
- [ setContainer, [@service_container]]
@@ -15,6 +13,3 @@ services:
1513

1614
youshido.graphql.schema:
1715
class: %youshido.graphql.project_schema%
18-
19-
youshido.graphql.validator:
20-
class: %youshido.graphql.validator.class%

0 commit comments

Comments
 (0)