AbstractParserTest.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace JMS\Parser\Tests;
  3. class AbstractParserTest extends \PHPUnit_Framework_TestCase
  4. {
  5. const T_UNKNOWN = 0;
  6. const T_INT = 1;
  7. const T_PLUS = 100;
  8. const T_MINUS = 101;
  9. private $parser;
  10. private $lexer;
  11. public function testParse()
  12. {
  13. $this->assertSame(2, $this->parser->parse('1 + 1'));
  14. $this->assertSame(5, $this->parser->parse('1 + 1 + 4 - 1'));
  15. }
  16. /**
  17. * @expectedException JMS\Parser\SyntaxErrorException
  18. * @expectedExceptionMessage Expected T_INT, but got end of input.
  19. */
  20. public function testUnexpectedEnd()
  21. {
  22. $this->parser->parse('1 + ');
  23. }
  24. protected function setUp()
  25. {
  26. $this->lexer = $lexer = new \JMS\Parser\SimpleLexer(
  27. '/([0-9]+)|\s+|(.)/',
  28. array(0 => 'T_UNKNOWN', 1 => 'T_INT', 100 => 'T_PLUS', 101 => 'T_MINUS'),
  29. function($value) {
  30. if ('+' === $value) {
  31. return array(AbstractParserTest::T_PLUS, $value);
  32. }
  33. if ('-' === $value) {
  34. return array(AbstractParserTest::T_MINUS, $value);
  35. }
  36. // We would loose information on doubles here, but for this test it
  37. // does not matter anyway.
  38. if (is_numeric($value)) {
  39. return array(AbstractParserTest::T_INT, (integer) $value);
  40. }
  41. return AbstractParserTest::T_UNKNOWN;
  42. }
  43. );
  44. $this->parser = $parser = $this->getMockBuilder('JMS\Parser\AbstractParser')
  45. ->setConstructorArgs(array($this->lexer))
  46. ->getMockForAbstractClass();
  47. $match = function($type) use ($parser) {
  48. $ref = new \ReflectionMethod($parser, 'match');
  49. $ref->setAccessible(true);
  50. return $ref->invoke($parser, $type);
  51. };
  52. $this->parser->expects($this->any())
  53. ->method('parseInternal')
  54. ->will($this->returnCallback(function() use ($lexer, $match) {
  55. // Result :== Number ( ("+"|"-") Number )*
  56. $result = $match(AbstractParserTest::T_INT);
  57. while ($lexer->isNextAny(array(AbstractParserTest::T_PLUS, AbstractParserTest::T_MINUS))) {
  58. if ($lexer->isNext(AbstractParserTest::T_PLUS)) {
  59. $lexer->moveNext();
  60. $result += $match(AbstractParserTest::T_INT);
  61. } else if ($lexer->isNext(AbstractParserTest::T_MINUS)) {
  62. $lexer->moveNext();
  63. $result -= $match(AbstractParserTest::T_INT);
  64. } else {
  65. throw new \LogicException('Previous ifs were exhaustive.');
  66. }
  67. }
  68. return $result;
  69. }));
  70. }
  71. }