1
|
|
|
<?php |
2
|
|
|
/******************************************************************************* |
3
|
|
|
* This file is part of the GraphQL Bundle package. |
4
|
|
|
* |
5
|
|
|
* (c) YnloUltratech <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
******************************************************************************/ |
10
|
|
|
|
11
|
|
|
namespace Ynlo\GraphQLBundle\EventListener\GraphQL; |
12
|
|
|
|
13
|
|
|
use GraphQL\Error\Error; |
14
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
15
|
|
|
use Ynlo\GraphQLBundle\Events\GraphQLEvents; |
16
|
|
|
use Ynlo\GraphQLBundle\Events\GraphQLFieldEvent; |
17
|
|
|
|
18
|
|
|
class FieldConcurrentUsageListener implements EventSubscriberInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var int[] |
22
|
|
|
*/ |
23
|
|
|
private static $concurrentUsages = []; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @inheritDoc |
27
|
|
|
*/ |
28
|
1 |
|
public static function getSubscribedEvents() |
29
|
|
|
{ |
30
|
|
|
return [ |
31
|
1 |
|
GraphQLEvents::PRE_READ_FIELD => 'preReadField', |
32
|
|
|
]; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param GraphQLFieldEvent $event |
37
|
|
|
*/ |
38
|
2 |
|
public function preReadField(GraphQLFieldEvent $event) |
39
|
|
|
{ |
40
|
2 |
|
$definition = $event->getInfo()->getField(); |
41
|
2 |
|
if ($maxConcurrentUsage = $definition->getMaxConcurrentUsage()) { |
42
|
2 |
|
$oid = spl_object_hash($definition); |
43
|
2 |
|
$queryId = $event->getContext()->getQueryContext()->getQueryId(); |
44
|
2 |
|
$usages = static::$concurrentUsages[$queryId][$oid] ?? 1; |
|
|
|
|
45
|
2 |
|
if ($usages > $maxConcurrentUsage) { |
46
|
2 |
|
if (1 === $maxConcurrentUsage) { |
47
|
1 |
|
$error = sprintf( |
48
|
1 |
|
'The field "%s" can be fetched only once per query. This field can`t be used in a list.', |
49
|
1 |
|
$definition->getName() |
50
|
|
|
); |
51
|
|
|
} else { |
52
|
1 |
|
$error = sprintf( |
53
|
1 |
|
'The field "%s" can`t be fetched more than %s times per query.', |
54
|
1 |
|
$definition->getName(), |
55
|
1 |
|
$maxConcurrentUsage |
56
|
|
|
); |
57
|
|
|
} |
58
|
2 |
|
throw new Error($error); |
59
|
|
|
} |
60
|
2 |
|
static::$concurrentUsages[$queryId][$oid] = $usages + 1; |
61
|
|
|
} |
62
|
2 |
|
} |
63
|
|
|
} |
64
|
|
|
|