Skip to content

Commit 46528f2

Browse files
committed
Add: Json renderer
1 parent 21e12d1 commit 46528f2

File tree

4 files changed

+400
-0
lines changed

4 files changed

+400
-0
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
"digilive/git-changelog": "^2"
4040
},
4141
"suggest": {
42+
"ext-json": "*",
4243
"jblond/php-cli": "^1.0"
4344
},
4445
"autoload": {
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
namespace jblond\Diff\Renderer\Text;
4+
5+
use jblond\Diff\Renderer\MainRendererAbstract;
6+
7+
/**
8+
* Unified diff generator for PHP DiffLib.
9+
*
10+
* PHP version 7.3 or greater
11+
*
12+
* @package jblond\Diff\Renderer\Text
13+
* @author Mario Brandt <[email protected]>
14+
* @copyright (c) 2023 Mario Brandt
15+
* @license New BSD License http://www.opensource.org/licenses/bsd-license.php
16+
* @version 2.4.0
17+
* @link https://github.com/JBlond/php-diff
18+
*/
19+
20+
/**
21+
* Class Diff_Renderer_Text_Json
22+
*/
23+
class Json extends MainRendererAbstract
24+
{
25+
/**
26+
* @return false|string
27+
*/
28+
public function render()
29+
{
30+
$return = [];
31+
$opCodes = $this->diff->getGroupedOpCodes();
32+
33+
foreach ($opCodes as $key => $group) {
34+
$return[] = $this->toArray($group);
35+
}
36+
return json_encode($return, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
37+
}
38+
39+
/**
40+
* @param $group
41+
* @return array
42+
*/
43+
protected function toArray($group): array
44+
{
45+
$return = [];
46+
foreach ($group as [$tag, $iGroup1, $iGroup2, $jGroup1, $jGroup2]) {
47+
$return[] = [
48+
'tag' => $tag,
49+
'old' => [
50+
'offset' => $iGroup1,
51+
'lines' => $this->diff->getArrayRange($this->diff->getVersion1(), $iGroup1, $iGroup2)
52+
],
53+
'new' => [
54+
'offset' => $jGroup1,
55+
'lines' => $this->diff->getArrayRange($this->diff->getVersion2(), $jGroup1, $jGroup2)
56+
],
57+
];
58+
}
59+
return $return;
60+
}
61+
}

tests/Diff/Renderer/Text/TextRenderersTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,4 +130,23 @@ public function testInlineCli(): void
130130
}
131131
$this->assertStringEqualsFile('tests/resources/textInlineCli.txt', $result);
132132
}
133+
134+
/**
135+
* Test the output of the JSON text renderer
136+
*
137+
* @covers \jblond\Diff\Renderer\Text\Json
138+
*/
139+
public function testJson(): void
140+
{
141+
$diff = new Diff(
142+
file_get_contents('tests/resources/a.txt'),
143+
file_get_contents('tests/resources/b.txt')
144+
);
145+
$renderer = new Diff\Renderer\Text\Json();
146+
$result = $diff->render($renderer);
147+
if ($this->genOutputFiles) {
148+
file_put_contents('results.json', $result);
149+
}
150+
$this->assertStringEqualsFile('tests/resources/textResult.json', $result);
151+
}
133152
}

0 commit comments

Comments
 (0)