JsonDecoderTest.php 1.3 KB

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