Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | 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
 
991 lars 59
    public function getAsString(string $fileName): string
60
    {
61
        $snippet = $this->get($fileName);
62
 
63
        $snippetStrings = array_map(function (string $line, string $number) {
64
            return "{$number} {$line}";
65
        }, $snippet, array_keys($snippet));
66
 
67
        return implode(PHP_EOL, $snippetStrings);
68
    }
69
 
148 lars 70
    protected function getBounds(int $totalNumberOfLineInFile): array
71
    {
72
        $startLine = max($this->surroundingLine - floor($this->snippetLineCount / 2), 1);
73
 
74
        $endLine = $startLine + ($this->snippetLineCount - 1);
75
 
76
        if ($endLine > $totalNumberOfLineInFile) {
77
            $endLine = $totalNumberOfLineInFile;
78
            $startLine = max($endLine - ($this->snippetLineCount - 1), 1);
79
        }
80
 
81
        return [$startLine, $endLine];
82
    }
83
}