3 * This file is part of sebastian/diff.
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace SebastianBergmann\Diff;
14 * Unified diff parser.
19 * @param string $string
23 public function parse($string)
25 $lines = \preg_split('(\r\n|\r|\n)', $string);
27 if (!empty($lines) && $lines[\count($lines) - 1] == '') {
31 $lineCount = \count($lines);
36 for ($i = 0; $i < $lineCount; ++$i) {
37 if (\preg_match('(^---\\s+(?P<file>\\S+))', $lines[$i], $fromMatch) &&
38 \preg_match('(^\\+\\+\\+\\s+(?P<file>\\S+))', $lines[$i + 1], $toMatch)) {
40 $this->parseFileDiff($diff, $collected);
46 $diff = new Diff($fromMatch['file'], $toMatch['file']);
50 if (\preg_match('/^(?:diff --git |index [\da-f\.]+|[+-]{3} [ab])/', $lines[$i])) {
54 $collected[] = $lines[$i];
58 if ($diff !== null && \count($collected)) {
59 $this->parseFileDiff($diff, $collected);
71 private function parseFileDiff(Diff $diff, array $lines)
76 foreach ($lines as $line) {
77 if (\preg_match('/^@@\s+-(?P<start>\d+)(?:,\s*(?P<startrange>\d+))?\s+\+(?P<end>\d+)(?:,\s*(?P<endrange>\d+))?\s+@@/', $line, $match)) {
80 isset($match['startrange']) ? \max(1, $match['startrange']) : 1,
82 isset($match['endrange']) ? \max(1, $match['endrange']) : 1
91 if (\preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
92 $type = Line::UNCHANGED;
94 if ($match['type'] === '+') {
96 } elseif ($match['type'] === '-') {
97 $type = Line::REMOVED;
100 $diffLines[] = new Line($type, $match['line']);
102 if (null !== $chunk) {
103 $chunk->setLines($diffLines);
108 $diff->setChunks($chunks);