|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace GraphQLAPI\GraphQLAPI\Hooks; |
|
6
|
|
|
|
|
7
|
|
|
use PoP\Hooks\AbstractHookSet; |
|
8
|
|
|
use GraphQLAPI\GraphQLAPI\Facades\ModuleRegistryFacade; |
|
9
|
|
|
use GraphQLAPI\GraphQLAPI\ModuleResolvers\EndpointFunctionalityModuleResolver; |
|
10
|
|
|
use PoP\GraphQLAPI\DataStructureFormatters\GraphQLDataStructureFormatter; |
|
11
|
|
|
use PoP\API\Response\Schemes as APISchemes; |
|
12
|
|
|
|
|
13
|
|
|
class VarsHooks extends AbstractHookSet |
|
14
|
|
|
{ |
|
15
|
|
|
protected function init() |
|
16
|
|
|
{ |
|
17
|
|
|
// Implement immediately, before VarsHooks in API adds output=json |
|
18
|
|
|
$this->hooksAPI->addAction( |
|
19
|
|
|
'ApplicationState:addVars', |
|
20
|
|
|
array($this, 'maybeRemoveVars'), |
|
21
|
|
|
0, |
|
22
|
|
|
1 |
|
23
|
|
|
); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* If the single endpoint is disabled, or if pointing to a different URL |
|
28
|
|
|
* than the single endpoint (eg: /posts/) and the datastructure param |
|
29
|
|
|
* is not provided it's not "graphql", then: |
|
30
|
|
|
* Do not allow to query the endpoint through URL. |
|
31
|
|
|
* |
|
32
|
|
|
* Examples of not allowed URLs: |
|
33
|
|
|
* - /single-endpoint/?scheme=api&datastructure=graphql <= single endpoint disabled |
|
34
|
|
|
* - /posts/?scheme=api |
|
35
|
|
|
* |
|
36
|
|
|
* @param array<array> $vars_in_array |
|
37
|
|
|
*/ |
|
38
|
|
|
public function maybeRemoveVars(array $vars_in_array): void |
|
39
|
|
|
{ |
|
40
|
|
|
[&$vars] = $vars_in_array; |
|
41
|
|
|
if (isset($vars['scheme']) && $vars['scheme'] == APISchemes::API) { |
|
42
|
|
|
$moduleRegistry = ModuleRegistryFacade::getInstance(); |
|
43
|
|
|
// By setting explicit allowed datastructures, we avoid the empty one |
|
44
|
|
|
// being processed /?scheme=api <= native API |
|
45
|
|
|
// If ever need to support REST or another format, add a hook here |
|
46
|
|
|
$allowedDataStructures = [ |
|
47
|
|
|
GraphQLDataStructureFormatter::getName(), |
|
48
|
|
|
]; |
|
49
|
|
|
if ( |
|
50
|
|
|
// If single endpoint not enabled |
|
51
|
|
|
!$moduleRegistry->isModuleEnabled(EndpointFunctionalityModuleResolver::SINGLE_ENDPOINT) |
|
52
|
|
|
// If datastructure is not GraphQL (or another allowed one) |
|
53
|
|
|
|| !in_array($vars['datastructure'], $allowedDataStructures) |
|
54
|
|
|
) { |
|
55
|
|
|
unset($vars['scheme']); |
|
56
|
|
|
unset($vars['datastructure']); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|