Codesnippet::get()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 8
nop 1
dl 0
loc 29
rs 9.456
c 0
b 0
f 0
1
<?php
2
3
namespace Facade\FlareClient\Stacktrace;
4
5
use RuntimeException;
6
7
class Codesnippet
8
{
9
    /** @var int */
10
    private $surroundingLine = 1;
11
12
    /** @var int */
13
    private $snippetLineCount = 9;
14
15
    public function surroundingLine(int $surroundingLine): self
16
    {
17
        $this->surroundingLine = $surroundingLine;
18
19
        return $this;
20
    }
21
22
    public function snippetLineCount(int $snippetLineCount): self
23
    {
24
        $this->snippetLineCount = $snippetLineCount;
25
26
        return $this;
27
    }
28
29
    public function get(string $fileName): array
30
    {
31
        if (! file_exists($fileName)) {
32
            return [];
33
        }
34
35
        try {
36
            $file = new File($fileName);
37
38
            [$startLineNumber, $endLineNumber] = $this->getBounds($file->numberOfLines());
0 ignored issues
show
Bug introduced by
The variable $startLineNumber does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $endLineNumber does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
39
40
            $code = [];
41
42
            $line = $file->getLine($startLineNumber);
43
44
            $currentLineNumber = $startLineNumber;
45
46
            while ($currentLineNumber <= $endLineNumber) {
47
                $code[$currentLineNumber] = rtrim(substr($line, 0, 250));
48
49
                $line = $file->getNextLine();
50
                $currentLineNumber++;
51
            }
52
53
            return $code;
54
        } catch (RuntimeException $exception) {
55
            return [];
56
        }
57
    }
58
59
    private function getBounds($totalNumberOfLineInFile): array
60
    {
61
        $startLine = max($this->surroundingLine - floor($this->snippetLineCount / 2), 1);
62
63
        $endLine = $startLine + ($this->snippetLineCount - 1);
64
65
        if ($endLine > $totalNumberOfLineInFile) {
66
            $endLine = $totalNumberOfLineInFile;
67
            $startLine = max($endLine - ($this->snippetLineCount - 1), 1);
68
        }
69
70
        return [$startLine, $endLine];
71
    }
72
}
73