PHP 怎么静态分析徽章

wen PHP项目 3

本文目录导读:

PHP 怎么静态分析徽章

  1. 使用 Shields.io(最简单)
  2. 本地生成自定义 SVG 徽章
  3. 使用现成的 PHP 库
  4. 利用 CI 集成服务
  5. 高级方案:使用 Node.js badge 生成
  6. 完整生产级方案
  7. 建议的集成流程

在 PHP 中实现“静态分析徽章”(类似 GitHub 上的代码质量徽章),可以使用以下方案:

使用 Shields.io(最简单)

直接生成 SVG 徽章并集成到 CI 流程:

# 示例:PHPStan 结果徽章
https://img.shields.io/badge/PHPStan-Level%208-brightgreen

CI 集成示例(GitHub Actions)

name: Static Analysis
on: [push]
jobs:
  phpstan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: php-actions/composer@v6
      - name: PHPStan
        run: vendor/bin/phpstan analyse --no-progress --error-format=github
      - name: Generate Badge
        if: success()
        run: |
          # 生成自定义徽章
          echo "STATUS=success" >> $GITHUB_ENV
      # 上传徽章到某个位置(或服务)
      - name: Upload Badge
        uses: actions/upload-artifact@v3
        with:
          name: badge.svg
          path: badge.svg

本地生成自定义 SVG 徽章

创建 PHP 脚本生成 SVG:

<?php
// generate_badge.php
class BadgeGenerator {
    private int $passingChecks;
    private int $totalChecks;
    private string $toolName;
    public function __construct(string $toolName, int $passing, int $total) {
        $this->toolName = $toolName;
        $this->passingChecks = $passing;
        $this->totalChecks = $total;
    }
    public function generate(): string {
        $percentage = ($this->passingChecks / $this->totalChecks) * 100;
        $color = $percentage === 100 ? 'brightgreen' : 
                 ($percentage >= 80 ? 'yellow' : 'red');
        // 极简的 SVG 徽章
        return <<<SVG
        <svg xmlns="http://www.w3.org/2000/svg" width="120" height="20">
          <rect width="80" height="20" fill="grey"/>
          <rect x="80" width="40" height="20" fill="$color"/>
          <text x="40" y="14" fill="white" font-family="Arial" font-size="11" text-anchor="middle">
            {$this->toolName}
          </text>
          <text x="100" y="14" fill="white" font-family="Arial" font-size="11" text-anchor="middle">
            {$$this->passingChecks}/{$this->totalChecks}
          </text>
        </svg>
        SVG;
    }
}
// 用法
$badge = new BadgeGenerator('PHPStan', 98, 100);
file_put_contents('phpstan_badge.svg', $badge->generate());

使用现成的 PHP 库

1 badge 库(推荐)

composer require shields/badge
<?php
use ShieldsIO\Badge;
use ShieldsIO\Style\Flat;
$badge = new Badge();
$svg = $badge
    ->subject('PHPStan')
    ->status('Level 8')
    ->style(new Flat())
    ->color('brightgreen')
    ->render();
file_put_contents('phpstan_badge.svg', $svg);

2 PHP Static Analysis Tools(组合使用)

# 完整 CI 流程示例
name: PHP Quality
on: [push, pull_request]
jobs:
  static-analysis:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
          tools: phpstan, psalm, phpcs
      - name: Install dependencies
        run: composer install --prefer-dist
      # PHPStan
      - name: PHPStan Analysis
        run: phpstan analyse src --level=8 --no-progress
      # Psalm
      - name: Psalm Analysis
        run: psalm --show-info=false
      # Generate Combined Badge
      - name: Generate Badge
        run: |
          PHPSTAN_RESULT=$?
          // 如果所有检查通过,生成徽章
          echo "::set-output name=quality::pass"
      - name: Upload Badge
        uses: actions/upload-artifact@v3
        with:
          name: quality-badge
          path: quality-badge.svg

利用 CI 集成服务

1 GitHub Actions + actions-badge

- name: Badge Action
  uses: emibcn/badge-action@v2
  with:
    label: 'PHPStan'
    status: 'Level 8'
    color: 'green'
    path: 'badge.svg'

2 使用第三方服务(如 SonarQube)

- name: SonarQube Scan
  uses: SonarSource/sonarqube-scan-action@master

高级方案:使用 Node.js badge 生成

结合 Node.js 的 badge-maker 库:

npm install badge-maker
// generate-badge.js
const { makeBadge, ValidationError } = require('badge-maker');
const badge = makeBadge({
  label: 'PHPStan',
  message: 'Level 8',
  color: 'brightgreen',
  style: 'flat-square'
});
console.log(badge);

完整生产级方案

<?php
// quality_check.php
class QualityCheck {
    private array $results = [];
    public function runAll(): void {
        $tools = [
            'phpstan' => $this->runPHPStan(),
            'psalm'   => $this->runPsalm(),
            'phpcs'   => $this->runPHPCS(),
        ];
        $passed = array_filter($tools, fn($r) => $r === true);
        $total = count($tools);
        $passedCount = count($passed);
        $this->generateBadge($passedCount, $total);
    }
    private function runPHPStan(): bool {
        exec('vendor/bin/phpstan analyse --no-progress 2>&1', $output, $exitCode);
        return $exitCode === 0;
    }
    private function generateBadge(int $passed, int $total): void {
        $percentage = ($passed / $total) * 100;
        $color = $percentage === 100 ? 'brightgreen' : 
                 ($percentage >= 60 ? 'yellow' : 'red');
        $svg = '<svg xmlns="http://www.w3.org/2000/svg" width="120" height="20">...';
        file_put_contents('quality-badge.svg', $svg);
        // 可以推送到任何地方(如 CDN 或版本控制)
    }
}
$check = new QualityCheck();
$check->runAll();

建议的集成流程

  1. CI 工作流:PHP 静态分析在 CI 中运行
  2. 结果收集:解析工具输出,统计通过/失败
  3. 徽章生成:使用 SVG 或服务生成
  4. 部署:上传到静态托管(如 readme.io)或直接嵌入 README

最终效果

[![PHPStan](https://img.shields.io/badge/PHPStan-Level%208-brightgreen)](https://github.com/your-repo)

这样就能在 GitHub 等平台上显示质量徽章,实时反映代码质量状态。

抱歉,评论功能暂时关闭!