StringTest.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Node\Scalar;
  3. use PhpParser\Node\Stmt\Echo_;
  4. use PhpParser\ParserFactory;
  5. class StringTest extends \PHPUnit\Framework\TestCase
  6. {
  7. public function testRawValue()
  8. {
  9. $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
  10. $nodes = $parser->parse('<?php echo "sequence \x41";');
  11. $echo = $nodes[0];
  12. $this->assertInstanceOf(Echo_::class, $echo);
  13. /** @var Echo_ $echo */
  14. $string = $echo->exprs[0];
  15. $this->assertInstanceOf(String_::class, $string);
  16. /** @var String_ $string */
  17. $this->assertSame('sequence A', $string->value);
  18. $this->assertSame('"sequence \\x41"', $string->getAttribute('rawValue'));
  19. }
  20. /**
  21. * @dataProvider provideTestParseEscapeSequences
  22. */
  23. public function testParseEscapeSequences($expected, $string, $quote) {
  24. $this->assertSame(
  25. $expected,
  26. String_::parseEscapeSequences($string, $quote)
  27. );
  28. }
  29. /**
  30. * @dataProvider provideTestParse
  31. */
  32. public function testCreate($expected, $string) {
  33. $this->assertSame(
  34. $expected,
  35. String_::parse($string)
  36. );
  37. }
  38. public function provideTestParseEscapeSequences() {
  39. return [
  40. ['"', '\\"', '"'],
  41. ['\\"', '\\"', '`'],
  42. ['\\"\\`', '\\"\\`', null],
  43. ["\\\$\n\r\t\f\v", '\\\\\$\n\r\t\f\v', null],
  44. ["\x1B", '\e', null],
  45. [chr(255), '\xFF', null],
  46. [chr(255), '\377', null],
  47. [chr(0), '\400', null],
  48. ["\0", '\0', null],
  49. ['\xFF', '\\\\xFF', null],
  50. ];
  51. }
  52. public function provideTestParse() {
  53. $tests = [
  54. ['A', '\'A\''],
  55. ['A', 'b\'A\''],
  56. ['A', '"A"'],
  57. ['A', 'b"A"'],
  58. ['\\', '\'\\\\\''],
  59. ['\'', '\'\\\'\''],
  60. ];
  61. foreach ($this->provideTestParseEscapeSequences() as $i => $test) {
  62. // skip second and third tests, they aren't for double quotes
  63. if ($i !== 1 && $i !== 2) {
  64. $tests[] = [$test[0], '"' . $test[1] . '"'];
  65. }
  66. }
  67. return $tests;
  68. }
  69. }