Git Product home page Git Product logo

php-diff's People

Contributors

abdielcs avatar alejandrodecap avatar andreypaa avatar anrighi avatar baceto90 avatar brianteeman avatar chrisboulton avatar codacy-badger avatar dgarrett avatar flaushi avatar jensklose avatar jfcherng avatar joshfraser avatar kelunik avatar miclf avatar ondrejmirtes avatar oppara avatar phavel avatar sdlins avatar the-turk avatar woren951 avatar xiphe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-diff's Issues

Question: PHP8 Support

Hello,

Is the package compatible with php8? I see the tests are running on php8.1 too but I would like to see if anyone is using it in php8 env.

Difference of the Diffing Libraries

Hello,

I'm trying to implement the diffing logic on my project. I've been searched for diffing library for requirements of my project.

I've found two useful library. Yours and yetanotherape/diff-match-patch. Could you give me details that what is the difference between these libraries actually?

I could tell that the other library has support patch and different search algorithm. But also it hasn't provide HTML output. Your library so flexible for HTML output.

Also the other library has new line diffing match. I mean the library could able to catch the same sentence even the line has increased. As if it would be amazing that you could use the core algorithm of the other library on your project. But i might have missed something that i have don't know yet. Also that's why i've opened the issue.

I just don't want to miss something before having bad experience that if i choose yours or the other library for my requirement.

Thank you for providing the library to the community.

Duplicate output from Combined diff

Hi @jfcherng ,

First of all, thanks for your great work. Looks like there is one issue with the diff tool, I'll try to explain it below.

When having 3 lines edited from the beginning of the text, Combined diff gives the same result 3 times. Here is an example of the code:

            $textA = "111\n222\n333\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n";

            $textB = "999\n888\n777\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n";

            $testResult = DiffHelper::calculate(
                $textA,
                $textB,
                'Combined',
                ['context' => Differ::CONTEXT_ALL],
                ['showHeader' => false]
            );

The output is like this
image

With other renderers (Json, inline). the result is correct.

tabs and spaces

What is the intended behaviour of the tab visualisation you show in the demo. Doesnt appear to do anything.

In my tests I have set 6 spaces and two tabs

'spacesToNbsp' => true,
'tabSize' => 4,

image

image

it looks to me that only every alternative space is being presented as a nbsp

am I misunderstanding something?

First char is omitted in result

I am using version 6.11.1
I am encountering an issue where only the first character is missing when a diff is calculated.

Here is my function containing use of the php-diff tool.

public function getContentDiff($old, $new)
{
    $renderer_name = 'Combined';
    $differ_options = [];
    $renderer_options = [
        'detailLevel' => 'word',
    ];

    return DiffHelper::calculate($old, $new, $renderer_name, $differ_options, $renderer_options);
}

As you can see from the following image, after an edit is made the diff omits the first character of the line in the diff.

Screen Shot 2022-02-03 at 3 55 07 PM

Any advice?

Too much space in combined view with newlines

image

Problem seems to be a newline between these two <br> tags:

image

Removing the actual newline between the two tags using Firefox's inspector solves the problem for me:

image

I use the following code to render the page:

$diff = DiffHelper::calculate($model->OldContent, $model->NewContent, 'Combined', array(
	'context' => Differ::CONTEXT_ALL,
), array(
	'detailLevel' => 'word',
));

echo '<html><head><link rel="stylesheet" href="/vendor/jfcherng/php-diff/example/diff-table.css"></head><body>';
echo '<pre style="border:1px solid #000;">' . $model->OldContent . '</pre>';
echo '<pre style="border:1px solid #000;">' . $model->NewContent . '</pre>';
echo $diff;
echo '</body>';

unexpected combined diff result with Chinese

