TLDR:
I propose to introduce a new class \ReflectionContext (or perhaps
\ReflectionScope?), to give information about imported aliases and the
namespace.


## Background / motivation

Some libraries that parse doc comment annotations, e.g. phpDocumentor,
need to know the class aliases and the namespace that are active in
the place (scope) where the class, function or method is declared.

E.g. phpDocumentor has this class:
https://github.com/phpDocumentor/TypeResolver/blob/552bf401d264a443819a66233932be6a23f59d78/src/Types/Context.php

To get this information, they parse the PHP file where the class is defined:
https://github.com/phpDocumentor/TypeResolver/blob/552bf401d264a443819a66233932be6a23f59d78/src/Types/ContextFactory.php

It would be much more pleasant if PHP would provide this information
through the reflection API.
A custom library should not need to do an expensive and fragile
parsing job for information that is already known.

Also, this external parsing might not cover all cases, depending how
it is implemented. E.g. local namespace scopes in curly brackets. (Who
uses those, btw?)


## Proposal

Make information about class aliases (imported through use statements)
and the active namespace available through the reflection API.

$reflClass = new \ReflectionClass(C::class);
$reflContext = $reflClass->getContext();
$aliases = $reflContext->getAliases();


## Details

class ReflectionContext {

  function getNamespace() : string {..}

  /**
   * @return string[]
   *   Format: $[$alias] = $qcn
   */
  function getAliases() : string[] {..}

  /**
   * @return string|null
   *   The qcn of the class, or null if it is a built-in type like "string".
   */
  function resolveAlias($alias) : ?string {..}
}

The $reflClass->getContext()->getNamespace() is the same as
$reflClass->getNamespace().

But having it all in the $context object allows this object to be
passed around to components that need it.


## Open questions

In a method doc comment, we also want to resolve the "self" keyword.
For this, the class name is needed as well, not just external imports
and namespace.

Maybe also introduce \RefllectionMethod::getContext()? Not sure.

Should it be "context" or "scope"? It is not the same. Maybe "scope"
leads to the wrong expectations.

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to