name: Run unit tests on PR
on: 
  pull_request
jobs:
  test:
    name: PHP ${{ matrix.php }} WP ${{ matrix.wp }} MU ${{ matrix.multisite }} DB ${{ matrix.db }}
    timeout-minutes: 15
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        # We test against the earliest and latest PHP versions for each major supported version.
        php: [ '7.2', '7.4', '8.0', '8.3' ]
        wp: [ '6.5', '6.6', 'latest', 'nightly' ]
        multisite: [ '0', '1' ]
        db: [ 'mysql:5.6', 'mysql:8.1', 'mariadb:10.4', 'mariadb:10.6']
        exclude:
          # WordPress 6.6+ requires PHP 7.2+
          - php: 7.2
            wp: 6.6
          - php: 7.2
            wp: latest
          - php: 7.2
            wp: nightly
    services:
      database:
        image: ${{ matrix.db }}
        env:
          MYSQL_ROOT_PASSWORD: root
        ports:
          - 3306:3306
        options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=5
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Setup PHP
        uses: shivammathur/setup-php@0f7f1d08e3e32076e51cae65eb0b0c871405b16e # v2.34.1
        with:
          php-version: ${{ matrix.php }}
          tools: composer
          extensions: mysql
          coverage: none

      - name: Tool versions
        run: |
          php --version
          composer --version

      - name: Get composer cache directory
        id: composer-cache
        run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT

      - name: Cache dependencies
        uses: actions/cache@v4
        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

      - name: Install Subversion
        run: sudo apt-get update && sudo apt-get install -y subversion

      - name: Init DB and WP
        run: |
          # Use mysql_native_password when using PHP < 7.4 and MySQL >= 8.0
          if [ "$(php -r 'echo version_compare(PHP_VERSION, "7.4", "<");')" -eq 1 ] && [ "${{ matrix.db }}" == "mysql:8.1" ]; then
            mysql -uroot -proot -h127.0.0.1 -e "ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root'; FLUSH PRIVILEGES;"
          fi
          ./tests/bin/install.sh woo_test root root 127.0.0.1 ${{ matrix.wp }}

      - name: Run tests
        run: |
          ./vendor/bin/phpunit --version
          WP_MULTISITE=${{ matrix.multisite }} ./vendor/bin/phpunit -c ./tests/phpunit.xml.dist

      - name: Code Coverage
        run: |
          bash <(curl -s https://codecov.io/bash)
