Passed
Push — master ( 83c19a...dccfc6 )
by David
04:13
created

GraphQLMiddleware::fromGet()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 8.8571
cc 5
eloc 6
nc 16
nop 1
1
<?php
2
namespace TheCodingMachine\GraphQL\Controllers;
3
4
use GraphQL\GraphQL;
5
use Mouf\GraphQL\Schema;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, TheCodingMachine\GraphQL\Controllers\Schema.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Youshido\GraphQL\Execution\Processor;
9
use Zend\Diactoros\Response\JsonResponse;
10
11
class GraphQLMiddleware implements \Interop\Http\ServerMiddleware\MiddlewareInterface
12
{
13
    /**
14
     * @var string The graphql uri path to match against
15
     */
16
    private $graphqlUri;
17
18
    /**
19
     * @var array The graphql headers
20
     */
21
    private $graphql_headers = [
22
        "application/graphql"
23
    ];
24
25
    /**
26
     * @var array Allowed method for a graphql request, default GET, POST
27
     */
28
    private $allowed_methods = [
29
        "GET", "POST"
30
    ];
31
32
    /**
33
     * @var Processor
34
     */
35
    private $schema;
36
    /**
37
     * @var null
38
     */
39
    private $rootUrl;
0 ignored issues
show
Unused Code introduced by
The property $rootUrl is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
40
41
    /**
42
     * GraphQLMiddleware constructor.
43
     *
44
     * @param Schema    $schema
45
     * @param string    $graphqlUri
46
     */
47
    public function __construct(Schema $schema, $graphqlUri = '/graphql', $rootUrl = null)
48
    {
49
        $this->schema = $schema;
0 ignored issues
show
Documentation Bug introduced by
It seems like $schema of type object<Mouf\GraphQL\Schema> is incompatible with the declared type object<Youshido\GraphQL\Execution\Processor> of property $schema.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
50
        $this->graphqlUri = rtrim($rootUrl, '/').'/'. ltrim($graphqlUri, '/');
51
    }
52
53
    /**
54
     * Process an incoming server request and return a response, optionally delegating
55
     * to the next middleware component to create the response.
56
     *
57
     * @param \Psr\Http\Message\ServerRequestInterface $request
58
     * @param \Interop\Http\ServerMiddleware\DelegateInterface $delegate
59
     *
60
     * @return \Psr\Http\Message\ResponseInterface
61
     */
62
    public function process(\Psr\Http\Message\ServerRequestInterface $request, \Interop\Http\ServerMiddleware\DelegateInterface $delegate)
63
    {
64
        if (!$this->isGraphQLRequest($request)) {
65
            return $delegate->process($request);
66
        }
67
68
        if (!in_array($request->getMethod(), $this->allowed_methods, true)){
69
            return new JsonResponse([
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Zend\Diactor...llowed_methods)), 405); (Zend\Diactoros\Response\JsonResponse) is incompatible with the return type declared by the interface Interop\Http\ServerMiddl...ewareInterface::process of type Psr\Http\Message\ResponseInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
70
                "Method not allowed. Allowed methods are " . implode(", ", $this->allowed_methods)
71
            ], 405);
72
        }
73
74
        list($query, $variables) = $this->getPayload($request);
75
76
77
        $processor = new Processor($this->schema->toGraphQLSchema());
0 ignored issues
show
Bug introduced by
The method toGraphQLSchema() does not seem to exist on object<Youshido\GraphQL\Execution\Processor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
78
        $processor->processPayload($query, $variables);
79
        $res = $processor->getResponseData();
80
        return new JsonResponse($res);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Zend\Diactor...nse\JsonResponse($res); (Zend\Diactoros\Response\JsonResponse) is incompatible with the return type declared by the interface Interop\Http\ServerMiddl...ewareInterface::process of type Psr\Http\Message\ResponseInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
81
82
        /*$res = GraphQL::execute($this->schema->toGraphQLSchema(), $query, null, null, $variables, null);
0 ignored issues
show
Unused Code Comprehensibility introduced by
61% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
83
84
        return new JsonResponse($res);*/
85
    }
86
87
    private function isGraphQLRequest(ServerRequestInterface $request)
88
    {
89
        return $this->hasUri($request) || $this->hasGraphQLHeader($request);
90
    }
91
92
    private function hasUri(ServerRequestInterface $request)
93
    {
94
        return  $this->graphqlUri === $request->getUri()->getPath();
95
    }
96
97
    private function hasGraphQLHeader(ServerRequestInterface $request)
98
    {
99
        if (!$request->hasHeader('content-type')) {
100
            return false;
101
        }
102
103
        $request_headers = array_map(function($header){
104
            return trim($header);
105
        }, explode(",", $request->getHeaderLine("content-type")));
106
107
        foreach ($this->graphql_headers as $allowed_header) {
108
            if (in_array($allowed_header, $request_headers)){
109
                return true;
110
            }
111
        }
112
113
        return  false;
114
    }
115
116
    private function getPayload(ServerRequestInterface $request)
117
    {
118
        $method = $request->getMethod();
119
120
        switch ($method) {
121
            case "GET":
122
                return $this->fromGet($request);
123
            case "POST":
124
                return $this->fromPost($request);
125
            default:
126
                throw new \RuntimeException('Unexpected request type. Only support GET and POST.');
127
128
        }
129
    }
130
131
    private function fromGet(ServerRequestInterface $request)
132
    {
133
        $params = $request->getQueryParams();
134
135
        $query = isset($params['query']) ? $params['query'] : null;
136
        $variables = isset($params['variables']) ? $params['variables'] : [];
137
138
        $variables = is_string($variables) ? json_decode($variables, true) ?: [] : [];
139
140
        return [$query, $variables];
141
142
    }
143
144
    private function fromPost(ServerRequestInterface $request)
145
    {
146
        $content = $request->getBody()->getContents();
147
148
        if (empty($content)) {
149
            $params = $request->getParsedBody();
150
        } else {
151
            $params = json_decode($content, true);
152
        }
153
154
        $query = $variables = null;
155
156
        if (!empty($params)) {
157
            if ($this->hasGraphQLHeader($request)) {
158
                $query = $content;
159
            } else {
160
                if ($params) {
161
                    $query = isset($params['query']) ? $params['query'] : $query;
162
                    if (isset($params['variables'])) {
163
                        if (is_string($params['variables'])) {
164
                            $variables = json_decode($params['variables'], true) ?: $variables;
165
                        } else {
166
                            $variables = $params['variables'];
167
                        }
168
                        $variables = is_array($variables) ? $variables : [];
169
                    }
170
                }
171
            }
172
        }
173
        return [$query, $variables];
174
175
    }
176
}