MultipleTest.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Parser;
  3. use PhpParser\Error;
  4. use PhpParser\ErrorHandler;
  5. use PhpParser\Lexer;
  6. use PhpParser\Node\Expr;
  7. use PhpParser\Node\Scalar\LNumber;
  8. use PhpParser\Node\Stmt;
  9. use PhpParser\ParserAbstract;
  10. use PhpParser\ParserTest;
  11. class MultipleTest extends ParserTest
  12. {
  13. // This provider is for the generic parser tests, just pick an arbitrary order here
  14. protected function getParser(Lexer $lexer) {
  15. return new Multiple([new Php5($lexer), new Php7($lexer)]);
  16. }
  17. private function getPrefer7() {
  18. $lexer = new Lexer(['usedAttributes' => []]);
  19. return new Multiple([new Php7($lexer), new Php5($lexer)]);
  20. }
  21. private function getPrefer5() {
  22. $lexer = new Lexer(['usedAttributes' => []]);
  23. return new Multiple([new Php5($lexer), new Php7($lexer)]);
  24. }
  25. /** @dataProvider provideTestParse */
  26. public function testParse($code, Multiple $parser, $expected) {
  27. $this->assertEquals($expected, $parser->parse($code));
  28. }
  29. public function provideTestParse() {
  30. return [
  31. [
  32. // PHP 7 only code
  33. '<?php class Test { function function() {} }',
  34. $this->getPrefer5(),
  35. [
  36. new Stmt\Class_('Test', ['stmts' => [
  37. new Stmt\ClassMethod('function')
  38. ]]),
  39. ]
  40. ],
  41. [
  42. // PHP 5 only code
  43. '<?php global $$a->b;',
  44. $this->getPrefer7(),
  45. [
  46. new Stmt\Global_([
  47. new Expr\Variable(new Expr\PropertyFetch(new Expr\Variable('a'), 'b'))
  48. ])
  49. ]
  50. ],
  51. [
  52. // Different meaning (PHP 5)
  53. '<?php $$a[0];',
  54. $this->getPrefer5(),
  55. [
  56. new Stmt\Expression(new Expr\Variable(
  57. new Expr\ArrayDimFetch(new Expr\Variable('a'), LNumber::fromString('0'))
  58. ))
  59. ]
  60. ],
  61. [
  62. // Different meaning (PHP 7)
  63. '<?php $$a[0];',
  64. $this->getPrefer7(),
  65. [
  66. new Stmt\Expression(new Expr\ArrayDimFetch(
  67. new Expr\Variable(new Expr\Variable('a')), LNumber::fromString('0')
  68. ))
  69. ]
  70. ],
  71. ];
  72. }
  73. public function testThrownError() {
  74. $this->expectException(Error::class);
  75. $this->expectExceptionMessage('FAIL A');
  76. $parserA = new class implements \PhpParser\Parser {
  77. public function parse(string $code, ErrorHandler $errorHandler = null) {
  78. throw new Error('FAIL A');
  79. }
  80. };
  81. $parserB = new class implements \PhpParser\Parser {
  82. public function parse(string $code, ErrorHandler $errorHandler = null) {
  83. throw new Error('FAIL B');
  84. }
  85. };
  86. $parser = new Multiple([$parserA, $parserB]);
  87. $parser->parse('dummy');
  88. }
  89. }