View source
<?php
namespace Doctrine\Common\Annotations;
use Doctrine\Common\Annotations\Annotation\Attribute;
use ReflectionClass;
use Doctrine\Common\Annotations\Annotation\Enum;
use Doctrine\Common\Annotations\Annotation\Target;
use Doctrine\Common\Annotations\Annotation\Attributes;
final class DocParser {
private static $classIdentifiers = array(
DocLexer::T_IDENTIFIER,
DocLexer::T_TRUE,
DocLexer::T_FALSE,
DocLexer::T_NULL,
);
private $lexer;
private $target;
private static $metadataParser;
private $isNestedAnnotation = false;
private $imports = array();
private $classExists = array();
private $ignoreNotImportedAnnotations = false;
private $namespaces = array();
private $ignoredAnnotationNames = array();
private $context = '';
private static $annotationMetadata = array(
'Doctrine\\Common\\Annotations\\Annotation\\Target' => array(
'is_annotation' => true,
'has_constructor' => true,
'properties' => array(),
'targets_literal' => 'ANNOTATION_CLASS',
'targets' => Target::TARGET_CLASS,
'default_property' => 'value',
'attribute_types' => array(
'value' => array(
'required' => false,
'type' => 'array',
'array_type' => 'string',
'value' => 'array<string>',
),
),
),
'Doctrine\\Common\\Annotations\\Annotation\\Attribute' => array(
'is_annotation' => true,
'has_constructor' => false,
'targets_literal' => 'ANNOTATION_ANNOTATION',
'targets' => Target::TARGET_ANNOTATION,
'default_property' => 'name',
'properties' => array(
'name' => 'name',
'type' => 'type',
'required' => 'required',
),
'attribute_types' => array(
'value' => array(
'required' => true,
'type' => 'string',
'value' => 'string',
),
'type' => array(
'required' => true,
'type' => 'string',
'value' => 'string',
),
'required' => array(
'required' => false,
'type' => 'boolean',
'value' => 'boolean',
),
),
),
'Doctrine\\Common\\Annotations\\Annotation\\Attributes' => array(
'is_annotation' => true,
'has_constructor' => false,
'targets_literal' => 'ANNOTATION_CLASS',
'targets' => Target::TARGET_CLASS,
'default_property' => 'value',
'properties' => array(
'value' => 'value',
),
'attribute_types' => array(
'value' => array(
'type' => 'array',
'required' => true,
'array_type' => 'Doctrine\\Common\\Annotations\\Annotation\\Attribute',
'value' => 'array<Doctrine\\Common\\Annotations\\Annotation\\Attribute>',
),
),
),
'Doctrine\\Common\\Annotations\\Annotation\\Enum' => array(
'is_annotation' => true,
'has_constructor' => true,
'targets_literal' => 'ANNOTATION_PROPERTY',
'targets' => Target::TARGET_PROPERTY,
'default_property' => 'value',
'properties' => array(
'value' => 'value',
),
'attribute_types' => array(
'value' => array(
'type' => 'array',
'required' => true,
),
'literal' => array(
'type' => 'array',
'required' => false,
),
),
),
);
private static $typeMap = array(
'float' => 'double',
'bool' => 'boolean',
'Boolean' => 'boolean',
'int' => 'integer',
);
public function __construct() {
$this->lexer = new DocLexer();
}
public function setIgnoredAnnotationNames(array $names) {
$this->ignoredAnnotationNames = $names;
}
public function setIgnoreNotImportedAnnotations($bool) {
$this->ignoreNotImportedAnnotations = (bool) $bool;
}
public function addNamespace($namespace) {
if ($this->imports) {
throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
}
$this->namespaces[] = $namespace;
}
public function setImports(array $imports) {
if ($this->namespaces) {
throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
}
$this->imports = $imports;
}
public function setTarget($target) {
$this->target = $target;
}
public function parse($input, $context = '') {
$pos = $this
->findInitialTokenPosition($input);
if ($pos === null) {
return array();
}
$this->context = $context;
$this->lexer
->setInput(trim(substr($input, $pos), '* /'));
$this->lexer
->moveNext();
return $this
->Annotations();
}
private function findInitialTokenPosition($input) {
$pos = 0;
while (($pos = strpos($input, '@', $pos)) !== false) {
if ($pos === 0 || $input[$pos - 1] === ' ' || $input[$pos - 1] === '*') {
return $pos;
}
$pos++;
}
return null;
}
private function match($token) {
if (!$this->lexer
->isNextToken($token)) {
$this
->syntaxError($this->lexer
->getLiteral($token));
}
return $this->lexer
->moveNext();
}
private function matchAny(array $tokens) {
if (!$this->lexer
->isNextTokenAny($tokens)) {
$this
->syntaxError(implode(' or ', array_map(array(
$this->lexer,
'getLiteral',
), $tokens)));
}
return $this->lexer
->moveNext();
}
private function syntaxError($expected, $token = null) {
if ($token === null) {
$token = $this->lexer->lookahead;
}
$message = sprintf('Expected %s, got ', $expected);
$message .= $this->lexer->lookahead === null ? 'end of string' : sprintf("'%s' at position %s", $token['value'], $token['position']);
if (strlen($this->context)) {
$message .= ' in ' . $this->context;
}
$message .= '.';
throw AnnotationException::syntaxError($message);
}
private function classExists($fqcn) {
if (isset($this->classExists[$fqcn])) {
return $this->classExists[$fqcn];
}
if (class_exists($fqcn, false)) {
return $this->classExists[$fqcn] = true;
}
return $this->classExists[$fqcn] = AnnotationRegistry::loadAnnotationClass($fqcn);
}
private function collectAnnotationMetadata($name) {
if (self::$metadataParser === null) {
self::$metadataParser = new self();
self::$metadataParser
->setIgnoreNotImportedAnnotations(true);
self::$metadataParser
->setIgnoredAnnotationNames($this->ignoredAnnotationNames);
self::$metadataParser
->setImports(array(
'enum' => 'Doctrine\\Common\\Annotations\\Annotation\\Enum',
'target' => 'Doctrine\\Common\\Annotations\\Annotation\\Target',
'attribute' => 'Doctrine\\Common\\Annotations\\Annotation\\Attribute',
'attributes' => 'Doctrine\\Common\\Annotations\\Annotation\\Attributes',
));
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Enum.php');
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Target.php');
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Attribute.php');
AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Attributes.php');
}
$class = new \ReflectionClass($name);
$docComment = $class
->getDocComment();
$metadata = array(
'default_property' => null,
'has_constructor' => null !== ($constructor = $class
->getConstructor()) && $constructor
->getNumberOfParameters() > 0,
'properties' => array(),
'property_types' => array(),
'attribute_types' => array(),
'targets_literal' => null,
'targets' => Target::TARGET_ALL,
'is_annotation' => false !== strpos($docComment, '@Annotation'),
);
if ($metadata['is_annotation']) {
self::$metadataParser
->setTarget(Target::TARGET_CLASS);
foreach (self::$metadataParser
->parse($docComment, 'class @' . $name) as $annotation) {
if ($annotation instanceof Target) {
$metadata['targets'] = $annotation->targets;
$metadata['targets_literal'] = $annotation->literal;
continue;
}
if ($annotation instanceof Attributes) {
foreach ($annotation->value as $attribute) {
$this
->collectAttributeTypeMetadata($metadata, $attribute);
}
}
}
if (false === $metadata['has_constructor']) {
foreach ($class
->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
$metadata['properties'][$property->name] = $property->name;
if (false === ($propertyComment = $property
->getDocComment())) {
continue;
}
$attribute = new Attribute();
$attribute->required = false !== strpos($propertyComment, '@Required');
$attribute->name = $property->name;
$attribute->type = false !== strpos($propertyComment, '@var') && preg_match('/@var\\s+([^\\s]+)/', $propertyComment, $matches) ? $matches[1] : 'mixed';
$this
->collectAttributeTypeMetadata($metadata, $attribute);
if (false !== strpos($propertyComment, '@Enum')) {
$context = 'property ' . $class->name . "::\$" . $property->name;
self::$metadataParser
->setTarget(Target::TARGET_PROPERTY);
foreach (self::$metadataParser
->parse($propertyComment, $context) as $annotation) {
if (!$annotation instanceof Enum) {
continue;
}
$metadata['enum'][$property->name]['value'] = $annotation->value;
$metadata['enum'][$property->name]['literal'] = !empty($annotation->literal) ? $annotation->literal : $annotation->value;
}
}
}
$metadata['default_property'] = reset($metadata['properties']);
}
}
self::$annotationMetadata[$name] = $metadata;
}
private function collectAttributeTypeMetadata(&$metadata, Attribute $attribute) {
$type = isset(self::$typeMap[$attribute->type]) ? self::$typeMap[$attribute->type] : $attribute->type;
if ('mixed' === $type) {
return;
}
switch (true) {
case false !== ($pos = strpos($type, '<')):
$arrayType = substr($type, $pos + 1, -1);
$type = 'array';
if (isset(self::$typeMap[$arrayType])) {
$arrayType = self::$typeMap[$arrayType];
}
$metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
break;
case false !== ($pos = strrpos($type, '[')):
$arrayType = substr($type, 0, $pos);
$type = 'array';
if (isset(self::$typeMap[$arrayType])) {
$arrayType = self::$typeMap[$arrayType];
}
$metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
break;
}
$metadata['attribute_types'][$attribute->name]['type'] = $type;
$metadata['attribute_types'][$attribute->name]['value'] = $attribute->type;
$metadata['attribute_types'][$attribute->name]['required'] = $attribute->required;
}
private function Annotations() {
$annotations = array();
while (null !== $this->lexer->lookahead) {
if (DocLexer::T_AT !== $this->lexer->lookahead['type']) {
$this->lexer
->moveNext();
continue;
}
if (null !== $this->lexer->token && $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value'])) {
$this->lexer
->moveNext();
continue;
}
if (null === ($peek = $this->lexer
->glimpse()) || DocLexer::T_NAMESPACE_SEPARATOR !== $peek['type'] && !in_array($peek['type'], self::$classIdentifiers, true) || $peek['position'] !== $this->lexer->lookahead['position'] + 1) {
$this->lexer
->moveNext();
continue;
}
$this->isNestedAnnotation = false;
if (false !== ($annot = $this
->Annotation())) {
$annotations[] = $annot;
}
}
return $annotations;
}
private function Annotation() {
$this
->match(DocLexer::T_AT);
$name = $this
->Identifier();
$originalName = $name;
if ('\\' !== $name[0]) {
$alias = false === ($pos = strpos($name, '\\')) ? $name : substr($name, 0, $pos);
$found = false;
if ($this->namespaces) {
foreach ($this->namespaces as $namespace) {
if ($this
->classExists($namespace . '\\' . $name)) {
$name = $namespace . '\\' . $name;
$found = true;
break;
}
}
}
elseif (isset($this->imports[$loweredAlias = strtolower($alias)])) {
$found = true;
$name = false !== $pos ? $this->imports[$loweredAlias] . substr($name, $pos) : $this->imports[$loweredAlias];
}
elseif (!isset($this->ignoredAnnotationNames[$name]) && isset($this->imports['__NAMESPACE__']) && $this
->classExists($this->imports['__NAMESPACE__'] . '\\' . $name)) {
$name = $this->imports['__NAMESPACE__'] . '\\' . $name;
$found = true;
}
elseif (!isset($this->ignoredAnnotationNames[$name]) && $this
->classExists($name)) {
$found = true;
}
if (!$found) {
if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$name])) {
return false;
}
throw AnnotationException::semanticalError(sprintf('The annotation "@%s" in %s was never imported. Did you maybe forget to add a "use" statement for this annotation?', $name, $this->context));
}
}
if (!$this
->classExists($name)) {
throw AnnotationException::semanticalError(sprintf('The annotation "@%s" in %s does not exist, or could not be auto-loaded.', $name, $this->context));
}
if (!isset(self::$annotationMetadata[$name])) {
$this
->collectAnnotationMetadata($name);
}
if (self::$annotationMetadata[$name]['is_annotation'] === false) {
if (isset($this->ignoredAnnotationNames[$originalName])) {
return false;
}
throw AnnotationException::semanticalError(sprintf('The class "%s" is not annotated with @Annotation. Are you sure this class can be used as annotation? If so, then you need to add @Annotation to the _class_ doc comment of "%s". If it is indeed no annotation, then you need to add @IgnoreAnnotation("%s") to the _class_ doc comment of %s.', $name, $name, $originalName, $this->context));
}
$target = $this->isNestedAnnotation ? Target::TARGET_ANNOTATION : $this->target;
$this->isNestedAnnotation = true;
if (0 === (self::$annotationMetadata[$name]['targets'] & $target) && $target) {
throw AnnotationException::semanticalError(sprintf('Annotation @%s is not allowed to be declared on %s. You may only use this annotation on these code elements: %s.', $originalName, $this->context, self::$annotationMetadata[$name]['targets_literal']));
}
$values = $this
->MethodCall();
if (isset(self::$annotationMetadata[$name]['enum'])) {
foreach (self::$annotationMetadata[$name]['enum'] as $property => $enum) {
if (isset($values[$property]) && !in_array($values[$property], $enum['value'])) {
throw AnnotationException::enumeratorError($property, $name, $this->context, $enum['literal'], $values[$property]);
}
}
}
foreach (self::$annotationMetadata[$name]['attribute_types'] as $property => $type) {
if ($property === self::$annotationMetadata[$name]['default_property'] && !isset($values[$property]) && isset($values['value'])) {
$property = 'value';
}
if (!isset($values[$property])) {
if ($type['required']) {
throw AnnotationException::requiredError($property, $originalName, $this->context, 'a(n) ' . $type['value']);
}
continue;
}
if ($type['type'] === 'array') {
if (!is_array($values[$property])) {
$values[$property] = array(
$values[$property],
);
}
if (isset($type['array_type'])) {
foreach ($values[$property] as $item) {
if (gettype($item) !== $type['array_type'] && !$item instanceof $type['array_type']) {
throw AnnotationException::attributeTypeError($property, $originalName, $this->context, 'either a(n) ' . $type['array_type'] . ', or an array of ' . $type['array_type'] . 's', $item);
}
}
}
}
elseif (gettype($values[$property]) !== $type['type'] && !$values[$property] instanceof $type['type']) {
throw AnnotationException::attributeTypeError($property, $originalName, $this->context, 'a(n) ' . $type['value'], $values[$property]);
}
}
if (self::$annotationMetadata[$name]['has_constructor'] === true) {
return new $name($values);
}
$instance = new $name();
foreach ($values as $property => $value) {
if (!isset(self::$annotationMetadata[$name]['properties'][$property])) {
if ('value' !== $property) {
throw AnnotationException::creationError(sprintf('The annotation @%s declared on %s does not have a property named "%s". Available properties: %s', $originalName, $this->context, $property, implode(', ', self::$annotationMetadata[$name]['properties'])));
}
if (!($property = self::$annotationMetadata[$name]['default_property'])) {
throw AnnotationException::creationError(sprintf('The annotation @%s declared on %s does not accept any values, but got %s.', $originalName, $this->context, json_encode($values)));
}
}
$instance->{$property} = $value;
}
return $instance;
}
private function MethodCall() {
$values = array();
if (!$this->lexer
->isNextToken(DocLexer::T_OPEN_PARENTHESIS)) {
return $values;
}
$this
->match(DocLexer::T_OPEN_PARENTHESIS);
if (!$this->lexer
->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
$values = $this
->Values();
}
$this
->match(DocLexer::T_CLOSE_PARENTHESIS);
return $values;
}
private function Values() {
$values = array(
$this
->Value(),
);
while ($this->lexer
->isNextToken(DocLexer::T_COMMA)) {
$this
->match(DocLexer::T_COMMA);
if ($this->lexer
->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
break;
}
$token = $this->lexer->lookahead;
$value = $this
->Value();
if (!is_object($value) && !is_array($value)) {
$this
->syntaxError('Value', $token);
}
$values[] = $value;
}
foreach ($values as $k => $value) {
if (is_object($value) && $value instanceof \stdClass) {
$values[$value->name] = $value->value;
}
else {
if (!isset($values['value'])) {
$values['value'] = $value;
}
else {
if (!is_array($values['value'])) {
$values['value'] = array(
$values['value'],
);
}
$values['value'][] = $value;
}
}
unset($values[$k]);
}
return $values;
}
private function Constant() {
$identifier = $this
->Identifier();
if (!defined($identifier) && false !== strpos($identifier, '::') && '\\' !== $identifier[0]) {
list($className, $const) = explode('::', $identifier);
$alias = false === ($pos = strpos($className, '\\')) ? $className : substr($className, 0, $pos);
$found = false;
switch (true) {
case !empty($this->namespaces):
foreach ($this->namespaces as $ns) {
if (class_exists($ns . '\\' . $className) || interface_exists($ns . '\\' . $className)) {
$className = $ns . '\\' . $className;
$found = true;
break;
}
}
break;
case isset($this->imports[$loweredAlias = strtolower($alias)]):
$found = true;
$className = false !== $pos ? $this->imports[$loweredAlias] . substr($className, $pos) : $this->imports[$loweredAlias];
break;
default:
if (isset($this->imports['__NAMESPACE__'])) {
$ns = $this->imports['__NAMESPACE__'];
if (class_exists($ns . '\\' . $className) || interface_exists($ns . '\\' . $className)) {
$className = $ns . '\\' . $className;
$found = true;
}
}
break;
}
if ($found) {
$identifier = $className . '::' . $const;
}
}
$classPos = stripos($identifier, '::class');
if ($classPos === strlen($identifier) - 7) {
return substr($identifier, 0, $classPos);
}
if (!defined($identifier)) {
throw AnnotationException::semanticalErrorConstants($identifier, $this->context);
}
return constant($identifier);
}
private function Identifier() {
if (!$this->lexer
->isNextTokenAny(self::$classIdentifiers)) {
$this
->syntaxError('namespace separator or identifier');
}
$this->lexer
->moveNext();
$className = $this->lexer->token['value'];
while ($this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value']) && $this->lexer
->isNextToken(DocLexer::T_NAMESPACE_SEPARATOR)) {
$this
->match(DocLexer::T_NAMESPACE_SEPARATOR);
$this
->matchAny(self::$classIdentifiers);
$className .= '\\' . $this->lexer->token['value'];
}
return $className;
}
private function Value() {
$peek = $this->lexer
->glimpse();
if (DocLexer::T_EQUALS === $peek['type']) {
return $this
->FieldAssignment();
}
return $this
->PlainValue();
}
private function PlainValue() {
if ($this->lexer
->isNextToken(DocLexer::T_OPEN_CURLY_BRACES)) {
return $this
->Arrayx();
}
if ($this->lexer
->isNextToken(DocLexer::T_AT)) {
return $this
->Annotation();
}
if ($this->lexer
->isNextToken(DocLexer::T_IDENTIFIER)) {
return $this
->Constant();
}
switch ($this->lexer->lookahead['type']) {
case DocLexer::T_STRING:
$this
->match(DocLexer::T_STRING);
return $this->lexer->token['value'];
case DocLexer::T_INTEGER:
$this
->match(DocLexer::T_INTEGER);
return (int) $this->lexer->token['value'];
case DocLexer::T_FLOAT:
$this
->match(DocLexer::T_FLOAT);
return (double) $this->lexer->token['value'];
case DocLexer::T_TRUE:
$this
->match(DocLexer::T_TRUE);
return true;
case DocLexer::T_FALSE:
$this
->match(DocLexer::T_FALSE);
return false;
case DocLexer::T_NULL:
$this
->match(DocLexer::T_NULL);
return null;
default:
$this
->syntaxError('PlainValue');
}
}
private function FieldAssignment() {
$this
->match(DocLexer::T_IDENTIFIER);
$fieldName = $this->lexer->token['value'];
$this
->match(DocLexer::T_EQUALS);
$item = new \stdClass();
$item->name = $fieldName;
$item->value = $this
->PlainValue();
return $item;
}
private function Arrayx() {
$array = $values = array();
$this
->match(DocLexer::T_OPEN_CURLY_BRACES);
if ($this->lexer
->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
$this
->match(DocLexer::T_CLOSE_CURLY_BRACES);
return $array;
}
$values[] = $this
->ArrayEntry();
while ($this->lexer
->isNextToken(DocLexer::T_COMMA)) {
$this
->match(DocLexer::T_COMMA);
if ($this->lexer
->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
break;
}
$values[] = $this
->ArrayEntry();
}
$this
->match(DocLexer::T_CLOSE_CURLY_BRACES);
foreach ($values as $value) {
list($key, $val) = $value;
if ($key !== null) {
$array[$key] = $val;
}
else {
$array[] = $val;
}
}
return $array;
}
private function ArrayEntry() {
$peek = $this->lexer
->glimpse();
if (DocLexer::T_EQUALS === $peek['type'] || DocLexer::T_COLON === $peek['type']) {
if ($this->lexer
->isNextToken(DocLexer::T_IDENTIFIER)) {
$key = $this
->Constant();
}
else {
$this
->matchAny(array(
DocLexer::T_INTEGER,
DocLexer::T_STRING,
));
$key = $this->lexer->token['value'];
}
$this
->matchAny(array(
DocLexer::T_EQUALS,
DocLexer::T_COLON,
));
return array(
$key,
$this
->PlainValue(),
);
}
return array(
null,
$this
->Value(),
);
}
}