sebastian/diff Documentation

repository·main·Indexed 27 days ago

https://github.com/sebastianbergmann/diff

A standalone PHP component for generating and parsing textual diffs. It includes the Differ class for generating differences via various output builders like UnifiedDiffOutputBuilder and DiffOnlyOutputBuilder, and the Parser class for converting unified diff strings into an object graph of Diff, Chunk, and Line objects.

Tokens
570
Snippets
3
Records
3
Agent score
43%

What's inside sebastian/diff

  1. Install sebastian/diff via Composer

    main

    You can add this library to your project using Composer.

    To add it as a local, per-project dependency:

    composer require sebastian/diff

    To add it as a development-time dependency (e.g., for running test suites):

    composer require --dev sebastian/diff
  2. Generate textual diffs using the Differ class

    main

    The SebastianBergmann\Diff\Differ class generates a textual representation of the difference between two strings. It requires an implementation of DiffOutputBuilderInterface passed to its constructor.

    Available Output Builders:

    • UnifiedDiffOutputBuilder: Generates output in "unified diff" format (used by PHPUnit).
    • StrictUnifiedDiffOutputBuilder: Generates "strict unified diff" format with hunks, compatible with patch or git apply.
    • DiffOnlyOutputBuilder: Generates output containing only the lines that differ.
    • Custom Builders: You can implement DiffOutputBuilderInterface to create your own format.

    To implement a custom format, implement the SebastianBergmann\Diff\Output\DiffOutputBuilderInterface.

    <?php declare(strict_types=1);
    use SebastianBergmann\Diff\Differ;
    use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
    
    $differ = new Differ(new UnifiedDiffOutputBuilder);
    
    print $differ->diff('foo', 'bar');
  3. Parse unified diffs using the Parser class

    main

    The SebastianBergmann\Diff\Parser class can parse a unified diff string into an object graph consisting of Diff, Chunk, and Line objects.

    Note on line numbers: If a chunk size is 0 lines (i.e., getStartRange() or getEndRange() return 0), the value returned by getStart() or getEnd() is the line number after which the chunk should be inserted or deleted. In all other cases, it represents the first line number of the replaced range.

    use SebastianBergmann\Diff\Parser;
    // Assuming $diff is a string containing a unified diff
    
    $parser = new Parser;
    print_r($parser->parse($diff));