Debian Codegraph @

vendor/jfcherng/php-diff/src/Renderer/Text/JsonText.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jfcherng\Diff\Renderer\Text;
6
7 use Jfcherng\Diff\Differ;
8 use Jfcherng\Diff\SequenceMatcher;
9
10 /**
11 * Plain text Json diff generator.
12 */
13 final class JsonText extends AbstractText
14 {
15 /**
16 * {@inheritdoc}
17 */
18 public const INFO = [
19 'desc' => 'Text JSON',
20 'type' => 'Text',
21 ];
22
23 protected function renderWorker(Differ $differ): string
24 {
25 $ret = [];
26
27 foreach ($differ->getGroupedOpcodes() as $hunk) {
28 $ret[] = $this->renderHunk($differ, $hunk);
29 }
30
31 if ($this->options['outputTagAsString']) {
32 $this->convertTagToString($ret);
33 }
34
35 return json_encode($ret, $this->options['jsonEncodeFlags']);
36 }
37
38 /**
39 * Render the hunk.
40 *
41 * @param Differ $differ the differ object
42 * @param int[][] $hunk the hunk
43 */
44 protected function renderHunk(Differ $differ, array $hunk): array
45 {
46 $ret = [];
47
48 foreach ($hunk as [$op, $i1, $i2, $j1, $j2]) {
49 $ret[] = [
50 'tag' => $op,
51 'old' => [
52 'offset' => $i1,
53 'lines' => $differ->getOld($i1, $i2),
54 ],
55 'new' => [
56 'offset' => $j1,
57 'lines' => $differ->getNew($j1, $j2),
58 ],
59 ];
60 }
61
62 return $ret;
63 }
64
65 /**
66 * Convert tags of changes to their string form for better readability.
67 *
68 * @param array[][] $changes the changes
69 */
70 protected function convertTagToString(array &$changes): void
71 {
72 foreach ($changes as &$hunks) {
73 foreach ($hunks as &$block) {
74 $block['tag'] = SequenceMatcher::opIntToStr($block['tag']);
75 }
76 }
77 }
78 }