UnifiedDiffer.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Differ;
  13. use PhpCsFixer\Preg;
  14. use SebastianBergmann\Diff\Differ;
  15. use SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder;
  16. final class UnifiedDiffer implements DifferInterface
  17. {
  18. public function diff(string $old, string $new, ?\SplFileInfo $file = null): string
  19. {
  20. if (null === $file) {
  21. $options = [
  22. 'fromFile' => 'Original',
  23. 'toFile' => 'New',
  24. ];
  25. } else {
  26. $filePath = $file->getRealPath();
  27. if (Preg::match('/\s/', $filePath)) {
  28. $filePath = '"'.$filePath.'"';
  29. }
  30. $options = [
  31. 'fromFile' => $filePath,
  32. 'toFile' => $filePath,
  33. ];
  34. }
  35. $differ = new Differ(new StrictUnifiedDiffOutputBuilder($options));
  36. return $differ->diff($old, $new);
  37. }
  38. }