Hi, this maybe a problem, different test strings lead to different results.

    $rendererOptions = [
        'detailLevel' => 'char',
        'lineNumbers' => true,
        'showHeader' => false,
        'spacesToNbsp' => false,
        'tabSize' => -1,
        'separateBlock' => true,
        'resultForIdenticals' => '=',
        'wrapperClasses' => [],
    ];
    $differOptions = [];
    $rendererName = 'Combined';
    $old = '手动风尚打破';
    $new = '啊阿斯蒂芬破';
    // or
    // $old = '破手动风尚打';
    // $new = '破啊阿斯蒂芬';
    $diff_result = DiffHelper::calculate($old, $new, $rendererName, $differOptions, $rendererOptions);

expected: <del>手动风尚打</del><ins>啊阿斯蒂芬</ins>破
got <del>手动风尚打</del>破<ins>啊阿斯蒂芬</ins>破

or

expected: 破<del>手动风尚打</del><ins>啊阿斯蒂芬</ins>
got: 破<del>手动风尚打</del>破<ins>啊阿斯蒂芬</ins>

conditions to reproduce:

中文
字数相同
字数>=6
首字相同或尾字相同
chinese
old and new string with same length
length >= 6
same head or tail char

Json Combined

Hello!
first of all thank you very much for this cool library. I've been playing around with it a lot today!
Although it offers a lot, i couldn't find an option to have what "Renderer: Combined" does with an JSON option.
"Renderer: HTML JSON" kind of does it but it would still out put a deleted and inserted item in the "new" and "old" table separately.
Are you aware of a feasible solution to have what you do with combined just as output like the "Renderer: HTML JSON"?

If that is not the case do you have a good idea on how to do that?

Kind Regards
Jack

Autoloader tries to include Html/Unified.php

I have a problem with rendererName Unified calling for Jfcherng/Diff/Renderer/Html/Unified.php but the file is in the Text folder, not Html.

include 'vendor/autoload.php';
$diff = Jfcherng\Diff\DiffHelper::calculate($string1, $string2, 'Unified'); // Nope

It's worth noting I have a secondary spl_autoloader that fires if Composer's was unable to include the file. This is where I caught it. It shouldn't interfere as the secondary autoloader only fires when Composer did not autoload.

PSR-12

https://github.com/jfcherng/php-diff/tree/psr-12 Just to prevent from being forgotten.

Previously in PSR-2, the major "problem" is about the cs of multiline conditioning. PSR-12 has made it more clear and friendly.


May try <rule ref="PSR12"/> when php_codesniffer reaches 3.5.0.

[Question] How to avoid "No newline at end of file"?

Hi!

Is there any way to prevent "No newline at end of file" be present on diff string?

DiffHelper::calculate("", "abc");


// Also does not work
DiffHelper::calculate("", "abc", differOptions: ['ignoreLineEnding' => true]);

Results

@@ -0,0 +1 @@
+abc
\ No newline at end of file

In Combined view, HTML in the OP_EQ section is not escaped

To reproduce:

$old = '<b>three</b>';

$new = 'one
<b>two</b>
<b>three</b>';

echo Jfcherng\Diff\DiffHelper::calculate($old, $new, 'Combined');

Output (newlines added for readability):

<table class="diff-wrapper diff diff-html diff-combined">
  <thead><tr><th>Differences</th></tr></thead>
<tbody class="change change-ins">
  <tr data-type="+">
    <td class="new">one</td>
  </tr>
  <tr data-type="+">
    <td class="new">&lt;b&gt;two&lt;/b&gt;</td>
  </tr>
</tbody>
<tbody class="change change-eq">
  <tr data-type=" ">
    <td class="new"><b>three</b></td>
  </tr>
</tbody>
</table>

The line <b>two</b> is properly escaped as &lt;b&gt;two&lt;/b&gt;, but <b>three</b> is output literally.

This may lead to XSS if the diffed text that didn't change contains JavaScript.

PSR2

There are some code violations to PSR2

You use phpcs.xml with

<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="php-diff">
	<description>php-diff</description>
	<rule ref="PSR2" />
</ruleset>

example

php phpcs.phar --standard=phpcs.xml -s -p --colors ./src/

Render identical strings instead of returning null

First of all, Thank you so much for working on this amazing package ❤️

I am working on a Versioning plugin that shows the diff for fields like title, content.

Its inspired by WordPress Revisioning system.

