prinsfrank/phpstan-doc-code-analyzer
Analyze and validate PHP code examples in your documentation using PHPStan. This package scans doc blocks and docs for code snippets, runs static analysis, and helps catch outdated or incorrect examples early in CI.
Installation
composer require --dev prinsfrank/phpstan-doc-code-analyzer
Add to your phpstan.neon:
includes:
- vendor/prinsfrank/phpstan-doc-code-analyzer/extension.neon
First Use Case
Run PHPStan on a project with documented code snippets (e.g., README.md or .php files):
vendor/bin/phpstan analyse src --level=5
The extension will now analyze code blocks in Markdown files (fenced with ```php) alongside your PHP files.
Markdown + PHP Analysis Use the extension to validate code snippets in:
README.md (e.g., usage examples)docs/ directories (e.g., API documentation).php files with embedded docblocks (e.g., @example tags).
Example Markdown snippet:```php
$user = new User(); // PHPStan will check this snippet
$user->setName('Alice');
CI/CD Pipeline Add to your CI (e.g., GitHub Actions) to enforce consistency between docs and code:
- name: Run PHPStan with Doc Analyzer
run: vendor/bin/phpstan analyse --level=5
Custom Rules Extend the analyzer by creating a custom rule for project-specific docblock patterns:
// In a custom extension
public function getNodeTypes(): array {
return [DocCodeAnalyzerNode::class];
}
Exclude Files Skip non-critical docs (e.g., legacy examples):
excludes:
- docs/legacy-examples.md
Strictness Levels
Use --level=8 for strict checks in production docs, --level=5 for development.
False Positives in Snippets
PHPStan may flag incomplete snippets (e.g., missing classes). Use @ignore in docblocks:
```php
// @ignore-next-line
$unresolvable = new NonExistentClass();
Performance Overhead Large Markdown files (e.g., 1000+ lines) may slow analysis. Split docs into smaller files or exclude non-critical sections.
Syntax Parsing Quirks Avoid mixing languages in fenced blocks (e.g., PHP + HTML). Use separate blocks or disable analysis for mixed content:
phpstan-doc-code-analyzer:
enabled: true
ignore-mixed-language-blocks: true
Verbose Output Enable debug logs to inspect parsed snippets:
vendor/bin/phpstan analyse --debug
Isolated Testing
Test snippets in isolation by creating a minimal test.md file:
```php
<?php
class Test {}
Custom Block Delimiters Override default fences (e.g., ```example) in config:
phpstan-doc-code-analyzer:
block-delimiters: ['example', 'php']
Pre-Process Snippets Use a pre-commit hook to auto-fix minor issues (e.g., trailing commas) before PHPStan runs.
Integration with Other Tools
Combine with phpstan-baseline to ignore known doc-snippet issues temporarily.
How can I help you explore Laravel packages today?