GraphQLController   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 80
rs 10
c 0
b 0
f 0
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getErrorAttribute() 0 3 1
A renderGraphiQL() 0 3 1
A __construct() 0 3 1
A handle() 0 18 2
A responseDataToJson() 0 3 1
A renderPlayground() 0 3 1
1
<?php
2
3
namespace Digia\Lumen\GraphQL\Http;
4
5
use Digia\JsonHelpers\JsonEncoder;
6
use Digia\Lumen\GraphQL\GraphQLService;
7
use Digia\Lumen\GraphQL\Models\GraphQLError;
8
use Illuminate\Http\Request;
9
use Illuminate\View\View;
10
use Laravel\Lumen\Routing\Controller;
11
use Symfony\Component\HttpFoundation\JsonResponse as SymfonyJsonResponse;
12
13
class GraphQLController extends Controller
14
{
15
    public const ATTRIBUTE_ERROR = __CLASS__ . '_error';
16
17
    /**
18
     * @var GraphQLService
19
     */
20
    private $graphqlService;
21
22
    /**
23
     * GraphQLController constructor.
24
     *
25
     * @param GraphQLService $graphqlService
26
     */
27
    public function __construct(GraphQLService $graphqlService)
28
    {
29
        $this->graphqlService = $graphqlService;
30
    }
31
32
    /**
33
     * @param Request $request
34
     *
35
     * @return SymfonyJsonResponse
36
     */
37
    public function handle(Request $request)
38
    {
39
        $processor = $this->graphqlService->getProcessor();
40
41
        $query     = $request->get('query');
42
        $variables = $request->get('variables') ?? [];
43
44
        $responseData = $processor->processPayload($query, $variables)->getResponseData();
45
46
        if (isset($responseData['exceptions'])) {
47
            $request->attributes->set($this->getErrorAttribute(), new GraphQLError(
48
                $query, $variables, $responseData['exceptions']
49
            ));
50
        }
51
52
        $json = $this->responseDataToJson($responseData);
53
54
        return new SymfonyJsonResponse($json, 200, [], true);
55
    }
56
57
    /**
58
     * @return string
59
     */
60
    protected function getErrorAttribute()
61
    {
62
        return config('graphql.error_attribute', self::ATTRIBUTE_ERROR);
63
    }
64
65
    /**
66
     * Renders the GraphiQL interactive query interface.
67
     *
68
     * @return View
69
     */
70
    public function renderGraphiQL()
71
    {
72
        return view('graphql::graphiql');
73
    }
74
75
    /**
76
     * Renders the Playground interactive query interface
77
     *
78
     * @return View
79
     */
80
    public function renderPlayground()
81
    {
82
        return view('graphql::playground');
83
    }
84
85
    /**
86
     * @param array $responseData
87
     *
88
     * @return string
89
     */
90
    protected function responseDataToJson(array $responseData)
91
    {
92
        return JsonEncoder::encode(array_except($responseData, ['exceptions']));
93
    }
94
}
95