File size: 10,346 Bytes
38ff4d0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | <?php declare(strict_types=1);
namespace PhpDocReader;
use PhpDocReader\PhpParser\UseStatementParser;
use ReflectionClass;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;
use Reflector;
/**
* PhpDoc reader
*/
class PhpDocReader
{
/** @var UseStatementParser */
private $parser;
private const PRIMITIVE_TYPES = [
'bool' => 'bool',
'boolean' => 'bool',
'string' => 'string',
'int' => 'int',
'integer' => 'int',
'float' => 'float',
'double' => 'float',
'array' => 'array',
'object' => 'object',
'callable' => 'callable',
'resource' => 'resource',
'mixed' => 'mixed',
'iterable' => 'iterable',
];
/** @var bool */
private $ignorePhpDocErrors;
/**
* @param bool $ignorePhpDocErrors Enable or disable throwing errors when PhpDoc errors occur (when parsing annotations).
*/
public function __construct(bool $ignorePhpDocErrors = false)
{
$this->parser = new UseStatementParser;
$this->ignorePhpDocErrors = $ignorePhpDocErrors;
}
/**
* Parse the docblock of the property to get the type (class or primitive type) of the var annotation.
*
* @return string|null Type of the property (content of var annotation)
* @throws AnnotationException
*/
public function getPropertyType(ReflectionProperty $property): ?string
{
return $this->readPropertyType($property, true);
}
/**
* Parse the docblock of the property to get the class of the var annotation.
*
* @return string|null Type of the property (content of var annotation)
* @throws AnnotationException
*/
public function getPropertyClass(ReflectionProperty $property): ?string
{
return $this->readPropertyType($property, false);
}
private function readPropertyType(ReflectionProperty $property, bool $allowPrimitiveTypes): ?string
{
// Get the content of the @var annotation
$docComment = $property->getDocComment();
if (! $docComment) {
return null;
}
if (preg_match('/@var\s+([^\s]+)/', $docComment, $matches)) {
[, $type] = $matches;
} else {
return null;
}
// Ignore primitive types
if (isset(self::PRIMITIVE_TYPES[$type])) {
if ($allowPrimitiveTypes) {
return self::PRIMITIVE_TYPES[$type];
}
return null;
}
// Ignore types containing special characters ([], <> ...)
if (! preg_match('/^[a-zA-Z0-9\\\\_]+$/', $type)) {
return null;
}
$class = $property->getDeclaringClass();
// If the class name is not fully qualified (i.e. doesn't start with a \)
if ($type[0] !== '\\') {
// Try to resolve the FQN using the class context
$resolvedType = $this->tryResolveFqn($type, $class, $property);
if (! $resolvedType && ! $this->ignorePhpDocErrors) {
throw new AnnotationException(sprintf(
'The @var annotation on %s::%s contains a non existent class "%s". '
. 'Did you maybe forget to add a "use" statement for this annotation?',
$class->name,
$property->getName(),
$type
));
}
$type = $resolvedType;
}
if (! $this->ignorePhpDocErrors && ! $this->classExists($type)) {
throw new AnnotationException(sprintf(
'The @var annotation on %s::%s contains a non existent class "%s"',
$class->name,
$property->getName(),
$type
));
}
// Remove the leading \ (FQN shouldn't contain it)
$type = is_string($type) ? ltrim($type, '\\') : null;
return $type;
}
/**
* Parse the docblock of the property to get the type (class or primitive type) of the param annotation.
*
* @return string|null Type of the property (content of var annotation)
* @throws AnnotationException
*/
public function getParameterType(ReflectionParameter $parameter): ?string
{
return $this->readParameterClass($parameter, true);
}
/**
* Parse the docblock of the property to get the class of the param annotation.
*
* @return string|null Type of the property (content of var annotation)
* @throws AnnotationException
*/
public function getParameterClass(ReflectionParameter $parameter): ?string
{
return $this->readParameterClass($parameter, false);
}
private function readParameterClass(ReflectionParameter $parameter, bool $allowPrimitiveTypes): ?string
{
// Use reflection
$parameterType = $parameter->getType();
if ($parameterType && $parameterType instanceof \ReflectionNamedType && ! $parameterType->isBuiltin()) {
return $parameterType->getName();
}
$parameterName = $parameter->name;
// Get the content of the @param annotation
$method = $parameter->getDeclaringFunction();
$docComment = $method->getDocComment();
if (! $docComment) {
return null;
}
if (preg_match('/@param\s+([^\s]+)\s+\$' . $parameterName . '/', $docComment, $matches)) {
[, $type] = $matches;
} else {
return null;
}
// Ignore primitive types
if (isset(self::PRIMITIVE_TYPES[$type])) {
if ($allowPrimitiveTypes) {
return self::PRIMITIVE_TYPES[$type];
}
return null;
}
// Ignore types containing special characters ([], <> ...)
if (! preg_match('/^[a-zA-Z0-9\\\\_]+$/', $type)) {
return null;
}
$class = $parameter->getDeclaringClass();
// If the class name is not fully qualified (i.e. doesn't start with a \)
if ($type[0] !== '\\') {
// Try to resolve the FQN using the class context
$resolvedType = $this->tryResolveFqn($type, $class, $parameter);
if (! $resolvedType && ! $this->ignorePhpDocErrors) {
throw new AnnotationException(sprintf(
'The @param annotation for parameter "%s" of %s::%s contains a non existent class "%s". '
. 'Did you maybe forget to add a "use" statement for this annotation?',
$parameterName,
$class->name,
$method->name,
$type
));
}
$type = $resolvedType;
}
if (! $this->ignorePhpDocErrors && ! $this->classExists($type)) {
throw new AnnotationException(sprintf(
'The @param annotation for parameter "%s" of %s::%s contains a non existent class "%s"',
$parameterName,
$class->name,
$method->name,
$type
));
}
// Remove the leading \ (FQN shouldn't contain it)
$type = is_string($type) ? ltrim($type, '\\') : null;
return $type;
}
/**
* Attempts to resolve the FQN of the provided $type based on the $class and $member context.
*
* @return string|null Fully qualified name of the type, or null if it could not be resolved
*/
private function tryResolveFqn(string $type, ReflectionClass $class, Reflector $member): ?string
{
$alias = ($pos = strpos($type, '\\')) === false ? $type : substr($type, 0, $pos);
$loweredAlias = strtolower($alias);
// Retrieve "use" statements
$uses = $this->parser->parseUseStatements($class);
if (isset($uses[$loweredAlias])) {
// Imported classes
if ($pos !== false) {
return $uses[$loweredAlias] . substr($type, $pos);
}
return $uses[$loweredAlias];
}
if ($this->classExists($class->getNamespaceName() . '\\' . $type)) {
return $class->getNamespaceName() . '\\' . $type;
}
if (isset($uses['__NAMESPACE__']) && $this->classExists($uses['__NAMESPACE__'] . '\\' . $type)) {
// Class namespace
return $uses['__NAMESPACE__'] . '\\' . $type;
}
if ($this->classExists($type)) {
// No namespace
return $type;
}
// If all fail, try resolving through related traits
return $this->tryResolveFqnInTraits($type, $class, $member);
}
/**
* Attempts to resolve the FQN of the provided $type based on the $class and $member context, specifically searching
* through the traits that are used by the provided $class.
*
* @return string|null Fully qualified name of the type, or null if it could not be resolved
*/
private function tryResolveFqnInTraits(string $type, ReflectionClass $class, Reflector $member): ?string
{
/** @var ReflectionClass[] $traits */
$traits = [];
// Get traits for the class and its parents
while ($class) {
$traits = array_merge($traits, $class->getTraits());
$class = $class->getParentClass();
}
foreach ($traits as $trait) {
// Eliminate traits that don't have the property/method/parameter
if ($member instanceof ReflectionProperty && ! $trait->hasProperty($member->name)) {
continue;
}
if ($member instanceof ReflectionMethod && ! $trait->hasMethod($member->name)) {
continue;
}
if ($member instanceof ReflectionParameter && ! $trait->hasMethod($member->getDeclaringFunction()->name)) {
continue;
}
// Run the resolver again with the ReflectionClass instance for the trait
$resolvedType = $this->tryResolveFqn($type, $trait, $member);
if ($resolvedType) {
return $resolvedType;
}
}
return null;
}
private function classExists(string $class): bool
{
return class_exists($class) || interface_exists($class);
}
}
|