name: 🏥 Care API - Coverage Analysis on: push: branches: [main, develop, 'feature/*'] pull_request: branches: [main, develop] schedule: # Executar diariamente às 03:00 UTC - cron: '0 3 * * *' concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true env: PHP_VERSION: '8.1' NODE_VERSION: '18' COVERAGE_THRESHOLD: 70 jobs: # ====================================== # ANÁLISE DE CÓDIGO E PREPARAÇÃO # ====================================== prepare: name: 🔍 Preparação e Validação runs-on: ubuntu-latest outputs: should_run_coverage: ${{ steps.changes.outputs.php == 'true' || steps.changes.outputs.tests == 'true' }} php_files: ${{ steps.changes.outputs.php_files }} steps: - name: 📥 Checkout Code uses: actions/checkout@v4 with: fetch-depth: 0 - name: 🔄 Detect Changes uses: dorny/paths-filter@v2 id: changes with: filters: | php: - 'src/**/*.php' - 'composer.json' - 'composer.lock' tests: - 'tests/**/*.php' - 'phpunit.xml' - 'bin/**/*.sh' config: - '.github/workflows/coverage.yml' - 'phpcs.xml' - name: 📊 Output Changes run: | echo "PHP files changed: ${{ steps.changes.outputs.php }}" echo "Tests changed: ${{ steps.changes.outputs.tests }}" echo "Config changed: ${{ steps.changes.outputs.config }}" # ====================================== # COVERAGE ANALYSIS PRINCIPAL # ====================================== coverage: name: 📊 Coverage Analysis runs-on: ubuntu-latest needs: prepare if: needs.prepare.outputs.should_run_coverage == 'true' || github.event_name == 'schedule' strategy: fail-fast: false matrix: coverage-driver: ['pcov', 'xdebug'] services: mysql: image: mysql:8.0 env: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: wordpress_test ports: - 3306:3306 options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 steps: - name: 📥 Checkout Code uses: actions/checkout@v4 - name: 🐘 Setup PHP with Coverage uses: shivammathur/setup-php@v2 with: php-version: ${{ env.PHP_VERSION }} extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, mysql, mysqli, pdo_mysql coverage: ${{ matrix.coverage-driver }} tools: composer:v2, wp-cli - name: 📦 Get Composer Cache Directory id: composer-cache run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT - name: 🗄️ Cache Composer Dependencies uses: actions/cache@v3 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: | ${{ runner.os }}-composer- - name: 📦 Install Dependencies run: | composer install --prefer-dist --no-progress --no-interaction --optimize-autoloader composer show - name: 🔧 Setup WordPress Test Environment run: | bash bin/install-wp-tests.sh wordpress_test root root 127.0.0.1:3306 latest wp --info - name: ✅ Validate Environment run: | php --version php -m | grep -E "(pcov|xdebug)" phpunit --version mysql --version # ====================================== # EXECUTAR TESTES COM COVERAGE # ====================================== - name: 🧪 Run Unit Tests with Coverage run: | phpunit \ --testsuite="KiviCare API Unit Tests" \ --coverage-clover=coverage-unit.xml \ --coverage-html=coverage-unit-html \ --log-junit=junit-unit.xml - name: 🔗 Run Integration Tests with Coverage run: | phpunit \ --testsuite="KiviCare API Integration Tests" \ --coverage-clover=coverage-integration.xml \ --coverage-html=coverage-integration-html \ --log-junit=junit-integration.xml - name: 📋 Run Contract Tests with Coverage run: | phpunit \ --testsuite="KiviCare API Contract Tests" \ --coverage-clover=coverage-contract.xml \ --coverage-html=coverage-contract-html \ --log-junit=junit-contract.xml - name: 📊 Generate Combined Coverage Report run: | mkdir -p coverage-reports ./bin/generate-coverage.sh full ls -la coverage-* # ====================================== # ANÁLISE DE QUALIDADE # ====================================== - name: 🔍 Code Quality Analysis continue-on-error: true run: | # PHPLOC - Métricas de código if command -v phploc >/dev/null 2>&1; then phploc --log-xml=coverage-reports/phploc.xml src/ fi # PHPCPD - Código duplicado if command -v phpcpd >/dev/null 2>&1; then phpcpd --log-pmd=coverage-reports/phpcpd.xml src/ fi # PHPCS - Code Standards composer run phpcs || true # ====================================== # PROCESSAR RESULTADOS # ====================================== - name: 📈 Extract Coverage Metrics id: coverage run: | # Extrair percentagem de coverage do clover.xml if [ -f "coverage-reports/clover.xml" ]; then COVERAGE=$(php -r " \$xml = simplexml_load_file('coverage-reports/clover.xml'); \$elements = (int) \$xml->project->metrics['elements']; \$covered = (int) \$xml->project->metrics['coveredelements']; echo \$elements > 0 ? round((\$covered / \$elements) * 100, 2) : 0; ") echo "coverage=$COVERAGE" >> $GITHUB_OUTPUT echo "threshold_met=$([ $(echo "$COVERAGE >= $COVERAGE_THRESHOLD" | bc -l) -eq 1 ] && echo 'true' || echo 'false')" >> $GITHUB_OUTPUT else echo "coverage=0" >> $GITHUB_OUTPUT echo "threshold_met=false" >> $GITHUB_OUTPUT fi # ====================================== # UPLOAD DE ARTIFACTS # ====================================== - name: 📤 Upload Coverage Reports uses: actions/upload-artifact@v3 if: always() with: name: coverage-reports-${{ matrix.coverage-driver }}-${{ github.run_number }} path: | coverage-*.xml coverage-*-html/ coverage-reports/ coverage-dashboard.html junit-*.xml retention-days: 30 - name: 📤 Upload Test Results uses: actions/upload-artifact@v3 if: always() with: name: test-results-${{ matrix.coverage-driver }}-${{ github.run_number }} path: | junit-*.xml tests/_output/ retention-days: 7 # ====================================== # INTEGRAÇÃO CODECOV # ====================================== - name: 📊 Upload to Codecov uses: codecov/codecov-action@v3 if: always() with: files: ./coverage-reports/clover.xml,./coverage-unit.xml,./coverage-integration.xml,./coverage-contract.xml flags: ${{ matrix.coverage-driver }} name: care-api-${{ matrix.coverage-driver }} fail_ci_if_error: false verbose: true env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} # ====================================== # VALIDAÇÃO DE THRESHOLD # ====================================== - name: 🎯 Validate Coverage Threshold if: steps.coverage.outputs.threshold_met == 'false' run: | echo "❌ Coverage threshold not met!" echo "Current: ${{ steps.coverage.outputs.coverage }}%" echo "Required: ${{ env.COVERAGE_THRESHOLD }}%" exit 1 # ====================================== # COMENTÁRIO NO PR # ====================================== - name: 💬 Comment Coverage Results uses: actions/github-script@v6 if: github.event_name == 'pull_request' && always() with: script: | const coverage = '${{ steps.coverage.outputs.coverage }}'; const threshold = '${{ env.COVERAGE_THRESHOLD }}'; const driver = '${{ matrix.coverage-driver }}'; const thresholdMet = '${{ steps.coverage.outputs.threshold_met }}' === 'true'; const emoji = thresholdMet ? '✅' : '❌'; const status = thresholdMet ? 'PASSED' : 'FAILED'; const comment = `## 📊 Coverage Report (${driver}) ${emoji} **Coverage Status: ${status}** - **Current Coverage:** ${coverage}% - **Required Threshold:** ${threshold}% - **Coverage Driver:** ${driver} ### 📈 Detailed Reports - [Coverage Dashboard](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}) - [Unit Tests Coverage](coverage-unit-html/index.html) - [Integration Tests Coverage](coverage-integration-html/index.html) - [Contract Tests Coverage](coverage-contract-html/index.html) ### 🎯 Quality Metrics - Code coverage analysis completed with ${driver} - Reports available as workflow artifacts - Historical coverage tracking via Codecov --- 🏥 **Care API Healthcare Management System** 💚 *Powered by Descomplicar® Crescimento Digital*`; github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: comment }); # ====================================== # MERGE E COMPARAÇÃO DE RELATÓRIOS # ====================================== merge-reports: name: 🔀 Merge Coverage Reports runs-on: ubuntu-latest needs: coverage if: always() steps: - name: 📥 Checkout Code uses: actions/checkout@v4 - name: 🐘 Setup PHP uses: shivammathur/setup-php@v2 with: php-version: ${{ env.PHP_VERSION }} tools: composer:v2, phpcov - name: 📥 Download Coverage Artifacts uses: actions/download-artifact@v3 with: path: artifacts/ - name: 🔀 Merge Coverage Reports run: | mkdir -p merged-coverage # Localizar todos os arquivos clover.xml find artifacts/ -name "clover.xml" -exec cp {} merged-coverage/ \; -exec echo "Found: {}" \; # Se existem múltiplos relatórios, usar phpcov para merge if [ $(find merged-coverage/ -name "*.xml" | wc -l) -gt 1 ]; then composer global require phpunit/phpcov ~/.composer/vendor/bin/phpcov merge --html merged-coverage-html merged-coverage/ fi - name: 📤 Upload Merged Reports uses: actions/upload-artifact@v3 if: always() with: name: merged-coverage-reports-${{ github.run_number }} path: | merged-coverage/ merged-coverage-html/ retention-days: 90 # ====================================== # NOTIFICAÇÃO DE STATUS # ====================================== notify: name: 📢 Notify Status runs-on: ubuntu-latest needs: [coverage, merge-reports] if: always() && (github.event_name == 'push' || github.event_name == 'schedule') steps: - name: 🔔 Notify Success if: needs.coverage.result == 'success' run: | echo "✅ Coverage analysis completed successfully!" echo "All tests passed and coverage thresholds met." - name: 🚨 Notify Failure if: needs.coverage.result == 'failure' run: | echo "❌ Coverage analysis failed!" echo "Check the workflow logs for details." exit 1 # ====================================== # CONFIGURAÇÃO DE ENVIRONMENT # ====================================== env: CI: true WP_TESTS_DIR: /tmp/wordpress-tests-lib WP_CORE_DIR: /tmp/wordpress