Completed
Push — master ( 0f7b0a...750008 )
by Christoffer
02:09
created

SourceLocation::fromSource()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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