DifferTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Internal;
  3. use PHPUnit\Framework\TestCase;
  4. class DifferTest extends TestCase
  5. {
  6. private function formatDiffString(array $diff) {
  7. $diffStr = '';
  8. foreach ($diff as $diffElem) {
  9. switch ($diffElem->type) {
  10. case DiffElem::TYPE_KEEP:
  11. $diffStr .= $diffElem->old;
  12. break;
  13. case DiffElem::TYPE_REMOVE:
  14. $diffStr .= '-' . $diffElem->old;
  15. break;
  16. case DiffElem::TYPE_ADD:
  17. $diffStr .= '+' . $diffElem->new;
  18. break;
  19. case DiffElem::TYPE_REPLACE:
  20. $diffStr .= '/' . $diffElem->old . $diffElem->new;
  21. break;
  22. default:
  23. assert(false);
  24. break;
  25. }
  26. }
  27. return $diffStr;
  28. }
  29. /** @dataProvider provideTestDiff */
  30. public function testDiff($oldStr, $newStr, $expectedDiffStr) {
  31. $differ = new Differ(function($a, $b) { return $a === $b; });
  32. $diff = $differ->diff(str_split($oldStr), str_split($newStr));
  33. $this->assertSame($expectedDiffStr, $this->formatDiffString($diff));
  34. }
  35. public 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) {
  48. $differ = new Differ(function($a, $b) { return $a === $b; });
  49. $diff = $differ->diffWithReplacements(str_split($oldStr), str_split($newStr));
  50. $this->assertSame($expectedDiffStr, $this->formatDiffString($diff));
  51. }
  52. public function provideTestDiffWithReplacements() {
  53. return [
  54. ['abcde', 'axyze', 'a/bx/cy/dze'],
  55. ['abcde', 'xbcdy', '/axbcd/ey'],
  56. ['abcde', 'axye', 'a-b-c-d+x+ye'],
  57. ['abcde', 'axyzue', 'a-b-c-d+x+y+z+ue'],
  58. ];
  59. }
  60. }