1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Fubhy\GraphQL\Language; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* A representation of source input to GraphQL. |
7
|
|
|
* |
8
|
|
|
* The name is optional, but is mostly useful for clients who store GraphQL |
9
|
|
|
* documents in source files; for example, if the GraphQL input is in a file |
10
|
|
|
* Foo.graphql, it might be useful for name to be "Foo.graphql". |
11
|
|
|
*/ |
12
|
|
|
class Source |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var string |
16
|
|
|
*/ |
17
|
|
|
protected $body; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
protected $name; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var int |
26
|
|
|
*/ |
27
|
|
|
protected $length; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Constructor. |
31
|
|
|
* |
32
|
|
|
* @param string $body |
33
|
|
|
* @param string $name |
34
|
|
|
*/ |
35
|
426 |
|
public function __construct($body, $name = 'GraphQL') |
36
|
|
|
{ |
37
|
426 |
|
$this->body = $body; |
38
|
426 |
|
$this->name = $name; |
39
|
426 |
|
$this->length = mb_strlen($body); |
40
|
426 |
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @return string |
44
|
|
|
*/ |
45
|
426 |
|
public function getBody() |
46
|
|
|
{ |
47
|
426 |
|
return $this->body; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @return string |
52
|
|
|
*/ |
53
|
|
|
public function getName() |
54
|
|
|
{ |
55
|
|
|
return $this->name; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @return int |
60
|
|
|
*/ |
61
|
426 |
|
public function getLength() |
62
|
|
|
{ |
63
|
426 |
|
return $this->length; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Takes a Source and a UTF-8 character offset, and returns the |
68
|
|
|
* corresponding line and column as a SourceLocation. |
69
|
|
|
* |
70
|
|
|
* @param $position |
71
|
|
|
* |
72
|
|
|
* @return \Fubhy\GraphQL\Language\SourceLocation |
73
|
|
|
*/ |
74
|
|
|
public function getLocation($position) |
75
|
|
|
{ |
76
|
|
|
$pattern = '/\r\n|[\n\r\u2028\u2029]/g'; |
77
|
|
|
$subject = mb_substr($this->body, 0, $position, 'UTF-8'); |
78
|
|
|
|
79
|
|
|
preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE); |
80
|
|
|
$location = array_reduce($matches[0], function ($carry, $match) use ($position) { |
81
|
|
|
return [ |
82
|
|
|
$carry[0] + 1, |
83
|
|
|
$position + 1 - ($match[1] + mb_strlen($match[0], 'UTF-8')) |
84
|
|
|
]; |
85
|
|
|
}, [1, $position + 1]); |
86
|
|
|
|
87
|
|
|
return new SourceLocation($location[0], $location[1]); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|