Is there any option in this package to render the identical strings as they are instead of returning null. Just like WordPress, it renders both the string as they were not changed.

Here is work around we are using in a package:

if ($old === $new) {
    $diff[$key] = '<table class="diff-wrapper diff diff-html diff-side-by-side"><tbody class="change change-eq"><tr><td class="old">'.$old.'</td><td class="new">'.$new.'</td></tr></tbody></table>';
} else {
    $diff[$key] = str_replace('\n No newline at end of file', '', DiffHelper::calculate($old, $new, $renderer, $differOptions, $renderOptions));
}

Default behaviour of the package is fine. But i wish there is a way to render above by passing a render option maybe?

Make formatting behavior of HTML renderers more flexible

Basically, I'm talking about this:

        if (static::AUTO_FORMAT_CHANGES) {
            $this->formatChanges($changes);
        }

Which then comes to formatStringFromLines which calls $string = $this->htmlSafe($string);.

The thing is, I needed the library to not mutate the original string and not change the symbols to HTML entities. But there's no easy way of changing this behavior. I was using Combined renderer and couldn't override this behavior because the class is final (again - why? there're certainly the cases when you would like to hive slightly different renderer that comes out of the box).

I have a couple of proposals.

  1. Changing static::AUTO_FORMAT_CHANGES to an explicit option for HTML renderers.
  2. All HTML renderers should respect this option.
  3. Make renderer classes not final? Because there're use-cases when you want to override just a part of the behavior and these use-cases are valid.

Erroneous semicolon appearing in combined render

When using the combined rendering type, found a strange bug which causes an extra semicolon to appear in the diff even though it's not there in the input strings.

Narrowed the before/after strings that cause this bug to appear to the following:
Before:

<span><a href="#">Something</a>
</span>

<em><span>Something</span></em>

After:

<a href="#">Something</a>


<em>Something</em>

The options:

$diffOptions   = array(
	'context'          => 5,
	'ignoreWhitespace' => false,
);
$renderOptions = array(
	'detailLevel'   => 'word',
	'separateBlock' => true,
	'language'      => 'eng',
);

The rendered diff output:
Screenshot 2020-04-24 at 15 55 24

Removing the newline between the tags will cause the semicolon position to shift:
Screenshot 2020-04-24 at 16 03 49

display data in html format

Hi ,

Is there any way to display data in html like it shows on a web page.

it must render data as html , img src must display image not the image code.

Thanks
Arvind

Not same comparison result

Hello,
When I run example on my server (PHP Version 8.0.2), I don't get the same result. For example with Combined / Word :

image

Thanks for your help

Antoine

Custom html

Hello,

is it possible to inject custom html for a custom design?

"Context" and "Unified" renderers should handle "No EOL at EOF"

When it involves in "No EOL at EOF", the current diff output can not be successfully applied via GNU patch. The correct result can be generated by GNU diff with

# for Context with extra one line context
# " | tail -n +3" removes those 2 file path headers
$ diff --context=1 old_file.txt new_file.txt | tail -n +3

# for Unified with extra one line context
# " | tail -n +3" removes those 2 file path headers
$ diff --unified=1 old_file.txt new_file.txt | tail -n +3

old_file.txt (no EOL at EOF):

A
B
X

new_file.txt (has EOL at EOF):

A
C
X


Our current outputs (Context):

***************
*** 1,3 ****
  A
! B
  X
--- 1,4 ----
  A
! C
  X
+ 

GNU diff (Context):

***************
*** 1,3 ****
  A
! B
! X
\ No newline at end of file
--- 1,3 ----
  A
! C
! X

Our current outputs (Unified):

@@ -1,3 +1,4 @@
 A
-B
+C
 X
+

GNU diff (Unified):

@@ -1,3 +1,3 @@
 A
-B
-X
\ No newline at end of file
+C
+X

get just the different words?

hi, I am wondering if it's possible to just show the different words, for example:

$s1 = "hello Alice";
$s2 = "hello John";

// diff would show just Allice | John not the full line

I tried using detailLevel=>'word' but it doesn't seem to have this effect

thanks!
dan

JSON renderer sometimes set <ins> and <del> tags into lines

This is an return value example I've got:

[{
    "new": {
        "lines": ["菲灵", "Elmex", "夏依"],
        "offset": 0
    },
    "old": {
        "lines": ["菲灵", "Elmex", "夏依"],
        "offset": 0
    },
    "tag": "eq"
}, {
    "new": {
        "lines": ["<ins>福来恩</ins>"],
        "offset": 3
    },
    "old": {
        "lines": ["<del>百吉福</del>"],
        "offset": 3
    },
    "tag": "rep"
}, {
    "new": {
        "lines": ["乐高"],
        "offset": 4
    },
    "old": {
        "lines": ["乐高"],
        "offset": 4
    },
    "tag": "eq"
}, {
    "new": {
        "lines": [""],
        "offset": 5
    },
    "old": {
        "lines": ["天维美/国内"],
        "offset": 5
    },
    "tag": "del"
}, {
    "new": {
        "lines": ["皇家京东", "九木杂物社淘宝", "网鱼网咖", "味全", "英雄联盟旗舰店"],
        "offset": 5
    },
    "old": {
        "lines": ["皇家京东", "九木杂物社淘宝", "网鱼网咖", "味全", "英雄联盟旗舰店"],
        "offset": 6
    },
    "tag": "eq"
}]

with the following options:

$diffJson = DiffHelper::calculate($old, $new, "Json",
            [
                'context' => 2048
            ],
            [
                'outputTagAsString' => true,
            ]
        );

jfcherng/php-sequence-matcher is private git repo

composer require jfcherng/php-diff
Using version ^6.7 for jfcherng/php-diff
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
    Failed to download jfcherng/php-sequence-matcher from dist: The zip extension and unzip command are both missing, skipping.
The php.ini used by your command-line PHP is: /usr/local/etc/php/conf.d/docker-php-ext-sodium.ini
    Now trying to download from source
  - Installing jfcherng/php-sequence-matcher (3.2.3): Cloning 9468ac6734
Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos
Head to https://github.com/settings/tokens/new?scopes=repo&description=Composer+on+2fca3b3d11cb+2020-06-10+2107
to retrieve a token. It will be stored in "/root/.composer/auth.json" for future use by Composer.
Token (hidden): 

Comparing Html string that contains style

Hi, is there a way to compare correctly for case like this?

I need to compare by word, it will become a problem if the element tag contains different style property. The comparison result will return unnecessary closing tag"/>".

Original

<div>
    <p style="text-align:left;"><span style="color: rgb(32,33,36);font-size: 24px;">Hello World</span></p>
    <p style="text-align:left;"><span style="font-size: 24px;">John Doe</span></p>
</div>

New

<div>
    <p style="text-align:right"><span style="color: rgb(32,33,36);background-color: rgb(248,249,250);font-size: 124px;">Hello World</span></p>
    <p style="text-align:right;"><span style="font-size: 24px;">Maria Doe</span></p>
</div>

Loss of whitespace in combined view with newlines

A very minor style update that was introduced from this issue: #34

Reversing the commit resolved the issue, although I couldn't follow what the parent issue was and I may be overlooking some config setting using it for the first time.

      $rendererName = 'Combined';
      $old = <<<END
parent:
  title: Title
  restrict: true
  callback: true
  url: /demo
  modified: 2023-02-12T07:47:49+10:00
  published: 2020-07-29T10:39:04+10:00
END;
      $new = <<<END
parent:
  title: Title
  restrict: true
  callback: true
  url: /demo
  modified: 2022-05-13T11:05:52+10:00
  published: 2020-07-29T10:39:04+10:00
END;
      $result = DiffHelper::calculate($old, $new, $rendererName);
      print '<div style="border: 1px solid #333; border-radius: 5px; background-color: #eee;">' . $result . '</div>';

screenshot-diff

As an aside, great job forking the old project, it was good to finally to be able to update this project :)

