JsonDecoderTest.php 1.3 KB

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