Completed
Push — master ( e891dc...f1a729 )
by Alexandr
03:27
created

MaxComplexityQueryVisitor::visit()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 12
rs 9.2
ccs 10
cts 10
cp 1
cc 4
eloc 9
nc 8
nop 3
crap 4
1
<?php
2
/*
3
* Concrete implementation of query visitor.
4
*
5
* Enforces maximum complexity on a query, computed from "cost" functions on
6
* the fields touched by that query.
7
*
8
* @author Ben Roberts <[email protected]>
9
* created: 7/11/16 11:05 AM
10
*/
11
12
namespace Youshido\GraphQL\Execution\Visitor;
13
14
15
use Youshido\GraphQL\Config\Field\FieldConfig;
16
17
class MaxComplexityQueryVisitor extends AbstractQueryVisitor {
18
19
  public $maxScore;
20
21
  protected $defaultScore = 1;
22
23 2
  public function __construct($max) {
24 2
    parent::__construct();
25
26 2
    $this->maxScore = $max;
27 2
  }
28
29
  /**
30
   * @param array       $args
31
   * @param FieldConfig $fieldConfig
32
   * @param int         $childScore
33
   *
34
   * @return int|null
35
   * @throws \Exception
36
   */
37 2
  public function visit(array $args, FieldConfig $fieldConfig, $childScore = 0) {
38 2
    $cost = $fieldConfig->get('cost');
39 2
    if (is_callable($cost)) {
40 1
      $cost = $cost($args, $fieldConfig, $childScore);
41 1
    }
42 2
    $cost = $cost ?: $this->defaultScore;
43 2
    $this->memo += $cost;
44 2
    if ($this->memo > $this->maxScore) {
45 1
      throw new \Exception('query exceeded max allowed complexity of ' . $this->maxScore);
46
    }
47 2
    return $cost;
48
  }
49
}