DifferTest.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Internal;
  3. class DifferTest extends \PHPUnit\Framework\TestCase {
  4. private function formatDiffString(array $diff) {
  5. $diffStr = '';
  6. foreach ($diff as $diffElem) {
  7. switch ($diffElem->type) {
  8. case DiffElem::TYPE_KEEP:
  9. $diffStr .= $diffElem->old;
  10. break;
  11. case DiffElem::TYPE_REMOVE:
  12. $diffStr .= '-' . $diffElem->old;
  13. break;
  14. case DiffElem::TYPE_ADD:
  15. $diffStr .= '+' . $diffElem->new;
  16. break;
  17. case DiffElem::TYPE_REPLACE:
  18. $diffStr .= '/' . $diffElem->old . $diffElem->new;
  19. break;
  20. default:
  21. assert(false);
  22. break;
  23. }
  24. }
  25. return $diffStr;
  26. }
  27. /** @dataProvider provideTestDiff */
  28. public function testDiff($oldStr, $newStr, $expectedDiffStr): void {
  29. $differ = new Differ(function ($a, $b) {
  30. return $a === $b;
  31. });
  32. $diff = $differ->diff(str_split($oldStr), str_split($newStr));
  33. $this->assertSame($expectedDiffStr, $this->formatDiffString($diff));
  34. }
  35. public static function provideTestDiff() {
  36. return [
  37. ['abc', 'abc', 'abc'],
  38. ['abc', 'abcdef', 'abc+d+e+f'],
  39. ['abcdef', 'abc', 'abc-d-e-f'],
  40. ['abcdef', 'abcxyzdef', 'abc+x+y+zdef'],
  41. ['axyzb', 'ab', 'a-x-y-zb'],
  42. ['abcdef', 'abxyef', 'ab-c-d+x+yef'],
  43. ['abcdef', 'cdefab', '-a-bcdef+a+b'],
  44. ];
  45. }
  46. /** @dataProvider provideTestDiffWithReplacements */
  47. public function testDiffWithReplacements($oldStr, $newStr, $expectedDiffStr): void {
  48. $differ = new Differ(function ($a, $b) {
  49. return $a === $b;
  50. });
  51. $diff = $differ->diffWithReplacements(str_split($oldStr), str_split($newStr));
  52. $this->assertSame($expectedDiffStr, $this->formatDiffString($diff));
  53. }
  54. public static function provideTestDiffWithReplacements() {
  55. return [
  56. ['abcde', 'axyze', 'a/bx/cy/dze'],
  57. ['abcde', 'xbcdy', '/axbcd/ey'],
  58. ['abcde', 'axye', 'a-b-c-d+x+ye'],
  59. ['abcde', 'axyzue', 'a-b-c-d+x+y+z+ue'],
  60. ];
  61. }
  62. public function testNonContiguousIndices(): void {
  63. $differ = new Differ(function ($a, $b) {
  64. return $a === $b;
  65. });
  66. $diff = $differ->diff([0 => 'a', 2 => 'b'], [0 => 'a', 3 => 'b']);
  67. $this->assertEquals([
  68. new DiffElem(DiffElem::TYPE_KEEP, 'a', 'a'),
  69. new DiffElem(DiffElem::TYPE_KEEP, 'b', 'b'),
  70. ], $diff);
  71. }
  72. }