Passed
Pull Request — master (#128)
by Christoffer
02:40
created

SourceLocation::toJSON()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Digia\GraphQL\Language;
4
5
use Digia\GraphQL\Util\ArrayToJsonTrait;
6
use Digia\GraphQL\Util\SerializationInterface;
7
8
class SourceLocation implements SerializationInterface
9
{
10
    use ArrayToJsonTrait;
11
12
    /**
13
     * @var int
14
     */
15
    protected $line;
16
17
    /**
18
     * @var int
19
     */
20
    protected $column;
21
22
    /**
23
     * SourceLocation constructor.
24
     *
25
     * @param int $line
26
     * @param int $column
27
     */
28
    public function __construct(int $line = 1, int $column = 1)
29
    {
30
        $this->line   = $line;
31
        $this->column = $column;
32
    }
33
34
    /**
35
     * @return int
36
     */
37
    public function getLine(): int
38
    {
39
        return $this->line;
40
    }
41
42
    /**
43
     * @return int
44
     */
45
    public function getColumn(): int
46
    {
47
        return $this->column;
48
    }
49
50
    /**
51
     * @param Source $source
52
     * @param int    $position
53
     * @return SourceLocation
54
     */
55
    public static function fromSource(Source $source, int $position): self
56
    {
57
        $line    = 1;
58
        $column  = $position + 1;
59
        $matches = [];
60
        preg_match_all("/\r\n|[\n\r]/", mb_substr($source->getBody(), 0, $position), $matches, PREG_OFFSET_CAPTURE);
61
62
        foreach ($matches[0] as $index => $match) {
63
            $line   += 1;
64
            $column = $position + 1 - ($match[1] + mb_strlen($match[0]));
65
        }
66
67
        return new static($line, $column);
68
    }
69
70
    /**
71
     * @inheritdoc
72
     */
73
    public function toArray(): array
74
    {
75
        return [
76
            'line'   => $this->line,
77
            'column' => $this->column,
78
        ];
79
    }
80
}
81