DifferTest.php 2.3 KB

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