Error with "$new" is empty

Hello, I am getting an error when the variable "$new" comes up empty. Is there any way to fix this?

`
$rendererName = "Combined";

    $differOptions = [
        'context' => 3,
        'ignoreCase' => false,
        'ignoreWhitespace' => true,
    ];

    $rendererOptions = [
        'detailLevel' => 'char',
        'language' => 'rus',
        'lineNumbers' => false,
        'separateBlock' => true,
        'spacesToNbsp' => false,
        'tabSize' => 4,
        'mergeThreshold' => 0.8,
        'resultForIdenticals' => null,
        'wrapperClasses' => ['diff-wrapper'],
    ];

`

File: /var/www/gomer.local/www/vendor/jfcherng/php-sequence-matcher/src/SequenceMatcher.php Line: 244 #0 /var/www/gomer.local/www/vendor/jfcherng/php-sequence-matcher/src/SequenceMatcher.php(244): yii\base\ErrorHandler->handleError(8, 'Undefined offse...', '/var/www/gomer....', 244, Array) #1 /var/www/gomer.local/www/vendor/jfcherng/php-sequence-matcher/src/SequenceMatcher.php(337): Jfcherng\Diff\SequenceMatcher->findLongestMatch(0, 4, 0, 0) #2 /var/www/gomer.local/www/vendor/jfcherng/php-sequence-matcher/src/SequenceMatcher.php(426): Jfcherng\Diff\SequenceMatcher->getMatchingBlocks() #3 /var/www/gomer.local/www/vendor/jfcherng/php-diff/src/Renderer/Html/LineRenderer/AbstractLineRenderer.php(103): Jfcherng\Diff\SequenceMatcher->getOpcodes() #4 /var/www/gomer.local/www/vendor/jfcherng/php-diff/src/Renderer/Html/LineRenderer/Char.php(21): Jfcherng\Diff\Renderer\Html\LineRenderer\AbstractLineRenderer->getChangedExtentSegments(Array, Array) #5 /var/www/gomer.local/www/vendor/jfcherng/php-diff/src/Renderer/Html/AbstractHtml.php(156): Jfcherng\Diff\Renderer\Html\LineRenderer\Char->render(Object(Jfcherng\Utility\MbString), Object(Jfcherng\Utility\MbString)) #6 /var/www/gomer.local/www/vendor/jfcherng/php-diff/src/Renderer/Html/AbstractHtml.php(89): Jfcherng\Diff\Renderer\Html\AbstractHtml->renderChangedExtent(Object(Jfcherng\Diff\Renderer\Html\LineRenderer\Char), '1234', '') #7 /var/www/gomer.local/www/vendor/jfcherng/php-diff/src/Renderer/Html/AbstractHtml.php(113): Jfcherng\Diff\Renderer\Html\AbstractHtml->getChanges(Object(Jfcherng\Diff\Differ)) #8 /var/www/gomer.local/www/vendor/jfcherng/php-diff/src/Renderer/AbstractRenderer.php(172): Jfcherng\Diff\Renderer\Html\AbstractHtml->renderWorker(Object(Jfcherng\Diff\Differ)) #9 /var/www/gomer.local/www/vendor/jfcherng/php-diff/src/DiffHelper.php(134): Jfcherng\Diff\Renderer\AbstractRenderer->render(Object(Jfcherng\Diff\Differ)) #10 /var/www/gomer.local/www/vendor/splitter-modules/market.gomer/common/helpers/StringHelper.php(161): Jfcherng\Diff\DiffHelper::calculate(Array, Array, 'Combined', Array, Array) #11 /var/www/gomer.local/www/vendor/splitter-modules/market.gomer/controllers/ItemsController.php(562): market\gomer\common\helpers\StringHelper::descriptionDiff('&lt;style&gt; ....', '') #12 [internal function]: market\gomer\controllers\ItemsController->actionShowDiff() #13 /var/www/gomer.local/www/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array) #14 /var/www/gomer.local/www/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array) #15 /var/www/gomer.local/www/vendor/yiisoft/yii2/base/Module.php(528): yii\base\Controller->runAction('show-diff', Array) #16 /var/www/gomer.local/www/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction('gomer/items/sho...', Array) #17 /var/www/gomer.local/www/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request)) #18 /var/www/gomer.local/www/backend/web/index.php(22): yii\base\Application->run() #19 {main}

