MultipleTest.php 3.0 KB

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