Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Reflection Docblock Laravel Package

phpdocumentor/reflection-docblock

Parse and reflect PHPDoc DocBlocks with a factory-based API. Fully compatible with the PHPDoc standard, it extracts summaries, descriptions, and tags, enabling libraries to read documentation metadata and build annotation-like features from doc comments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require phpdocumentor/reflection-docblock
    
  2. Basic Usage:
    use phpdocumentor\Reflection\DocBlockFactory;
    
    $factory = DocBlockFactory::createInstance();
    $docblock = $factory->create('/** @var string $name */');
    

First Use Case: Parsing DocBlocks in Laravel

  • Extracting DocBlock from Reflection:
    $reflectionClass = new ReflectionClass(MyClass::class);
    $docblock = $factory->create($reflectionClass->getDocComment());
    
  • Accessing Summary/Description:
    $summary = $docblock->getSummary(); // "Class description"
    $description = $docblock->getDescription()->render(); // Full description
    

Key Entry Points

  • DocBlockFactory: Central factory for creating DocBlock objects.
  • DocBlock: Parsed docblock with methods like getTags(), getSummary(), getDescription().
  • Tag: Individual docblock tags (e.g., @param, @return, @var).

Implementation Patterns

1. Tag Extraction and Validation

  • Pattern: Extract and validate tags dynamically.
    foreach ($docblock->getTags() as $tag) {
        if ($tag->getName() === 'param') {
            $type = $tag->getType();
            $var = $tag->getVariableName();
            // Validate or process
        }
    }
    
  • Laravel Integration: Use in service providers or middleware to enforce docblock standards.

2. Dynamic Tag Handling

  • Pattern: Register custom tag handlers for non-standard tags.
    $factory->addTagHandler('custom', function (string $content) {
        return new CustomTag($content);
    });
    

3. DocBlock Rendering

  • Pattern: Convert DocBlock back to string for logging or validation.
    $rendered = $docblock->render();
    // Use in Laravel's logging or validation rules
    

4. Integration with Laravel Reflection

  • Pattern: Combine with ReflectionClass/ReflectionMethod for metadata extraction.
    $method = new ReflectionMethod(MyClass::class, 'myMethod');
    $docblock = $factory->create($method->getDocComment());
    $returnType = $docblock->getTagsByName('return')[0]->getType();
    

5. Validation Rules

  • Pattern: Use in Laravel's FormRequest or Validator for docblock compliance.
    use Illuminate\Validation\Rule;
    
    $rules = [
        'docblock' => [
            'required',
            Rule::custom(function ($attribute, $value, $fail) {
                $docblock = $factory->create($value);
                if (!$docblock->hasTag('return')) {
                    $fail('Missing @return tag.');
                }
            }),
        ],
    ];
    

6. Caching Parsed DocBlocks

  • Pattern: Cache parsed docblocks to avoid reprocessing.
    $cache = new Illuminate\Support\Facades\Cache;
    $key = 'docblock:'.md5($className);
    $docblock = $cache->remember($key, 3600, function () use ($factory, $reflectionClass) {
        return $factory->create($reflectionClass->getDocComment());
    });
    

Gotchas and Tips

Pitfalls

  1. Deprecated Features:
    • Avoid @param tags without variable names (deprecated in v5.4+).
    • Static factory interfaces are deprecated; use DocBlockFactory directly.
  2. Type Resolution:
    • Complex generics (e.g., Array<mixed>) may return InvalidTag. Use phpdocumentor/type-resolver for advanced cases.
  3. Multiline Descriptions:
    • Indented lines in descriptions may cause parsing issues (fixed in v5.4.1+).
  4. PHP Version Quirks:
    • PHP 8.1+ disables Reflection*::setAccessible(). The library handles this automatically, but custom extensions may need adjustments.

Debugging Tips

  1. Inspect Raw DocBlocks:
    $rawDocblock = $reflectionClass->getDocComment();
    Log::debug('Raw docblock:', [$rawDocblock]);
    
  2. Validate Tag Parsing:
    try {
        $docblock = $factory->create($docblockText);
    } catch (\phpDocumentor\Reflection\Exception\InvalidTagException $e) {
        Log::error('Invalid tag:', [$e->getTag()->getContent()]);
    }
    
  3. Check for Missing Tags:
    if (!$docblock->hasTag('return')) {
        throw new \RuntimeException('Missing @return tag.');
    }
    

Extension Points

  1. Custom Tag Handlers:
    $factory->addTagHandler('deprecated', function (string $content) {
        return new DeprecatedTag($content);
    });
    
  2. Override Default Tag Factories:
    $factory->setTagFactory(new CustomTagFactory());
    
  3. Integrate with Laravel Events:
    Event::listen('illuminate.starting', function () {
        $docblock = $factory->create(MyService::class->getDocComment());
        if (!$docblock->hasTag('author')) {
            throw new \RuntimeException('Missing @author tag.');
        }
    });
    

Performance Considerations

  • Avoid Re-parsing: Cache DocBlock objects for frequently used classes/methods.
  • Lazy Loading: Parse docblocks only when needed (e.g., in boot() or register() methods).

Laravel-Specific Quirks

  1. Service Container Binding:
    $app->bind(DocBlockFactory::class, function () {
        return DocBlockFactory::createInstance();
    });
    
  2. Artisan Commands:
    use phpdocumentor\Reflection\DocBlockFactory;
    
    protected $factory;
    
    public function __construct(DocBlockFactory $factory) {
        $this->factory = $factory;
    }
    
  3. Testing:
    $this->app->instance(DocBlockFactory::class, DocBlockFactory::createInstance());
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport