3 * This file is part of the Diff package.
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);
26 $lineCount = count($lines);
31 for ($i = 0; $i < $lineCount; ++$i) {
32 if (preg_match('(^---\\s+(?P<file>\\S+))', $lines[$i], $fromMatch) &&
33 preg_match('(^\\+\\+\\+\\s+(?P<file>\\S+))', $lines[$i + 1], $toMatch)) {
35 $this->parseFileDiff($diff, $collected);
40 $diff = new Diff($fromMatch['file'], $toMatch['file']);
43 if (preg_match('/^(?:diff --git |index [\da-f\.]+|[+-]{3} [ab])/', $lines[$i])) {
46 $collected[] = $lines[$i];
50 if (count($collected) && ($diff !== null)) {
51 $this->parseFileDiff($diff, $collected);
62 private function parseFileDiff(Diff $diff, array $lines)
66 foreach ($lines as $line) {
67 if (preg_match('/^@@\s+-(?P<start>\d+)(?:,\s*(?P<startrange>\d+))?\s+\+(?P<end>\d+)(?:,\s*(?P<endrange>\d+))?\s+@@/', $line, $match)) {
70 isset($match['startrange']) ? max(1, $match['startrange']) : 1,
72 isset($match['endrange']) ? max(1, $match['endrange']) : 1
80 if (preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
81 $type = Line::UNCHANGED;
83 if ($match['type'] == '+') {
85 } elseif ($match['type'] == '-') {
86 $type = Line::REMOVED;
89 $diffLines[] = new Line($type, $match['line']);
92 $chunk->setLines($diffLines);
97 $diff->setChunks($chunks);