xref: /web-bugs/src/Utils/Diff.php (revision e3c4b0ac)
1<?php
2
3namespace App\Utils;
4
5/**
6 * Unified diff renderer.
7 *
8 * This class renders the diff in classic "unified diff" format and extends the
9 * Horde Text_Diff library https://www.horde.org/libraries/Horde_Text_Diff
10 */
11class Diff extends \Horde_Text_Diff_Renderer
12{
13    /**
14     * Number of leading context "lines" to preserve.
15     */
16    public $_leading_context_lines = 4;
17
18    /**
19     * Number of trailing context "lines" to preserve.
20     */
21    public $_trailing_context_lines = 4;
22
23    /**
24     * Class constructor.
25     */
26    public function __construct($d)
27    {
28        $this->diff = $d;
29        parent::__construct();
30    }
31
32    public function _blockHeader($xbeg, $xlen, $ybeg, $ylen)
33    {
34        $removed = $xlen - $ylen;
35        if ($removed > 0) {
36            return '<span class="diffheader">Line '.$xbeg.' (now '.$ybeg.'), was '.$xlen.' lines, now '.$ylen.' lines</span>';
37        }
38    }
39
40    public function _added($lines)
41    {
42        self::escapeHTML($lines);
43
44        return '<span class="newdiff"> '.implode('</span>'."\n".'<span class="newdiff"> ', $lines).'</span>';
45    }
46
47    public function _context($lines)
48    {
49        self::escapeHTML($lines);
50
51        return "\n" . parent::_context($lines);
52    }
53
54    public function _deleted($lines)
55    {
56        self::escapeHTML($lines);
57
58        return '<span class="olddiff"> '.implode('</span>'."\n".'<span class="olddiff"> ', $lines).'</span>';
59    }
60
61    public function _changed($orig, $final)
62    {
63        return $this->_deleted($orig)."\n".$this->_added($final);
64    }
65
66    public function render($diff)
67    {
68        return parent::render($this->diff);
69    }
70
71    protected static function escapeHTML(&$lines)
72    {
73        array_walk($lines, function(&$a, $b) {
74            $a = htmlspecialchars($a);
75        });
76    }
77}
78