ReflectionDocBlock

repository·master·Indexed 23 days ago

https://github.com/barryvdh/reflectiondocblock

A PHPDoc standard-compatible parser for retrieving information and annotations embedded within DocBlocks. This specific version is a fork optimized for laravel-ide-helper. It provides classes to parse DocBlocks, manage parsing state via Context, handle descriptions, and manipulate tags such as @author, @method, and @param. It supports template mechanisms using #@+ and #@- markers and allows for the registration of custom tag handlers.

Tokens
4.3K
Snippets
5
Records
30
Agent score
79%

What's inside reflectiondocblock

  1. Install the ReflectionDocBlock component

    master

    You can install the component via Composer or by using the official GitHub repository.

    Note: This specific repository is a fork optimized for laravel-ide-helper. If you are not using that specific tool, the maintainers recommend using the official phpDocumentor/ReflectionDocBlock directly.

  2. How DocBlock templates work

    master

    The library supports a template mechanism where one DocBlock can serve as a template for subsequent DocBlocks. This is indicated by special markers:

    • #@+: Marks the start of a template section. When this marker is present immediately after the opening /**, the description and tags (but not the summary) are copied to subsequent DocBlocks.
    • #@-: Marks the end of a template section.

    You can check the status of a DocBlock using isTemplateStart() and isTemplateEnd().

  3. Parse DocBlocks using the DocBlock class

    master

    The \phpDocumentor\Reflection\DocBlock class is used to parse PHPDoc standard DocBlocks. It is designed to work similarly to PHP's native Reflection extension.

    You can initiate parsing in two ways:

    1. By passing a raw string containing the DocBlock (including the leading asterisks).
    2. By passing an object that implements the getDocComment() method (such as ReflectionClass or ReflectionMethod).
    // Option 1: Passing a Reflection object
    $class = new ReflectionClass('MyClass');
    $phpdoc = new \phpDocumentor\Reflection\DocBlock($class);
    
    // Option 2: Passing a raw DocBlock string
    $docblock = <<<'DOCBLOCK'
    /**
     * This is a short description.
     *
     * This is a *long* description.
     *
     * @return void
     */
    DOCBLOCK;
    
    $phpdoc = new \phpDocumentor\Reflection\DocBlock($docblock);
  4. Use the Description class to parse DocBlock text

    master

    The Description class is used to represent and parse the text content within a DocBlock or a specific tag. It allows you to retrieve the raw text or a parsed version where inline tags (e.g., {@link ...}) are converted into Tag objects.

    Key methods:

    • getContents(): Returns the raw, unparsed string content.
    • getParsedContents(): Returns an array containing the description's parts, alternating between plain strings and Tag objects, preserving their original order.
    • getFormattedContents(): Returns the content formatted as HTML. It attempts to use Parsedown or dflydev/markdown if available to convert Markdown to HTML, and automatically wraps plain <code> tags in <pre> tags.
  5. Register custom DocBlock tag handlers

    master

    You can extend the library's parsing capabilities by registering custom handlers for specific DocBlock tags. To do this, create a class that inherits from Barryvdh\ Reflection\ DocBlock\ Tag and register it using Tag::registerTagHandler().

    When registering a namespaced tag, you must provide the full name starting with a leading slash (e.g., /\My\Custom\Tag). Passing null as the handler will remove any existing handler for that tag.

    Note: The handler class must be a subclass of Tag and must be autoloadable.

  6. Retrieve descriptions and text from a DocBlock

    master

    Once a DocBlock is instantiated, you can extract the descriptive text it contains:

    • getShortDescription(): Returns the first line or the summary (the text before the first dot followed by a newline or two consecutive newlines).
    • getLongDescription(): Returns a DocBlock\Description object containing the full body of the description.
    • getText(): Returns the combined text of both the short and long descriptions.
  7. Identify related DocBlock tags with inSameGroup()

    master

    The inSameGroup() method allows you to determine if two tags belong to the same logical category. This is useful for grouping related metadata in UI components or documentation generators.

    Tags are considered in the same group if they share the same name or belong to one of these predefined groups:

    • deprecated, link, see, since
    • author, copyright, license
    • category, package, subpackage
    • property, property-read, property-write
    • param, return
  8. Configure namespace aliases in Context

    master

    You can manage namespace aliases within a Context object using setNamespaceAliases() to replace all existing aliases, or setNamespaceAlias() to add or update a single alias.

    When using setNamespaceAlias($alias, $fqnn), the library automatically trims leading and trailing slashes from the FQNN and prefixes it with a single backslash.

    Methods

    • setNamespaceAliases(array $namespace_aliases): Replaces all current aliases with the provided associative array where keys are aliases and values are FQNNs.
    • setNamespaceAlias($alias, $fqnn): Adds or updates a specific alias.
  9. Instantiate DocBlock to parse DocBlock comments

    master

    The Barryvdh\Reflection\DocBlock class is the primary entry point for parsing PHP DocBlock comments. You can instantiate it by passing either a raw DocBlock string (including asterisks) or a PHP Reflector object that implements the getDocComment method.

    To improve type resolution (e.g., converting relative types in @param or @return to Fully Qualified Class Names), you can optionally provide a Context and a Location object during instantiation.

  10. Query and manage tags in a DocBlock

    master

    You can inspect and manipulate the @tag elements within a DocBlock using the following methods:

    • getTags(): Returns an array of all Tag objects found in the DocBlock.
    • getTagsByName($name): Returns an array of Tag objects that match a specific tag name (e.g., param).
    • hasTag($name): Returns true if a tag with the specified name exists.
    • appendTag(Tag $tag): Adds a new Tag object to the end of the DocBlock's tag list.
    • deleteTag(Tag $tag): Removes a specific Tag object from the list.
  11. Use the MethodTag class to parse @method DocBlock tags

    master

    The MethodTag class is used to represent and manipulate @method tags found in PHP DocBlocks. It allows you to extract the method name, its arguments, its return type, and whether it is a static method.

    When using setContent(), the class parses the tag content using a specific regex pattern that supports:

    • The static keyword (only if a type is also present).
    • Return types (including $this, generics like Type<T>, and array notation Type[]).
    • The method name.
    • Arguments enclosed in parentheses ().
    • A trailing description.

    Note: If no return type is specified in the tag, the class defaults the type to void.

  12. Use the Collection class to manage DocBlock types

    master

    The Barryvdh\Reflection\DocBlock\Type\Collection class is an ArrayObject used to store and manage a collection of types parsed from DocBlocks. It handles the expansion of relative class names into Fully Qualified Class Names (FQCN) using a provided Context (which contains namespace and alias information).

    Key features:

    • Type Expansion: Automatically converts relative types (e.g., User) into FQCNs (e.g., App\Models\User) based on the current context.
    • Union Types: Supports the OR operator (|) to handle multiple types.
    • Array Types: Supports the array operator ([]).
    • String Representation: Casting the collection to a string returns the resolved types separated by the | operator.