Failed Conditions
Push — master ( 6e7cf2...804daa )
by Vladimir
04:26
created

GraphQL::promiseToExecute()   B

Complexity

Conditions 8
Paths 55

Size

Total Lines 53
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 8

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 53
rs 8.2114
c 0
b 0
f 0
ccs 26
cts 26
cp 1
cc 8
nc 55
nop 9
crap 8

How to fix   Long Method    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
namespace GraphQL;
3
4
use GraphQL\Error\Error;
5
use GraphQL\Executor\ExecutionResult;
6
use GraphQL\Executor\Executor;
7
use GraphQL\Executor\Promise\Adapter\SyncPromiseAdapter;
8
use GraphQL\Executor\Promise\Promise;
9
use GraphQL\Language\AST\DocumentNode;
10
use GraphQL\Language\Parser;
11
use GraphQL\Language\Source;
12
use GraphQL\Executor\Promise\PromiseAdapter;
13
use GraphQL\Type\Definition\Directive;
14
use GraphQL\Type\Definition\Type;
15
use GraphQL\Validator\DocumentValidator;
16
use GraphQL\Validator\Rules\ValidationRule;
17
use GraphQL\Validator\Rules\QueryComplexity;
18
19
/**
20
 * This is the primary facade for fulfilling GraphQL operations.
21
 * See [related documentation](executing-queries.md).
22
 */
