Completed
Pull Request — 8.x-3.x (#519)
by Sebastian
02:15
created

MaxComplexityQueryVisitor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql\GraphQL\Execution\QueryVisitor;
4
5
use Youshido\GraphQL\Exception\ResolveException;
6
use Youshido\GraphQL\Field\FieldInterface;
7
8
class MaxComplexityQueryVisitor implements QueryVisitorInterface {
9
10
  /**
11
   * The allowed maximum complexity;
12
   *
13
   * @var int
14
   */
15
  protected $maxComplexity;
16
17
  /**
18
   * MaxComplexityQueryVisitor constructor.
19
   *
20
   * @param int $maxComplexity
21
   *   The allowed maximum complexity.
22
   */
23
  public function __construct($maxComplexity) {
24
    $this->maxComplexity = $maxComplexity;
25
  }
26
27
  /**
28
   * {@inheritdoc}
29
   */
30
  public function visit(array $args, FieldInterface $field, $child) {
31
    /** @var \Youshido\GraphQL\Config\Field\FieldConfig $config */
32
    $config = $field->getConfig();
33
    $cost = $config->get('cost', NULL);
34
35
    if (is_callable($cost)) {
36
      $cost = $cost($args, $field, $child);
37
    }
38
39
    return $cost;
40
  }
41
42
  /**
43
   * {@inheritdoc}
44
   */
45
  public function reduce($carry, $current) {
46
    return !empty($current) ? $carry + $current : $carry;
47
  }
48
49
  /**
50
   * {@inheritdoc}
51
   */
52
  public function initial() {
53
    return 0;
54
  }
55
56
  /**
57
   * {@inheritdoc}
58
   */
59
  public function finish($result) {
60
    if ($result > $this->maxComplexity) {
61
      throw new ResolveException('The query exceeds the allowed maximum complexity.');
62
    }
63
  }
64
}