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