Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Diff Laravel Package

jfcherng/php-diff

PHP library to generate diffs between two strings with multiple renderers: unified/context/text, JSON, and rich HTML (inline, side-by-side, combined). Includes helper CSS (or your own) and customizable differ/renderer options. Requires PHP 8.3+ and ext-iconv.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jfcherng/php-diff
    

    Ensure PHP ≥ 8.3.0 and the iconv extension are enabled.

  2. First Use Case: Compare two strings with the default Unified renderer:

    use Jfcherng\Diff\DiffHelper;
    
    $old = "Hello world!";
    $new = "Hi there!";
    $diff = DiffHelper::calculate($old, $new);
    echo $diff;
    
  3. Key Entry Points:

    • DiffHelper::calculate() – Quick string comparison.
    • DiffHelper::calculateFiles() – Compare file contents.
    • Differ + RendererFactory – Custom workflows.

Implementation Patterns

Core Workflow

  1. String Comparison:

    $diff = DiffHelper::calculate($oldText, $newText, 'Inline', $differOptions, $rendererOptions);
    
    • Use Unified for CLI tools, Inline/SideBySide for web UIs.
  2. File Comparison:

    $diff = DiffHelper::calculateFiles('old.txt', 'new.txt', 'Context');
    
  3. Custom Rendering:

    $differ = new Differ(explode("\n", $old), explode("\n", $new), $differOptions);
    $renderer = RendererFactory::make('Combined', $rendererOptions);
    $htmlDiff = $renderer->render($differ);
    

Laravel Integration

  1. Blade Templates:

    // In a controller
    $diff = DiffHelper::calculate($old, $new, 'SideBySide');
    return view('diff.view', ['diff' => $diff]);
    
    // In Blade
    <div class="diff-container">
        {!! $diff !!}
        @include('diff-table.css') <!-- Include CSS -->
    </div>
    
  2. API Responses:

    return response()->json([
        'diff' => DiffHelper::calculate($old, $new, 'JsonText')
    ]);
    
  3. Service Layer:

    // app/Services/DiffService.php
    class DiffService {
        public function generateDiff(string $old, string $new, string $format = 'Unified'): string {
            return DiffHelper::calculate($old, $new, $format);
        }
    }
    

Advanced Patterns

  1. JSON Storage:

    $jsonDiff = DiffHelper::calculate($old, $new, 'Json');
    // Store $jsonDiff in DB for later HTML rendering
    
  2. Dynamic Renderers:

    $rendererName = request()->input('renderer', 'Inline');
    $diff = DiffHelper::calculate($old, $new, $rendererName);
    
  3. Line-Level Granularity:

    $differOptions = new DifferOptions(context: 5, detailLevel: 'line');
    

Gotchas and Tips

Pitfalls

  1. HTML Renderers Require CSS:

    • Always include diff-table.css or use DiffHelper::getStyleSheet().
    • Example:
      <style>{!! \Jfcherng\Diff\DiffHelper::getStyleSheet() !!}</style>
      
  2. Case Sensitivity:

    • Default ignoreCase: false treats Hellohello. Set ignoreCase: true for case-insensitive diffs.
  3. Performance with Large Files:

    • Use lengthLimit in DifferOptions to avoid memory issues:
      $differOptions = new DifferOptions(lengthLimit: 10000);
      
  4. Line Endings:

    • ignoreLineEnding: true merges \n/\r\n differences. Disable for strict comparisons.
  5. JSON Renderers:

    • JsonHtml vs. JsonText: Use JsonHtml for inline HTML diffs, JsonText for plain JSON.

Debugging Tips

  1. Validate Inputs:

    • Ensure inputs are strings or file paths. Files must be readable.
  2. Check Renderer Names:

    • Valid names: Unified, Inline, SideBySide, Combined, Context, Json, JsonHtml.
    • Case-sensitive! Use RendererConstant for constants.
  3. Debugging Custom Renderers:

    • Extend \Jfcherng\Diff\Renderer\AbstractRenderer for custom logic:
      class CustomRenderer extends AbstractRenderer {
          protected function renderLine(...): string { ... }
      }
      
  4. Whitespace Handling:

    • ignoreWhitespace: true hides space/tab changes. Useful for code diffs but may mask issues.

Extension Points

  1. Custom Languages:

    • Override translations via language option:
      $rendererOptions = new RendererOptions(language: ['added' => '✅ Added']);
      
  2. Post-Processing:

    • Parse Json output to highlight changes in a custom UI:
      $jsonDiff = json_decode(DiffHelper::calculate($old, $new, 'Json'), true);
      // Process $jsonDiff['tag'] (e.g., 'del', 'ins', 'rep')
      
  3. CLI Colorization:

    • Force colors with:
      $rendererOptions = new RendererOptions(cliColorization: RendererConstant::CLI_COLOR_ENABLE);
      
  4. Tab Handling:

    • Control tab visualization with tabSize (negative = preserve tabs):
      $rendererOptions = new RendererOptions(tabSize: -1); // Keep tabs as-is
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle