shieldci / analyzers-core
Shared foundation for building static analysis tools - includes abstract analyzer classes, result formatters, file parsers, and utilities
Installs: 26
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/shieldci/analyzers-core
Requires
- php: ^8.1
- nikic/php-parser: ^4.15|^5.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.40
- mockery/mockery: ^1.6
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2025-11-25 06:19:54 UTC
README
Shared foundation for building static analysis tools. Includes abstract analyzer classes, result formatters, file parsers, and utilities.
Features
- Framework Agnostic: Works with any PHP 8.1+ project
- Type Safe: Full type hints and strict typing
- Extensible: Easy to create custom analyzers
- Well Tested: Comprehensive test suite (90%+ coverage)
- Modern PHP: Uses PHP 8.1+ features
- Laravel Compatible: Works with Laravel 9.x, 10.x, 11.x, and 12.x
Requirements
- PHP 8.1 or higher
- Composer
Installation
composer require shieldci/analyzers-core
Architecture
Core Components
-
Interfaces
AnalyzerInterface- Contract for all analyzersResultInterface- Contract for analysis resultsReporterInterface- Contract for result formattersParserInterface- Contract for code parsers
-
Abstract Base Classes
AbstractAnalyzer- Base class with timing, error handling, and helper methodsAbstractFileAnalyzer- Base class for file-based analyzers with file filtering
-
Value Objects
Location- Represents a code location (file, line, column)Issue- Represents a specific issue foundAnalyzerMetadata- Metadata about an analyzer
-
Results
AnalysisResult- Result of running a single analyzerResultCollection- Collection of analysis results
-
Utilities
AstParser- AST parsing using nikic/php-parserFileParser- File content parsing utilitiesCodeHelper- Code analysis helpers
-
Formatters
JsonFormatter- Format results as JSONConsoleFormatter- Format results for console output
Usage
Creating a Custom Analyzer
<?php use ShieldCI\AnalyzersCore\Abstracts\AbstractFileAnalyzer; use ShieldCI\AnalyzersCore\Contracts\ResultInterface; use ShieldCI\AnalyzersCore\ValueObjects\{AnalyzerMetadata, Issue, Location}; use ShieldCI\AnalyzersCore\Enums\{Category, Severity}; class MySecurityAnalyzer extends AbstractFileAnalyzer { protected function metadata(): AnalyzerMetadata { return new AnalyzerMetadata( id: 'my-security-analyzer', name: 'My Security Analyzer', description: 'Checks for security vulnerabilities', category: Category::Security, severity: Severity::High, ); } protected function runAnalysis(): ResultInterface { $issues = []; foreach ($this->getPhpFiles() as $file) { $content = $this->readFile($file); if (str_contains($content, 'eval(')) { $issues[] = $this->createIssue( message: 'Dangerous eval() function found', location: new Location($file, 1), severity: Severity::Critical, recommendation: 'Remove eval() and use safer alternatives' ); } } if (empty($issues)) { return $this->passed('No security issues found'); } return $this->failed( 'Security issues detected', $issues, ['files_scanned' => count($this->getPhpFiles())] ); } }
Running an Analyzer
<?php $analyzer = new MySecurityAnalyzer(); $analyzer->setBasePath('/path/to/project'); $analyzer->setPaths(['src', 'app']); $result = $analyzer->analyze(); echo "Status: " . $result->getStatus()->value . PHP_EOL; echo "Message: " . $result->getMessage() . PHP_EOL; echo "Issues: " . count($result->getIssues()) . PHP_EOL;
Using Result Collection
<?php use ShieldCI\AnalyzersCore\Results\ResultCollection; $collection = new ResultCollection(); $collection->add($analyzer1->analyze()); $collection->add($analyzer2->analyze()); $collection->add($analyzer3->analyze()); echo "Score: " . $collection->score() . "%" . PHP_EOL; echo "Total Issues: " . $collection->totalIssues() . PHP_EOL; echo "Execution Time: " . $collection->totalExecutionTime() . "s" . PHP_EOL;
Formatting Results
<?php use ShieldCI\AnalyzersCore\Formatters\{ConsoleFormatter, JsonFormatter}; $results = [$result1, $result2, $result3]; // Console output $consoleFormatter = new ConsoleFormatter(useColors: true, verbose: true); echo $consoleFormatter->format($results); // JSON output $jsonFormatter = new JsonFormatter(prettyPrint: true); $json = $jsonFormatter->format($results); file_put_contents('report.json', $json);
Using the AST Parser
<?php use ShieldCI\AnalyzersCore\Support\AstParser; use PhpParser\Node\Expr\MethodCall; $parser = new AstParser(); $ast = $parser->parseFile('/path/to/file.php'); // Find all method calls $methodCalls = $parser->findMethodCalls($ast, 'query'); // Find static calls $staticCalls = $parser->findStaticCalls($ast, 'DB', 'raw'); // Find nodes of specific type $classes = $parser->findNodes($ast, \PhpParser\Node\Stmt\Class_::class);
Using Code Helpers
<?php use ShieldCI\AnalyzersCore\Support\CodeHelper; $code = file_get_contents('/path/to/file.php'); // Calculate complexity $complexity = CodeHelper::calculateComplexity($code); // Find dangerous functions $dangerous = CodeHelper::findDangerousFunctions($code); // Check if looks like SQL $isSql = CodeHelper::looksLikeSql($string); // Validate naming conventions $isValid = CodeHelper::isValidClassName('MyClass');
Enums
Status
Passed- Analysis passedFailed- Analysis found issuesWarning- Analysis found warningsSkipped- Analysis was skippedError- Analysis encountered an error
Category
Security- Security vulnerabilities and risksPerformance- Performance issues and optimizationsCodeQuality- Code quality and maintainabilityBestPractices- Best practices and conventionsReliability- Reliability and stability issues
Severity
Critical- Critical issue requiring immediate attentionHigh- High priority issueMedium- Medium priority issueLow- Low priority issueInfo- Informational message
Testing
# Run tests composer test # Run tests with coverage composer test-coverage # Run static analysis composer analyse # Format code composer format
Directory Structure
src/
├── Contracts/ # Interfaces
├── Abstracts/ # Abstract base classes
├── Enums/ # Enum types
├── ValueObjects/ # Immutable value objects
├── Results/ # Result classes
├── Support/ # Utility classes
└── Formatters/ # Result formatters
tests/
├── Unit/ # Unit tests
Used By
- shieldci/laravel - Free Laravel analyzer package
- shieldci/laravel-pro - Pro Laravel analyzer package
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT License. See LICENSE file for details.
Credits
Built by the ShieldCI team.