Debian Codegraph @

vendor/jfcherng/php-diff/src/Renderer/AbstractRenderer.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jfcherng\Diff\Renderer;
6
7 use Jfcherng\Diff\Differ;
8 use Jfcherng\Diff\SequenceMatcher;
9 use Jfcherng\Diff\Utility\Language;
10
11 /**
12 * Base class for diff renderers.
13 *
14 * @todo use typed properties (BC breaking for public interface) in v7
15 */
16 abstract class AbstractRenderer implements RendererInterface
17 {
18 /**
19 * @var array information about this renderer
20 */
21 public const INFO = [
22 'desc' => 'default_desc',
23 'type' => 'default_type',
24 ];
25
26 /**
27 * @var bool Is this renderer pure text?
28 */
29 public const IS_TEXT_RENDERER = true;
30
31 /**
32 * @var string[] array of the opcodes and their corresponding symbols
33 */
34 public const SYMBOL_MAP = [
35 SequenceMatcher::OP_DEL => '-',
36 SequenceMatcher::OP_EQ => ' ',
37 SequenceMatcher::OP_INS => '+',
38 SequenceMatcher::OP_REP => '!',
39 ];
40
41 /**
42 * @var Language the language translation object
43 */
44 protected $t;
45
46 /**
47 * If the input "changes" have `<ins>...</ins>` or `<del>...</del>`,
48 * which means they have been processed, then `false`. Otherwise, `true`.
49 *
50 * @var bool
51 */
52 protected $changesAreRaw = true;
53
54 /**
55 * @var array array of the default options that apply to this renderer
56 */
57 protected static $defaultOptions = [
58 // how detailed the rendered HTML in-line diff is? (none, line, word, char)
59 'detailLevel' => 'line',
60 // renderer language: eng, cht, chs, jpn, ...
61 // or an array which has the same keys with a language file
62 // check the "Custom Language" section in the readme for more advanced usage
63 'language' => 'eng',
64 // show line numbers in HTML renderers
65 'lineNumbers' => true,
66 // show a separator between different diff hunks in HTML renderers
67 'separateBlock' => true,
68 // show the (table) header
69 'showHeader' => true,
70 // convert spaces/tabs into HTML codes like `<span class="ch sp"> </span>`
71 // and the frontend is responsible for rendering them with CSS.
72 // when using this, "spacesToNbsp" should be false and "tabSize" is not respected.
73 'spaceToHtmlTag' => false,
74 // the frontend HTML could use CSS "white-space: pre;" to visualize consecutive whitespaces
75 // but if you want to visualize them in the backend with "&nbsp;", you can set this to true
76 'spacesToNbsp' => false,
77 // HTML renderer tab width (negative = do not convert into spaces)
78 'tabSize' => 4,
79 // this option is currently only for the Combined renderer.
80 // it determines whether a replace-type block should be merged or not
81 // depending on the content changed ratio, which values between 0 and 1.
82 'mergeThreshold' => 0.8,
83 // this option is currently only for the Unified and the Context renderers.
84 // RendererConstant::CLI_COLOR_AUTO = colorize the output if possible (default)
85 // RendererConstant::CLI_COLOR_ENABLE = force to colorize the output
86 // RendererConstant::CLI_COLOR_DISABLE = force not to colorize the output
87 'cliColorization' => RendererConstant::CLI_COLOR_AUTO,
88 // this option is currently only for the Json renderer.
89 // internally, ops (tags) are all int type but this is not good for human reading.
90 // set this to "true" to convert them into string form before outputting.
91 'outputTagAsString' => false,
92 // this option is currently only for the Json renderer.
93 // it controls how the output JSON is formatted.
94 // see available options on https://www.php.net/manual/en/function.json-encode.php
95 'jsonEncodeFlags' => \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE,
96 // this option is currently effective when the "detailLevel" is "word"
97 // characters listed in this array can be used to make diff segments into a whole
98 // for example, making "<del>good</del>-<del>looking</del>" into "<del>good-looking</del>"
99 // this should bring better readability but set this to empty array if you do not want it
100 'wordGlues' => ['-', ' '],
101 // change this value to a string as the returned diff if the two input strings are identical
102 'resultForIdenticals' => null,
103 // extra HTML classes added to the DOM of the diff container
104 'wrapperClasses' => ['diff-wrapper'],
105 ];
106
107 /**
108 * @var array array containing the user applied and merged default options for the renderer
109 */
110 protected $options = [];
111
112 /**
113 * The constructor. Instantiates the rendering engine and if options are passed,
114 * sets the options for the renderer.
115 *
116 * @param array $options optionally, an array of the options for the renderer
117 */
118 public function __construct(array $options = [])
119 {
120 $this->setOptions($options);
121 }
122
123 /**
124 * Set the options of the renderer to those supplied in the passed in array.
125 * Options are merged with the default to ensure that there aren't any missing
126 * options.
127 *
128 * @param array $options the options
129 *
130 * @return static
131 */
132 public function setOptions(array $options): self
133 {
134 $newOptions = $options + static::$defaultOptions;
135
136 $this->updateLanguage(
137 $this->options['language'] ?? '',
138 $newOptions['language'],
139 );
140
141 $this->options = $newOptions;
142
143 return $this;
144 }
145
146 /**
147 * Get the options.
148 *
149 * @return array the options
150 */
151 public function getOptions(): array
152 {
153 return $this->options;
154 }
155
156 /**
157 * @final
158 *
159 * @todo mark this method with "final" in the next major release
160 *
161 * @throws \InvalidArgumentException
162 */
163 public function getResultForIdenticals(): string
164 {
165 $custom = $this->options['resultForIdenticals'];
166
167 if (isset($custom) && !\is_string($custom)) {
168 throw new \InvalidArgumentException('renderer option `resultForIdenticals` must be null or string.');
169 }
170
171 return $custom ?? $this->getResultForIdenticalsDefault();
172 }
173
174 /**
175 * Get the renderer default result when the old and the new are the same.
176 */
177 abstract public function getResultForIdenticalsDefault(): string;
178
179 final public function render(Differ $differ): string
180 {
181 $this->changesAreRaw = true;
182
183 // the "no difference" situation may happen frequently
184 return $differ->getOldNewComparison() === 0 && !$differ->options['fullContextIfIdentical']
185 ? $this->getResultForIdenticals()
186 : $this->renderWorker($differ);
187 }
188
189 final public function renderArray(array $differArray): string
190 {
191 $this->changesAreRaw = false;
192
193 return $this->renderArrayWorker($differArray);
194 }
195
196 /**
197 * The real worker for self::render().
198 *
199 * @param Differ $differ the differ object
200 */
201 abstract protected function renderWorker(Differ $differ): string;
202
203 /**
204 * The real worker for self::renderArray().
205 *
206 * @param array[][] $differArray the differ array
207 */
208 abstract protected function renderArrayWorker(array $differArray): string;
209
210 /**
211 * Update the Language object.
212 *
213 * @param string|string[] $old the old language
214 * @param string|string[] $new the new language
215 *
216 * @return static
217 */
218 protected function updateLanguage($old, $new): self
219 {
220 if (!isset($this->t) || $old !== $new) {
221 $this->t = new Language($new);
222 }
223
224 return $this;
225 }
226
227 /**
228 * A shorthand to do translation.
229 *
230 * @param string $text The text
231 * @param bool $escapeHtml Escape the translated text for HTML?
232 *
233 * @return string the translated text
234 */
235 protected function _(string $text, bool $escapeHtml = true): string
236 {
237 $text = $this->t->translate($text);
238
239 return $escapeHtml ? htmlspecialchars($text) : $text;
240 }
241 }