TypeParser.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace JMS\SerializerBundle\Serializer;
  3. /**
  4. * Parses a serializer type.
  5. *
  6. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  7. */
  8. final class TypeParser extends \JMS\Parser\AbstractParser
  9. {
  10. const T_NAME = 1;
  11. const T_STRING = 2;
  12. const T_OPEN_BRACKET = 3;
  13. const T_CLOSE_BRACKET = 4;
  14. const T_COMMA = 5;
  15. const T_NONE = 6;
  16. public function __construct()
  17. {
  18. parent::__construct(new \JMS\Parser\SimpleLexer(
  19. '/
  20. # PHP Class Names
  21. ((?:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\\\\)*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)
  22. # Strings
  23. |("(?:[^"]|"")*"|\'(?:[^\']|\'\')*\')
  24. # Ignore whitespace
  25. |\s*
  26. # Terminals
  27. |(.)
  28. /x',
  29. array(self::T_NAME => 'T_NAME', self::T_STRING => 'T_STRING', self::T_OPEN_BRACKET => 'T_OPEN_BRACKET',
  30. self::T_CLOSE_BRACKET => 'T_CLOSE_BRACKET', self::T_COMMA => 'T_COMMA', self::T_NONE => 'T_NONE'),
  31. function($value) {
  32. switch ($value[0]) {
  33. case '"':
  34. case "'":
  35. return array(TypeParser::T_STRING, substr($value, 1, -1));
  36. case '<':
  37. return array(TypeParser::T_OPEN_BRACKET, '<');
  38. case '>':
  39. return array(TypeParser::T_CLOSE_BRACKET, '>');
  40. case ',':
  41. return array(TypeParser::T_COMMA, ',');
  42. default:
  43. if (preg_match('/^(?:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\\\\)*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $value)) {
  44. return array(TypeParser::T_NAME, $value);
  45. }
  46. return array(TypeParser::T_NONE, $value);
  47. }
  48. }
  49. ));
  50. }
  51. /**
  52. * @return array of the format ["name" => string, "params" => array]
  53. */
  54. protected function parseInternal()
  55. {
  56. $typeName = $this->match(self::T_NAME);
  57. if ( ! $this->lexer->isNext(self::T_OPEN_BRACKET)) {
  58. return array('name' => $typeName, 'params' => array());
  59. }
  60. $this->match(self::T_OPEN_BRACKET);
  61. $params = array();
  62. do {
  63. if ($this->lexer->isNext(self::T_NAME)) {
  64. $params[] = $this->parseInternal();
  65. } else if ($this->lexer->isNext(self::T_STRING)) {
  66. $params[] = $this->match(self::T_STRING);
  67. } else {
  68. $this->matchAny(array(self::T_NAME, self::T_STRING)); // Will throw an exception.
  69. }
  70. } while ($this->lexer->isNext(self::T_COMMA) && $this->lexer->moveNext());
  71. $this->match(self::T_CLOSE_BRACKET);
  72. return array('name' => $typeName, 'params' => $params);
  73. }
  74. }