StringTest.php 2.4 KB

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