|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of Railt package. |
|
5
|
|
|
* |
|
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
7
|
|
|
* file that was distributed with this source code. |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
declare(strict_types=1); |
|
11
|
|
|
|
|
12
|
|
|
namespace Railt\SDL\Exception; |
|
13
|
|
|
|
|
14
|
|
|
use Phplrt\Contracts\Source\ReadableInterface; |
|
15
|
|
|
use Phplrt\Position\PositionInterface; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Class Highlight |
|
19
|
|
|
*/ |
|
20
|
|
|
class Highlight |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* @param ReadableInterface $file |
|
24
|
|
|
* @param PositionInterface $position |
|
25
|
|
|
* @return string |
|
26
|
|
|
*/ |
|
27
|
|
|
public function read(ReadableInterface $file, PositionInterface $position): string |
|
28
|
|
|
{ |
|
29
|
|
|
$current = $this->getSourceLine($file, $position); |
|
30
|
|
|
|
|
31
|
|
|
return \PHP_EOL . |
|
32
|
|
|
$this->renderLine((string)$position->getLine(), $current) . |
|
33
|
|
|
$this->renderErrorPosition($position->getColumn()) |
|
34
|
|
|
; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @param int $offset |
|
39
|
|
|
* @return string |
|
40
|
|
|
*/ |
|
41
|
|
|
private function renderErrorPosition(int $offset): string |
|
42
|
|
|
{ |
|
43
|
|
|
return $this->line('') . \str_repeat(' ', \max($offset - 1, 0)) . '^' . \PHP_EOL; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* @param string $line |
|
48
|
|
|
* @param string $code |
|
49
|
|
|
* @return string |
|
50
|
|
|
*/ |
|
51
|
|
|
private function renderLine(string $line, string $code): string |
|
52
|
|
|
{ |
|
53
|
|
|
return $this->line($line) . \rtrim($code) . \PHP_EOL; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @param string $line |
|
58
|
|
|
* @return string |
|
59
|
|
|
*/ |
|
60
|
|
|
private function line(string $line): string |
|
61
|
|
|
{ |
|
62
|
|
|
$line = \str_pad($line, 4, ' ', \STR_PAD_LEFT); |
|
63
|
|
|
|
|
64
|
|
|
return ' ' . $line . ' | '; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* @param ReadableInterface $file |
|
69
|
|
|
* @param PositionInterface $position |
|
70
|
|
|
* @return array|string[] |
|
71
|
|
|
*/ |
|
72
|
|
|
private function getSourceLine(ReadableInterface $file, PositionInterface $position): string |
|
73
|
|
|
{ |
|
74
|
|
|
[$stream, $i, $line] = [$file->getStream(), 0, '']; |
|
75
|
|
|
|
|
76
|
|
|
while (++$i <= $position->getLine() && ! \feof($stream)) { |
|
77
|
|
|
$line = \fgets($stream); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
return $line; |
|
|
|
|
|
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|