PHP code example of shieldci / analyzers-core

1. Go to this page and download the library: Download shieldci/analyzers-core library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

shieldci / analyzers-core example snippets




use ShieldCI\AnalyzersCore\Abstracts\AbstractFileAnalyzer;
use ShieldCI\AnalyzersCore\Contracts\ResultInterface;
use ShieldCI\AnalyzersCore\ValueObjects\AnalyzerMetadata;
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);

            // Find line number where eval() appears
            $lines = explode("\n", $content);
            foreach ($lines as $lineNum => $line) {
                if (str_contains($line, 'eval(')) {
                    $issues[] = $this->createIssueWithSnippet(
                        message: 'Dangerous eval() function found',
                        filePath: $file,
                        lineNumber: $lineNum + 1,
                        severity: Severity::Critical,
                        recommendation: 'Remove eval() and use safer alternatives',
                        metadata: ['code' => 'dangerous-eval']
                    );
                }
            }
        }

        if (empty($issues)) {
            return $this->passed('No security issues found');
        }

        return $this->failed(
            'Security issues detected',
            $issues,
            ['files_scanned' => count($this->getPhpFiles())]
        );
    }
}



$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;



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;



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);



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);

// Resolve fully-qualified class names with NameResolver
// After this, use $node->getAttribute('resolvedName') on Name nodes to get FQCNs
$resolvedAst = $parser->resolveNames($ast);

// With options — preserve original Name nodes, set only the 'resolvedName' attribute
$resolvedAst = $parser->resolveNames($ast, ['replaceNodes' => false]);
$fqcn = $someNameNode->getAttribute('resolvedName')?->toString(); // e.g. 'Illuminate\Database\Eloquent\Model'



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');



use ShieldCI\AnalyzersCore\ValueObjects\CodeSnippet;

// Create a code snippet from a file
$snippet = CodeSnippet::fromFile(
    filePath: '/path/to/file.php',
    targetLine: 42,
    contextLines: 8  // Lines before/after to show (default: 8)
);

if ($snippet !== null) {
    // Get the lines with line numbers as keys
    $lines = $snippet->getLines();

    // Get the target line number
    $targetLine = $snippet->getTargetLine();

    // Get file path
    $filePath = $snippet->getFilePath();

    // Convert to array for serialization
    $array = $snippet->toArray();
}



use ShieldCI\AnalyzersCore\ValueObjects\{Issue, Location, CodeSnippet};
use ShieldCI\AnalyzersCore\Enums\Severity;

$issue = new Issue(
    message: 'Hardcoded credentials detected',
    location: new Location('/path/to/file.php', 42),
    severity: Severity::Critical,
    recommendation: 'Move credentials to environment variables',
    metadata: ['type' => 'password', 'code' => 'hardcoded-credentials'],
    codeSnippet: CodeSnippet::fromFile('/path/to/file.php', 42)
);

// The code snippet is displayed in verbose console output with:
// - Line numbers alongside each line
// - "→" prefix on the target line, "  " prefix on context lines
// - Indentation preserved (trailing whitespace stripped, leading kept)

// Given this code:
// Line 35: public function processPayment($amount)
// Line 36: {
// Line 37:     // validation
// Line 38:     // ...
// Line 42:     $hardcodedKey = 'secret123';  // ← Issue here
// Line 43: }

// Even though line 35 is normally outside the 8-line context window,
// CodeSnippet automatically 



use ShieldCI\AnalyzersCore\Support\ConfigFileHelper;

// Get the path to a config file
$configPath = ConfigFileHelper::getConfigPath(
    basePath: '/path/to/project',
    file: 'database',  // with or without .php extension
    fallback: fn($file) => config_path($file)  // Optional Laravel helper fallback
);
// Result: /path/to/project/config/database.php

// Find the line number where a specific key is defined
$lineNumber = ConfigFileHelper::findKeyLine(
    configFile: '/path/to/project/config/database.php',
    key: 'default'
);
// Returns the line number (1-indexed) where 'default' => is defined

