Passed
Pull Request — master (#69)
by Dave
02:23
created

Parser   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 47
rs 10
c 0
b 0
f 0
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A parseDiff() 0 23 4
A getLines() 0 14 4
1
<?php
2
3
/**
4
 * Static Analysis Results Baseliner (sarb).
5
 *
6
 * (c) Dave Liddament
7
 *
8
 * For the full copyright and licence information please view the LICENSE file distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace DaveLiddament\StaticAnalysisResultsBaseliner\Domain\HistoryAnalyser\UnifiedDiffParser;
14
15
use DaveLiddament\StaticAnalysisResultsBaseliner\Domain\HistoryAnalyser\UnifiedDiffParser\internal\DiffParseException;
16
use DaveLiddament\StaticAnalysisResultsBaseliner\Domain\HistoryAnalyser\UnifiedDiffParser\internal\FileMutationsBuilder;
17
use DaveLiddament\StaticAnalysisResultsBaseliner\Domain\HistoryAnalyser\UnifiedDiffParser\internal\FindFileDiffStartState;
18
19
/**
20
 * Parses a Unified Diff (see docs folder).
21
 */
22
class Parser
23
{
24
    /**
25
     * @throws ParseException
26
     */
27
    public function parseDiff(string $diffAsString): FileMutations
28
    {
29
        $fileMutationsBuilder = new FileMutationsBuilder();
30
        $state = new FindFileDiffStartState($fileMutationsBuilder);
31
32
        $lines = $this->getLines($diffAsString);
33
34
        foreach ($lines as $number => $line) {
35
            try {
36
                $state = $state->processLine($line);
37
            } catch (DiffParseException $e) {
38
                $lineNumber = $number + 1;
39
                throw ParseException::fromDiffParseException((string) $lineNumber, $e);
40
            }
41
        }
42
43
        try {
44
            $state->finish();
45
        } catch (DiffParseException $e) {
46
            throw ParseException::fromDiffParseException(ParseException::UNEXPECTED_END_OF_FILE, $e);
47
        }
48
49
        return $fileMutationsBuilder->build();
50
    }
51
52
    /**
53
     * @return array<int,string>
54
     */
55
    private function getLines(string $diffAsString): array
56
    {
57
        $lines = explode(PHP_EOL, $diffAsString);
58
59
        // Strip trailing empty lines from diff
60
        do {
61
            $finalLineIndex = count($lines) - 1;
62
            $removeFinalLine = ($finalLineIndex >= 0) && ('' === trim($lines[$finalLineIndex]));
63
            if ($removeFinalLine) {
64
                unset($lines[$finalLineIndex]);
65
            }
66
        } while ($removeFinalLine);
67
68
        return $lines;
69
    }
70
}
71