Debian Codegraph @

vendor/jfcherng/php-diff/src/Renderer/Html/Combined.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jfcherng\Diff\Renderer\Html;
6
7 use Jfcherng\Diff\Factory\LineRendererFactory;
8 use Jfcherng\Diff\Renderer\RendererConstant;
9 use Jfcherng\Diff\SequenceMatcher;
10 use Jfcherng\Diff\Utility\ReverseIterator;
11 use Jfcherng\Utility\MbString;
12
13 /**
14 * Combined HTML diff generator.
15 *
16 * Note that this renderer always has no line number.
17 */
18 final class Combined extends AbstractHtml
19 {
20 /**
21 * {@inheritdoc}
22 */
23 public const INFO = [
24 'desc' => 'Combined',
25 'type' => 'Html',
26 ];
27
28 /**
29 * {@inheritdoc}
30 */
31 public const AUTO_FORMAT_CHANGES = false;
32
33 protected function redererChanges(array $changes): string
34 {
35 if (empty($changes)) {
36 return $this->getResultForIdenticals();
37 }
38
39 $wrapperClasses = [
40 ...$this->options['wrapperClasses'],
41 'diff', 'diff-html', 'diff-combined',
42 ];
43
44 return
45 '<table class="' . implode(' ', $wrapperClasses) . '">' .
46 $this->renderTableHeader() .
47 $this->renderTableHunks($changes) .
48 '</table>';
49 }
50
51 /**
52 * Renderer the table header.
53 */
54 protected function renderTableHeader(): string
55 {
56 if (!$this->options['showHeader']) {
57 return '';
58 }
59
60 return
61 '<thead>' .
62 '<tr>' .
63 '<th>' . $this->_('differences') . '</th>' .
64 '</tr>' .
65 '</thead>';
66 }
67
68 /**
69 * Renderer the table separate block.
70 */
71 protected function renderTableSeparateBlock(): string
72 {
73 return
74 '<tbody class="skipped">' .
75 '<tr>' .
76 '<td></td>' .
77 '</tr>' .
78 '</tbody>';
79 }
80
81 /**
82 * Renderer table hunks.
83 *
84 * @param array[][] $hunks each hunk has many blocks
85 */
86 protected function renderTableHunks(array $hunks): string
87 {
88 $ret = '';
89
90 foreach ($hunks as $i => $hunk) {
91 if ($i > 0 && $this->options['separateBlock']) {
92 $ret .= $this->renderTableSeparateBlock();
93 }
94
95 foreach ($hunk as $block) {
96 $ret .= $this->renderTableBlock($block);
97 }
98 }
99
100 return $ret;
101 }
102
103 /**
104 * Renderer the table block.
105 *
106 * @param array $block the block
107 */
108 protected function renderTableBlock(array $block): string
109 {
110 switch ($block['tag']) {
111 case SequenceMatcher::OP_EQ:
112 $content = $this->renderTableBlockEqual($block);
113 break;
114 case SequenceMatcher::OP_INS:
115 $content = $this->renderTableBlockInsert($block);
116 break;
117 case SequenceMatcher::OP_DEL:
118 $content = $this->renderTableBlockDelete($block);
119 break;
120 case SequenceMatcher::OP_REP:
121 $content = $this->renderTableBlockReplace($block);
122 break;
123 default:
124 $content = '';
125 }
126
127 return '<tbody class="change change-' . self::TAG_CLASS_MAP[$block['tag']] . '">' . $content . '</tbody>';
128 }
129
130 /**
131 * Renderer the table block: equal.
132 *
133 * @param array $block the block
134 */
135 protected function renderTableBlockEqual(array $block): string
136 {
137 $block['new']['lines'] = $this->customFormatLines(
138 $block['new']['lines'],
139 SequenceMatcher::OP_EQ,
140 );
141
142 $ret = '';
143
144 // note that although we are in a OP_EQ situation,
145 // the old and the new may not be exactly the same
146 // because of ignoreCase, ignoreWhitespace, etc
147 foreach ($block['new']['lines'] as $newLine) {
148 // we could only pick either the old or the new to show
149 // here we pick the new one to let the user know what it is now
150 $ret .= $this->renderTableRow('new', SequenceMatcher::OP_EQ, $newLine);
151 }
152
153 return $ret;
154 }
155
156 /**
157 * Renderer the table block: insert.
158 *
159 * @param array $block the block
160 */
161 protected function renderTableBlockInsert(array $block): string
162 {
163 $block['new']['lines'] = $this->customFormatLines(
164 $block['new']['lines'],
165 SequenceMatcher::OP_INS,
166 );
167
168 $ret = '';
169
170 foreach ($block['new']['lines'] as $newLine) {
171 $ret .= $this->renderTableRow('new', SequenceMatcher::OP_INS, $newLine);
172 }
173
174 return $ret;
175 }
176
177 /**
178 * Renderer the table block: delete.
179 *
180 * @param array $block the block
181 */
182 protected function renderTableBlockDelete(array $block): string
183 {
184 $block['old']['lines'] = $this->customFormatLines(
185 $block['old']['lines'],
186 SequenceMatcher::OP_DEL,
187 );
188
189 $ret = '';
190
191 foreach ($block['old']['lines'] as $oldLine) {
192 $ret .= $this->renderTableRow('old', SequenceMatcher::OP_DEL, $oldLine);
193 }
194
195 return $ret;
196 }
197
198 /**
199 * Renderer the table block: replace.
200 *
201 * @param array $block the block
202 */
203 protected function renderTableBlockReplace(array $block): string
204 {
205 if ($this->options['detailLevel'] === 'none') {
206 return
207 $this->renderTableBlockDelete($block) .
208 $this->renderTableBlockInsert($block);
209 }
210
211 $ret = '';
212
213 $oldLines = $block['old']['lines'];
214 $newLines = $block['new']['lines'];
215
216 $oldLinesCount = \count($oldLines);
217 $newLinesCount = \count($newLines);
218
219 // if the line counts changes, we treat the old and the new as
220 // "a line with \n in it" and then do one-line-to-one-line diff
221 if ($oldLinesCount !== $newLinesCount) {
222 [$oldLines, $newLines] = $this->markReplaceBlockDiff($oldLines, $newLines);
223 $oldLinesCount = $newLinesCount = 1;
224 }
225
226 $oldLines = $this->customFormatLines($oldLines, SequenceMatcher::OP_DEL);
227 $newLines = $this->customFormatLines($newLines, SequenceMatcher::OP_INS);
228
229 // now $oldLines must has the same line counts with $newlines
230 for ($no = 0; $no < $newLinesCount; ++$no) {
231 $mergedLine = $this->mergeReplaceLines($oldLines[$no], $newLines[$no]);
232
233 // not merge-able, we fall back to separated form
234 if (!isset($mergedLine)) {
235 $ret .=
236 $this->renderTableBlockDelete($block) .
237 $this->renderTableBlockInsert($block);
238
239 break;
240 }
241
242 $ret .= $this->renderTableRow('rep', SequenceMatcher::OP_REP, $mergedLine);
243 }
244
245 return $ret;
246 }
247
248 /**
249 * Renderer a content row of the output table.
250 *
251 * @param string $tdClass the <td> class
252 * @param int $op the operation
253 * @param string $line the line
254 */
255 protected function renderTableRow(string $tdClass, int $op, string $line): string
256 {
257 return
258 '<tr data-type="' . self::SYMBOL_MAP[$op] . '">' .
259 '<td class="' . $tdClass . '">' . $line . '</td>' .
260 '</tr>';
261 }
262
263 /**
264 * Merge two "replace"-type lines into a single line.
265 *
266 * The implementation concept is that if we remove all closure parts from
267 * the old and the new, the rest of them (cleaned line) should be the same.
268 * And then, we add back those removed closure parts in a correct order.
269 *
270 * @param string $oldLine the old line
271 * @param string $newLine the new line
272 *
273 * @return null|string string if merge-able, null otherwise
274 */
275 protected function mergeReplaceLines(string $oldLine, string $newLine): ?string
276 {
277 $delParts = $this->analyzeClosureParts(
278 $oldLine,
279 RendererConstant::HTML_CLOSURES_DEL,
280 SequenceMatcher::OP_DEL,
281 );
282 $insParts = $this->analyzeClosureParts(
283 $newLine,
284 RendererConstant::HTML_CLOSURES_INS,
285 SequenceMatcher::OP_INS,
286 );
287
288 // get the cleaned line by a non-regex way (should be faster)
289 // i.e., the new line with all "<ins>...</ins>" parts removed
290 $mergedLine = $newLine;
291 foreach (ReverseIterator::fromArray($insParts) as $part) {
292 $mergedLine = substr_replace(
293 $mergedLine,
294 '', // deletion
295 $part['offset'],
296 \strlen($part['content']),
297 );
298 }
299
300 // note that $mergedLine is actually a clean line at this point
301 if (!$this->isLinesMergeable($oldLine, $newLine, $mergedLine)) {
302 return null;
303 }
304
305 // before building the $mergedParts, we do some adjustments
306 $this->revisePartsForBoundaryNewlines($delParts, RendererConstant::HTML_CLOSURES_DEL);
307 $this->revisePartsForBoundaryNewlines($insParts, RendererConstant::HTML_CLOSURES_INS);
308
309 // create a sorted merged parts array
310 $mergedParts = [...$delParts, ...$insParts];
311 usort(
312 $mergedParts,
313 // first sort by "offsetClean", "order" then by "type"
314 static fn (array $a, array $b): int => (
315 $a['offsetClean'] <=> $b['offsetClean']
316 ?: $a['order'] <=> $b['order']
317 ?: ($a['type'] === SequenceMatcher::OP_DEL ? -1 : 1)
318 ),
319 );
320
321 // insert merged parts into the cleaned line
322 foreach (ReverseIterator::fromArray($mergedParts) as $part) {
323 $mergedLine = substr_replace(
324 $mergedLine,
325 $part['content'],
326 $part['offsetClean'],
327 0, // insertion
328 );
329 }
330
331 return str_replace("\n", '<br>', $mergedLine);
332 }
333
334 /**
335 * Analyze and get the closure parts information of the line.
336 *
337 * Such as
338 * extract information for "<ins>part 1</ins>" and "<ins>part 2</ins>"
339 * from "Hello <ins>part 1</ins>SOME OTHER TEXT<ins>part 2</ins> World"
340 *
341 * @param string $line the line
342 * @param string[] $closures the closures
343 * @param int $type the type
344 *
345 * @return array[] the closure information
346 */
347 protected function analyzeClosureParts(string $line, array $closures, int $type): array
348 {
349 [$ld, $rd] = $closures;
350
351 $ldLength = \strlen($ld);
352 $rdLength = \strlen($rd);
353
354 $parts = [];
355 $partStart = $partEnd = 0;
356 $partLengthSum = 0;
357
358 // find the next left delimiter
359 while (false !== ($partStart = strpos($line, $ld, $partEnd))) {
360 // find the corresponding right delimiter
361 if (false === ($partEnd = strpos($line, $rd, $partStart + $ldLength))) {
362 break;
363 }
364
365 $partEnd += $rdLength;
366 $partLength = $partEnd - $partStart;
367
368 $parts[] = [
369 'type' => $type,
370 // the sorting order used when both "offsetClean" are the same
371 'order' => 0,
372 // the offset in the line
373 'offset' => $partStart,
374 // the offset in the cleaned line (i.e., the line with closure parts removed)
375 'offsetClean' => $partStart - $partLengthSum,
376 // the content of the part
377 'content' => substr($line, $partStart, $partLength),
378 ];
379
380 $partLengthSum += $partLength;
381 }
382
383 return $parts;
384 }
385
386 /**
387 * Mark differences between two "replace" blocks.
388 *
389 * Each of the returned block (lines) is always only one line.
390 *
391 * @param string[] $oldBlock The old block
392 * @param string[] $newBlock The new block
393 *
394 * @return string[][] the value of [[$oldLine], [$newLine]]
395 */
396 protected function markReplaceBlockDiff(array $oldBlock, array $newBlock): array
397 {
398 static $mbOld, $mbNew, $lineRenderer;
399
400 $mbOld ??= new MbString();
401 $mbNew ??= new MbString();
402 $lineRenderer ??= LineRendererFactory::make(
403 $this->options['detailLevel'],
404 [], /** @todo is it possible to get the differOptions here? */
405 $this->options,
406 );
407
408 $mbOld->set(implode("\n", $oldBlock));
409 $mbNew->set(implode("\n", $newBlock));
410
411 $lineRenderer->render($mbOld, $mbNew);
412
413 return [
414 [$mbOld->get()], // one-line block for the old
415 [$mbNew->get()], // one-line block for the new
416 ];
417 }
418
419 /**
420 * Determine whether the "replace"-type lines are merge-able or not.
421 *
422 * @param string $oldLine the old line
423 * @param string $newLine the new line
424 * @param string $cleanLine the clean line
425 */
426 protected function isLinesMergeable(string $oldLine, string $newLine, string $cleanLine): bool
427 {
428 $oldLine = str_replace(RendererConstant::HTML_CLOSURES_DEL, '', $oldLine);
429 $newLine = str_replace(RendererConstant::HTML_CLOSURES_INS, '', $newLine);
430
431 $sumLength = \strlen($oldLine) + \strlen($newLine);
432
433 /** @var float the changed ratio, 0 <= value < 1 */
434 $changedRatio = ($sumLength - (\strlen($cleanLine) << 1)) / ($sumLength + 1);
435
436 return $changedRatio <= $this->options['mergeThreshold'];
437 }
438
439 /**
440 * Extract boundary newlines from parts into new parts.
441 *
442 * @param array[] $parts the parts
443 * @param string[] $closures the closures
444 *
445 * @see https://git.io/JvVXH
446 */
447 protected function revisePartsForBoundaryNewlines(array &$parts, array $closures): void
448 {
449 [$ld, $rd] = $closures;
450
451 $ldRegex = preg_quote($ld, '/');
452 $rdRegex = preg_quote($rd, '/');
453
454 for ($i = \count($parts) - 1; $i >= 0; --$i) {
455 $part = &$parts[$i];
456
457 // deal with leading newlines
458 $part['content'] = preg_replace_callback(
459 "/(?P<closure>{$ldRegex})(?P<nl>[\r\n]++)/u",
460 static function (array $matches) use (&$parts, $part, $ld, $rd): string {
461 // add a new part for the extracted newlines
462 $part['order'] = -1;
463 $part['content'] = "{$ld}{$matches['nl']}{$rd}";
464 $parts[] = $part;
465
466 return $matches['closure'];
467 },
468 $part['content'],
469 );
470
471 // deal with trailing newlines
472 $part['content'] = preg_replace_callback(
473 "/(?P<nl>[\r\n]++)(?P<closure>{$rdRegex})/u",
474 static function (array $matches) use (&$parts, $part, $ld, $rd): string {
475 // add a new part for the extracted newlines
476 $part['order'] = 1;
477 $part['content'] = "{$ld}{$matches['nl']}{$rd}";
478 $parts[] = $part;
479
480 return $matches['closure'];
481 },
482 $part['content'],
483 );
484 }
485 }
486
487 /**
488 * Make lines suitable for HTML output.
489 *
490 * @param string[] $lines the lines
491 * @param int $op the operation
492 */
493 protected function customFormatLines(array $lines, int $op): array
494 {
495 if (!$this->changesAreRaw) {
496 return $lines;
497 }
498
499 static $closureMap = [
500 SequenceMatcher::OP_DEL => RendererConstant::HTML_CLOSURES_DEL,
501 SequenceMatcher::OP_INS => RendererConstant::HTML_CLOSURES_INS,
502 ];
503
504 $lines = $this->formatLines($lines);
505
506 $htmlClosures = $closureMap[$op] ?? null;
507
508 foreach ($lines as &$line) {
509 if ($htmlClosures) {
510 $line = str_replace(RendererConstant::HTML_CLOSURES, $htmlClosures, $line);
511 }
512 // fixes https://github.com/jfcherng/php-diff/issues/34
513 $line = str_replace("\r\n", "\n", $line);
514 }
515
516 return $lines;
517 }
518 }