Passed
Push — master ( 36097f...93304f )
by Rafael
03:14
created

GraphQLEndpointController   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Test Coverage

Coverage 71.43%

Importance

Changes 0
Metric Value
wmc 13
dl 0
loc 72
ccs 30
cts 42
cp 0.7143
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A addGlobalValidationRules() 0 13 4
C __invoke() 0 44 8
1
<?php
2
3
/*******************************************************************************
4
 *  This file is part of the GraphQL Bundle package.
5
 *
6
 *  (c) YnloUltratech <[email protected]>
7
 *
8
 *  For the full copyright and license information, please view the LICENSE
9
 *  file that was distributed with this source code.
10
 ******************************************************************************/
11
12
namespace Ynlo\GraphQLBundle\Controller;
13
14
use GraphQL\Error\Debug;
15
use GraphQL\GraphQL;
16
use GraphQL\Validator\DocumentValidator;
17
use GraphQL\Validator\Rules;
18
use Psr\Log\LoggerInterface;
19
use Symfony\Component\HttpFoundation\JsonResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Symfony\Component\HttpKernel\Exception\HttpException;
23
use Ynlo\GraphQLBundle\Schema\SchemaCompiler;
24
25
class GraphQLEndpointController
26
{
27
    private $compiler;
28
    private $debug;
29
    private $logger;
30
31 22
    public function __construct(SchemaCompiler $compiler, bool $debug, LoggerInterface $logger = null)
32
    {
33 22
        $this->compiler = $compiler;
34 22
        $this->debug = $debug;
35 22
        $this->logger = $logger;
36 22
    }
37
38 22
    public function __invoke(Request $request): JsonResponse
39
    {
40 22
        if (!$this->debug && $request->getMethod() !== Request::METHOD_POST) {
41
            throw new HttpException(Response::HTTP_BAD_REQUEST, 'The method should be POST to talk with GraphQL API');
42
        }
43
44 22
        $input = json_decode($request->getContent(), true);
45 22
        $query = $input['query'];
46 22
        $context = null;
47 22
        $variableValues = $input['variables'] ?? null;
48 22
        $operationName = $input['operationName'] ?? null;
49
        // this will override global validation rules for this request
50 22
        $validationRules = null;
51
52
        try {
53 22
            $schema = $this->compiler->compile();
54 22
            $schema->assertValid();
55
56 22
            $result = GraphQL::executeQuery($schema, $query, null, $context, $variableValues, $operationName, null, $validationRules);
57
58 22
            $debug = false;
59 22
            if ($this->debug) {
60
                $debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE;
61
            }
62 22
            $output = $result->toArray($debug);
63 22
            $statusCode = Response::HTTP_OK;
64
65 22
            if (isset($output['errors'])) {
66 22
                $statusCode = Response::HTTP_BAD_REQUEST;
67
            }
68
        } catch (\Exception $e) {
69
            if (null !== $this->logger) {
70
                $this->logger->error($e->getMessage(), $e->getTrace());
71
            }
72
            $statusCode = Response::HTTP_INTERNAL_SERVER_ERROR;
73
            $output['errors']['message'] = $e->getMessage();
74
            $output['errors']['category'] = 'internal';
75
76
            if ($this->debug) {
77
                $output['errors']['trace'] = $e->getTraceAsString();
78
            }
79
        }
80
81 22
        return JsonResponse::create($output, $statusCode);
82
    }
83
84 22
    public function addGlobalValidationRules(array $validationRules): void
85
    {
86 22
        $rules = [];
87 22
        if (!empty($validationRules['query_complexity'])) {
88 22
            $rules[] = new Rules\QueryComplexity($validationRules['query_complexity']);
89
        }
90 22
        if (!empty($validationRules['query_depth'])) {
91
            $rules[] = new Rules\QueryDepth($validationRules['query_depth']);
92
        }
93 22
        if (!empty($validationRules['disable_introspection'])) {
94
            $rules[] = new Rules\DisableIntrospection();
95
        }
96 22
        array_map([DocumentValidator::class, 'addRule'], $rules);
97 22
    }
98
}
99