// Find a key within a parent array
$lineNumber = ConfigFileHelper::findKeyLine(
    configFile: '/path/to/project/config/database.php',
    key: 'driver',
    parentKey: 'connections'  // Search within 'connections' array
);
// Returns the line number where 'driver' => is defined within 'connections'

// Find a nested key within a specific array item
$lineNumber = ConfigFileHelper::findNestedKeyLine(
    configFile: '/path/to/project/config/cache.php',
    parentKey: 'stores',
    nestedKey: 'driver',
    nestedValue: 'redis'  // Search within 'redis' store configuration
);
// Returns the line number where 'driver' => is defined
// within the 'redis' item in the 'stores' array



use ShieldCI\AnalyzersCore\Support\ConfigFileHelper;

$entries = ConfigFileHelper::parseConfigArray('/path/to/config/session.php');

// Each entry has: value, line, isEnvCall, envDefault, envHasDefault
foreach ($entries as $key => $entry) {
    echo "{$key} on line {$entry['line']}: ";

    if ($entry['isEnvCall']) {
        // Value comes from env() at runtime
        echo "env() call";
        if ($entry['envHasDefault']) {
            var_dump($entry['envDefault']); // The default argument value
        }
    } else {
        var_dump($entry['value']); // Literal: string, int, float, bool, or null
    }
}

$session = ConfigFileHelper::parseConfigArray($configPath);

// Resolve the effective value (literal or env() default)
$secure = $session['secure']['isEnvCall']
    ? $session['secure']['envDefault']
    : $session['secure']['value'];

if ($secure !== true) {
    $issues[] = $this->createIssueWithSnippet(
        message: 'Session cookies are not marked secure',
        filePath: $configPath,
        lineNumber: $session['secure']['line'],
        severity: Severity::High,
        recommendation: 'Set SESSION_SECURE_COOKIE=true in production',
    );
}



use ShieldCI\AnalyzersCore\Support\FileParser;

$code = file_get_contents('/path/to/file.php');

// Strips //, #, /* */, and /** */ comments
// Preserves line numbering (removed lines replaced with blank lines)
// Safe for URLs in strings: "https://example.com" is NOT stripped
$stripped = FileParser::stripAllComments($code);



use ShieldCI\AnalyzersCore\Support\MessageHelper;

// Redacts: passwords, API keys, bearer tokens, AWS keys, internal IPs (10.x, 172.x, 192.168.x)
$safe = MessageHelper::sanitizeErrorMessage(
    'Connection failed: password=s3cr3t host=10.0.0.5'
);
// → 'Connection failed: password=[REDACTED] host=[INTERNAL_IP]'

// Use in analyzer recommendations:
$issues[] = $this->createIssue(
    message: 'Redis connection failed',
    location: null,
    severity: Severity::High,
    recommendation: MessageHelper::sanitizeErrorMessage($e->getMessage()),
);



use ShieldCI\AnalyzersCore\Support\InlineSuppressionParser;

$parser = new InlineSuppressionParser();
$lines  = file('/path/to/file.php', FILE_IGNORE_NEW_LINES);

// Returns true if the line (or an adjacent suppression comment) suppresses $analyzerId
$suppressed = $parser->isLineSuppressed($lines, $lineNumber, 'sql-injection');

if (! $suppressed) {
    $issues[] = $this->createIssueWithSnippet(/* … */);
}

// Same-line:
$query = $db->raw($input); // @shieldci-ignore sql-injection

// Previous-line:
// @shieldci-ignore sql-injection
$query = $db->raw($input);

// Suppress multiple rules:
// @shieldci-ignore sql-injection, xss
echo $userInput;

// Suppress all rules on a line:
// @shieldci-ignore
echo $trustedContent;

/**
 * @shieldci-ignore sql-injection
 */
$query = $db->raw($input);