23
class GraphQL
24
{
25
    /**
26
     * Executes graphql query.
27
     *
28
     * More sophisticated GraphQL servers, such as those which persist queries,
29
     * may wish to separate the validation and execution phases to a static time
30
     * tooling step, and a server runtime step.
31
     *
32
     * Available options:
33
     *
34
     * schema:
35
     *    The GraphQL type system to use when validating and executing a query.
36
     * source:
37
     *    A GraphQL language formatted string representing the requested operation.
38
     * rootValue:
39
     *    The value provided as the first argument to resolver functions on the top
40
     *    level type (e.g. the query object type).
41
     * context:
42
     *    The value provided as the third argument to all resolvers.
43
     *    Use this to pass current session, user data, etc
44
     * variableValues:
45
     *    A mapping of variable name to runtime value to use for all variables
46
     *    defined in the requestString.
47
     * operationName:
48
     *    The name of the operation to use if requestString contains multiple
49
     *    possible operations. Can be omitted if requestString contains only
50
     *    one operation.
51
     * fieldResolver:
52
     *    A resolver function to use when one is not provided by the schema.
53
     *    If not provided, the default field resolver is used (which looks for a
54
     *    value on the source value with the field's name).
55
     * validationRules:
56
     *    A set of rules for query validation step. Default value is all available rules.
57
     *    Empty array would allow to skip query validation (may be convenient for persisted
58
     *    queries which are validated before persisting and assumed valid during execution)
59
     *
60
     * @api
61
     * @param \GraphQL\Type\Schema $schema
62
     * @param string|DocumentNode $source
63
     * @param mixed $rootValue
64
     * @param mixed $context
65
     * @param array|null $variableValues
66
     * @param string|null $operationName
67
     * @param callable $fieldResolver
68
     * @param array $validationRules
69
     *
70
     * @return ExecutionResult
71
     */
72 74
    public static function executeQuery(
73
        \GraphQL\Type\Schema $schema,
74
        $source,
75
        $rootValue = null,
76
        $context = null,
77
        $variableValues = null,
78
        $operationName = null,
79
        callable $fieldResolver = null,
80
        array $validationRules = null
81
    )
82
    {
83 74
        $promiseAdapter = new SyncPromiseAdapter();
84
85 74
        $promise = self::promiseToExecute($promiseAdapter, $schema, $source, $rootValue, $context,
86 74
            $variableValues, $operationName, $fieldResolver, $validationRules);
87
88 74
        return $promiseAdapter->wait($promise);
89
    }
90
91
    /**
92
     * Same as executeQuery(), but requires PromiseAdapter and always returns a Promise.
93
     * Useful for Async PHP platforms.
94
     *
95
     * @api
96
     * @param PromiseAdapter $promiseAdapter
97
     * @param \GraphQL\Type\Schema $schema
98
     * @param string|DocumentNode $source
99
     * @param mixed $rootValue
100
     * @param mixed $context
101
     * @param array|null $variableValues
102
     * @param string|null $operationName
103
     * @param callable $fieldResolver
104
     * @param array $validationRules
105
     *
106
     * @return Promise
107
     */
108 97
    public static function promiseToExecute(
109
        PromiseAdapter $promiseAdapter,
110
        \GraphQL\Type\Schema $schema,
111
        $source,
112
        $rootValue = null,
113
        $context = null,
114
        $variableValues = null,
115
        $operationName = null,
116
        callable $fieldResolver = null,
117
        array $validationRules = null
118
    )
119
    {
120
        try {
121 97
            if ($source instanceof DocumentNode) {
122 21
                $documentNode = $source;
123
            } else {
124 76
                $documentNode = Parser::parse(new Source($source ?: '', 'GraphQL'));
125
            }
126
127
            // FIXME
128 96
            if (!empty($validationRules)) {
129 3
                foreach ($validationRules as $rule) {
130 3
                    if ($rule instanceof QueryComplexity) {
131 3
                        $rule->setRawVariableValues($variableValues);
132
                    }
133
                }
134
            } else {
135
                /** @var QueryComplexity $queryComplexity */
136 95
                $queryComplexity = DocumentValidator::getRule(QueryComplexity::class);
137 95
                $queryComplexity->setRawVariableValues($variableValues);
138
            }
139
140 96
            $validationErrors = DocumentValidator::validate($schema, $documentNode, $validationRules);
141
142 96
            if (!empty($validationErrors)) {
143 14
                return $promiseAdapter->createFulfilled(
144 14
                    new ExecutionResult(null, $validationErrors)
145
                );
146
            } else {
147 86
                return Executor::promiseToExecute(
148 86
                    $promiseAdapter,
149 86
                    $schema,
150 86
                    $documentNode,
151 86
                    $rootValue,
152 86
                    $context,
153 86
                    $variableValues,
154 86
                    $operationName,
155 86
                    $fieldResolver
156
                );
157
            }
158 1
        } catch (Error $e) {
159 1
            return $promiseAdapter->createFulfilled(
160 1
                new ExecutionResult(null, [$e])
161
            );
162
        }
163
    }
164
165
    /**
166
     * @deprecated Use executeQuery()->toArray() instead
167
     *
168
     * @param \GraphQL\Type\Schema $schema
169
     * @param string|DocumentNode $source
170
     * @param mixed $rootValue
171
     * @param mixed $contextValue
172
     * @param array|null $variableValues
173
     * @param string|null $operationName
174
     * @return Promise|array
175
     */
176
    public static function execute(
177
        \GraphQL\Type\Schema $schema,
178
        $source,
179
        $rootValue = null,
180
        $contextValue = null,
181
        $variableValues = null,
182
        $operationName = null
183
    )
184
    {
185
        trigger_error(
186
            __METHOD__ . ' is deprecated, use GraphQL::executeQuery()->toArray() as a quick replacement',
187
            E_USER_DEPRECATED
188
        );
189
        $result = self::promiseToExecute(
190
            $promiseAdapter = Executor::getPromiseAdapter(),
191
            $schema,
192
            $source,
193
            $rootValue,
194
            $contextValue,
195
            $variableValues,
196
            $operationName
197
        );
198
199
        if ($promiseAdapter instanceof SyncPromiseAdapter) {
200
            $result = $promiseAdapter->wait($result)->toArray();
201
        } else {
202
            $result = $result->then(function(ExecutionResult $r) {
203
                return $r->toArray();
204
            });
205
        }
206
        return $result;
207
    }
208
209
    /**
210
     * @deprecated renamed to executeQuery()
211
     *
212
     * @param \GraphQL\Type\Schema $schema
213
     * @param string|DocumentNode $source
214
     * @param mixed $rootValue
215
     * @param mixed $contextValue
216
     * @param array|null $variableValues
217
     * @param string|null $operationName
218
     *
219
     * @return ExecutionResult|Promise
220
     */
221
    public static function executeAndReturnResult(
222
        \GraphQL\Type\Schema $schema,
223
        $source,
224
        $rootValue = null,
225
        $contextValue = null,
226
        $variableValues = null,
227
        $operationName = null
228
    )
229
    {
230
        trigger_error(
231
            __METHOD__ . ' is deprecated, use GraphQL::executeQuery() as a quick replacement',
232
            E_USER_DEPRECATED
233
        );
234
        $result = self::promiseToExecute(
235
            $promiseAdapter = Executor::getPromiseAdapter(),
236
            $schema,
237
            $source,
238
            $rootValue,
239
            $contextValue,
240
            $variableValues,
241
            $operationName
242
        );
243
        if ($promiseAdapter instanceof SyncPromiseAdapter) {
244
            $result = $promiseAdapter->wait($result);
245
        }
246
        return $result;
247
    }
248
249
    /**
250
     * Returns directives defined in GraphQL spec
251
     *
252
     * @api
253
     * @return Directive[]
254
     */
255 339
    public static function getStandardDirectives()
256
    {
257 339
        return array_values(Directive::getInternalDirectives());
258
    }
259
260
    /**
261
     * Returns types defined in GraphQL spec
262
     *
263
     * @api
264
     * @return Type[]
265
     */
266
    public static function getStandardTypes()
267
    {
268
        return array_values(Type::getInternalTypes());
269
    }
270
271
    /**
272
     * Returns standard validation rules implementing GraphQL spec
273
     *
274
     * @api
275
     * @return ValidationRule[]
276
     */
277
    public static function getStandardValidationRules()
278
    {
279
        return array_values(DocumentValidator::defaultRules());
280
    }
281
282
    /**
283
     * @param callable $fn
284
     */
285
    public static function setDefaultFieldResolver(callable $fn)
286
    {
287
        Executor::setDefaultFieldResolver($fn);
288
    }
289
290
    /**
291
     * @param PromiseAdapter|null $promiseAdapter
292
     */
293
    public static function setPromiseAdapter(PromiseAdapter $promiseAdapter = null)
294
    {
295
        Executor::setPromiseAdapter($promiseAdapter);
296
    }
297
298
    /**
299
     * Returns directives defined in GraphQL spec
300
     *
301
     * @deprecated Renamed to getStandardDirectives
302
     * @return Directive[]
303
     */
304
    public static function getInternalDirectives()
305
    {
306
        return self::getStandardDirectives();
307
    }
308
}
309