How to show statistic

Hello.
I can not find a way how to get statistic.

Added - 5 lines, deleted - 10 lines, updated - 2 lines, unmodified - 250 lines

Is it possible to read it?

Also can not find a way how to show how many lines is hidden.
'context' => 3, => means how many lines to show before or after changes.
But how to show "1001 Unmodified line(s)" no idea

Thanks

Can't pass custom language array

Hi, I'm having an issue passing in a custom 'Language'. I was following the documentation where it says:

// the renderer class options
$rendererOptions = [
// how detailed the rendered HTML in-line diff is? (none, line, word, char)
'detailLevel' => 'line',
// renderer language: eng, cht, chs, jpn, ...
// or an array which has the same keys with a language file
'language' => 'eng',

I tried passing in an array for the language key, but it threw an error:

Uncaught PHP Exception TypeError: "Argument 2 passed to Jfcherng\Diff\Renderer\AbstractRenderer::updateLanguage() must be of the type string, array given, called in /var/www/api.getastra.com/vendor/jfcherng/php-diff/src/Renderer/AbstractRenderer.php on line 85"

From what I can tell, although the Language constructor accepts and detects a string (for one of the bundled language) or an array (for a custom language), the updateLanguage() method of AbstractRenderer is set to only accept a string as its second parameter. Have I misunderstood how to pass in a custom language, or is this a bug?

Many thanks,
Vidur

Render HTML from JSON

it could be good option to store differences as JSON in database and then convert them into tabular view.

Difference is not rendering properly for 'Combined' rendered

Thank you for making such an awesome package. It's really useful.
I was trying this package today and found one issue when rendering output to the HTML. That's why I am creating an issue here.

Old file

Path:

/folder/old.txt

Content:

This is the old file.
This is the line that is not changed.
I am writing here in the old file.

New file

Path:

/folder/new.txt

Content:

This is the new file.
This is the line that is not changed.
I am writing here in the new file.

What I did

The code that I ran is this. It's the same example from the readme.

$rendererName = 'Combined';
$old = file_get_contents("/folder/old.txt");
$new = file_get_contents("/folder/new.txt");

$jsonResult = DiffHelper::calculate($old, $new, 'Json');
$htmlRenderer = RendererFactory::make($rendererName);
$output = $htmlRenderer->renderArray(json_decode($jsonResult, true));

When rendering the output to the browser, it looks like this:
Screen Shot 2022-06-26 at 4 25 49 AM

But the other $rendererName options works perfectly fine. For example Inline
Screen Shot 2022-06-26 at 4 27 25 AM

New Renderer Suggestion

What does it take to write a renderer to show diffs as in GitHub (see my edit history)? Currently it duplicates the text and doubles the storage volume when storing a JSON output into the database. We might need two renderers for this kind of functionality (one is JSON and the other one is HTML).

[Suggestion] Option to disable the header in HTML renderer

This looks really good, thank you for your work. Just a quick suggestion, would it be possible to add an option to disable the generation of the table header in renderTableHeader() in the HTML renderers? For now I'll just hide it via CSS.

Thanks again.

David

Feedbacks for SideBySide Renderer

I'm getting some feedbacks from users for SideBySide Renderer.

We should merge two equal lines and expand the changed lines over the blank ones on SideBySide Renderer when lineNumbers option set to false because it makes more sense and looks beautiful that way. See samples:

What's now:

now

What should be:

new

Besides, please consider flexbox for v7.

How to return some text when both strings are identicals?

Hi,

First of all, thank you for your efforts to make/continue this extension. But I have a question: I found RendererInterface::getResultForIdenticals() but in SideBySide implementation it returns a '' empty string, SideBySide is a final class so that I can't extend it, so, how could I set a string to show for equal situations?

DetailLevel option seems to be stuck as 'Line'

Setup:

$jsonResult = DiffHelper::calculate($this->data['originalText'], $this->data['correctedText'], 'Json'); 
$htmlRenderer = RendererFactory::make('Combined', $this->getRenderOptions());
$this->data['orgDiff'] = $htmlRenderer->renderArray(json_decode($jsonResult, true));

geRenderOptions()


private function getRenderOptions()
    {
        return [
            // how detailed the rendered HTML in-line diff is? (none, line, word, char)
            'detailLevel' => 'char', // <<<<<------------ char
            // renderer language: eng, cht, chs, jpn, ...
            // or an array which has the same keys with a language file
            // check the "Custom Language" section in the readme for more advanced usage
            'language' => 'eng',
            // show line numbers in HTML renderers
            'lineNumbers' => true,
            // show a separator between different diff hunks in HTML renderers
            'separateBlock' => true,
            // show the (table) header
            'showHeader' => true,
            // the frontend HTML could use CSS "white-space: pre;" to visualize consecutive whitespaces
            // but if you want to visualize them in the backend with "&nbsp;", you can set this to true
            'spacesToNbsp' => false,
            // HTML renderer tab width (negative = do not convert into spaces)
            'tabSize' => 4,
            // this option is currently only for the Combined renderer.
            // it determines whether a replace-type block should be merged or not
            // depending on the content changed ratio, which values between 0 and 1.
            'mergeThreshold' => 0.8,
            // this option is currently only for the Unified and the Context renderers.
            // RendererConstant::CLI_COLOR_AUTO = colorize the output if possible (default)
            // RendererConstant::CLI_COLOR_ENABLE = force to colorize the output
            // RendererConstant::CLI_COLOR_DISABLE = force not to colorize the output
            'cliColorization' => RendererConstant::CLI_COLOR_AUTO,
            // this option is currently only for the Json renderer.
            // internally, ops (tags) are all int type but this is not good for human reading.
            // set this to "true" to convert them into string form before outputting.
            'outputTagAsString' => false,
            // this option is currently only for the Json renderer.
            // it controls how the output JSON is formatted.
            // see available options on https://www.php.net/manual/en/function.json-encode.php
            'jsonEncodeFlags' => \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE,
            // this option is currently effective when the "detailLevel" is "word"
            // characters listed in this array can be used to make diff segments into a whole
            // for example, making "<del>good</del>-<del>looking</del>" into "<del>good-looking</del>"
            // this should bring better readability but set this to empty array if you do not want it
            'wordGlues' => [' ', '-'],
            // change this value to a string as the returned diff if the two input strings are identical
            'resultForIdenticals' => null,
            // extra HTML classes added to the DOM of the diff container
            'wrapperClasses' => ['diff-wrapper'],
        ];

    }

Debug

dd($htmlRenderer->getOptions());

shows DetailLevel = 'char' which is correct however the rendered html is using lines

image

The only change done on this is changing all Hys to hes

Filtering the diff text

Hi, thank you for this amazing library. Works great!

I'm using the SideBySide option. How can I filter the Json and remove certain text before it's displayed? I want to get the result first, filter it, and then display it SideBySide.

$result = DiffHelper::calculateFiles(
$oldFile,
$newFile,
'SideBySide',
$differOptions,
$rendererOptions
);

Thanks!

Changelog

Hi Jack,

as you are the most active developer and you have a very good implementation of php-diff we are using your diff solution in production.

We are using php-diff since November 2018 in Version 2.1.17. I just noticed via composer that you now reached version 4.0.1 and published 23 new releases since. I love updates but for dependency maintenance it's quite a challenge ;-)

As I can not tell if you use semantic versioning (semver) I am afraid to update because updating from v2 to v4 means often breaking changes.

It would help a lot if you would add a changelog to your releases (or to the README) and/or use semantic versioning (so I know I can safely update from e.g. 2.1 to 2.9).

Kind regards and a big thanks for your good work!

Different Line of text not comparing

Hi,

I am trying to compare old text 5 lines and new text 10 lines but the script not return any comparison results. its show no difference. please advice can compare different number of lines both side?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.