DiffOnlyOutputBuilder.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of sebastian/diff.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\Diff\Output;
  11. use function fclose;
  12. use function fopen;
  13. use function fwrite;
  14. use function str_ends_with;
  15. use function stream_get_contents;
  16. use function substr;
  17. use SebastianBergmann\Diff\Differ;
  18. /**
  19. * Builds a diff string representation in a loose unified diff format
  20. * listing only changes lines. Does not include line numbers.
  21. */
  22. final class DiffOnlyOutputBuilder implements DiffOutputBuilderInterface
  23. {
  24. private string $header;
  25. public function __construct(string $header = "--- Original\n+++ New\n")
  26. {
  27. $this->header = $header;
  28. }
  29. public function getDiff(array $diff): string
  30. {
  31. $buffer = fopen('php://memory', 'r+b');
  32. if ('' !== $this->header) {
  33. fwrite($buffer, $this->header);
  34. if (!str_ends_with($this->header, "\n")) {
  35. fwrite($buffer, "\n");
  36. }
  37. }
  38. foreach ($diff as $diffEntry) {
  39. if ($diffEntry[1] === Differ::ADDED) {
  40. fwrite($buffer, '+' . $diffEntry[0]);
  41. } elseif ($diffEntry[1] === Differ::REMOVED) {
  42. fwrite($buffer, '-' . $diffEntry[0]);
  43. } elseif ($diffEntry[1] === Differ::DIFF_LINE_END_WARNING) {
  44. fwrite($buffer, ' ' . $diffEntry[0]);
  45. continue; // Warnings should not be tested for line break, it will always be there
  46. } else { /* Not changed (old) 0 */
  47. continue; // we didn't write the not-changed line, so do not add a line break either
  48. }
  49. $lc = substr($diffEntry[0], -1);
  50. if ($lc !== "\n" && $lc !== "\r") {
  51. fwrite($buffer, "\n"); // \No newline at end of file
  52. }
  53. }
  54. $diff = stream_get_contents($buffer, -1, 0);
  55. fclose($buffer);
  56. return $diff;
  57. }
  58. }