JsonDecoderTest.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. class JsonDecoderTest extends \PHPUnit\Framework\TestCase {
  4. public function testRoundTrip(): void {
  5. $code = <<<'PHP'
  6. <?php
  7. // comment
  8. /** doc comment */
  9. function functionName(&$a = 0, $b = 1.0) {
  10. echo 'Foo';
  11. }
  12. PHP;
  13. $parser = new Parser\Php7(new Lexer());
  14. $stmts = $parser->parse($code);
  15. $json = json_encode($stmts);
  16. $jsonDecoder = new JsonDecoder();
  17. $decodedStmts = $jsonDecoder->decode($json);
  18. $this->assertEquals($stmts, $decodedStmts);
  19. }
  20. /** @dataProvider provideTestDecodingError */
  21. public function testDecodingError($json, $expectedMessage): void {
  22. $jsonDecoder = new JsonDecoder();
  23. $this->expectException(\RuntimeException::class);
  24. $this->expectExceptionMessage($expectedMessage);
  25. $jsonDecoder->decode($json);
  26. }
  27. public static function provideTestDecodingError() {
  28. return [
  29. ['???', 'JSON decoding error: Syntax error'],
  30. ['{"nodeType":123}', 'Node type must be a string'],
  31. ['{"nodeType":"Name","attributes":123}', 'Attributes must be an array'],
  32. ['{"nodeType":"Comment"}', 'Comment must have text'],
  33. ['{"nodeType":"xxx"}', 'Unknown node type "xxx"'],
  34. ];
  35. }
  36. }