name: CI

on:
  push:
  pull_request:

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

jobs:
  build:
    name: Build and Test
    runs-on: ubuntu-latest
    strategy:
      matrix:
        php:
          - '7.4'
          - '8.0'
          - '8.1'
          - '8.2'
        include:
          - php: '8.2'
            latest: true
    steps:
      - uses: actions/checkout@v3

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: ${{ matrix.php }}
          ini-values: memory_limit=-1
          coverage: pcov
          tools: composer, cs2pr, php-cs-fixer

      - name: Get Composer Cache Directory
        id: composer-cache
        run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
      
      - 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 prerequisites
        run: |
          wget -O box.phar https://github.com/humbug/box/releases/download/4.3.8/box.phar
          echo "BOX_BIN=$(pwd)/box.phar" >> $GITHUB_ENV
          sudo chown -R $(whoami):$(whoami) .

      - name: Install dependencies
        if: matrix.latest
        run: composer install --prefer-dist --no-interaction --no-progress --ansi

      - name: Update dependencies
        if: "!matrix.latest"
        run: composer update --no-interaction --no-progress --ansi

      - name: Enable code coverage
        if: matrix.latest
        run: echo "COVERAGE=1" >> $GITHUB_ENV

      - name: Run PHPUnit
        run: vendor/bin/simple-phpunit ${{ matrix.latest && '--coverage-clover build/logs/phpunit/clover.xml' || '' }}

      - name: Run PHP CS Fixer
        if: matrix.latest
        run: php-cs-fixer fix --dry-run --format=checkstyle --ansi | cs2pr

      - name: Run PHPStan 
        if: matrix.latest
        run: vendor/bin/phpstan analyse --ansi

      - name: Run e2e tests
        if: matrix.latest
        run: bin/compile

      - name: Upload coverage results to Coveralls
        if: matrix.latest
        env:
          COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          composer global require --prefer-dist --no-interaction --no-progress --ansi php-coveralls/php-coveralls
          export PATH="$PATH:$HOME/.composer/vendor/bin"
          php-coveralls --coverage_clover=build/logs/phpunit/clover.xml -v
        continue-on-error: true
