Subversion-Projekte lars-tiefland.laravel_shop

Revision

Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
namespace Spatie\Backtrace;
4
 
5
use RuntimeException;
6
 
7
class CodeSnippet
8
{
9
    /** @var int */
10
    protected $surroundingLine = 1;
11
 
12
    /** @var int */
13
    protected $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());
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
    protected function getBounds(int $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
}