Test Setup Failed
Push — master ( 1595cb...050b68 )
by Kirill
21:00
created

Highlight   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 13
dl 0
loc 61
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A line() 0 5 1
A renderLine() 0 3 1
A renderErrorPosition() 0 3 1
A getSourceLine() 0 9 3
A read() 0 7 1
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;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $line returns the type string which is incompatible with the documented return type array|string[].
Loading history...
81
    }
82
}
83