AbstractChunkOutputBuilder.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. abstract class AbstractChunkOutputBuilder implements DiffOutputBuilderInterface
  12. {
  13. /**
  14. * Takes input of the diff array and returns the common parts.
  15. * Iterates through diff line by line.
  16. *
  17. * @param array $diff
  18. * @param int $lineThreshold
  19. *
  20. * @return array
  21. */
  22. protected function getCommonChunks(array $diff, int $lineThreshold = 5): array
  23. {
  24. $diffSize = \count($diff);
  25. $capturing = false;
  26. $chunkStart = 0;
  27. $chunkSize = 0;
  28. $commonChunks = [];
  29. for ($i = 0; $i < $diffSize; ++$i) {
  30. if ($diff[$i][1] === 0 /* OLD */) {
  31. if ($capturing === false) {
  32. $capturing = true;
  33. $chunkStart = $i;
  34. $chunkSize = 0;
  35. } else {
  36. ++$chunkSize;
  37. }
  38. } elseif ($capturing !== false) {
  39. if ($chunkSize >= $lineThreshold) {
  40. $commonChunks[$chunkStart] = $chunkStart + $chunkSize;
  41. }
  42. $capturing = false;
  43. }
  44. }
  45. if ($capturing !== false && $chunkSize >= $lineThreshold) {
  46. $commonChunks[$chunkStart] = $chunkStart + $chunkSize;
  47. }
  48. return $commonChunks;
  49. }
  50. }