name: Unit Test

on:
    pull_request:
        branches:
            - main
    push:
        branches:
            - main
jobs:
    php_unit:
        runs-on: ubuntu-latest
        strategy:
            matrix:
                php-versions: ['7.4', '8.0', '8.1']
                wp-versions: ['6.7', '6.6', '6.5']
        name: PHP Unit Test on PHP ${{ matrix.php-versions }} / WP ${{ matrix.wp-versions }} Test
        services:
            mysql:
                image: mysql:5.7
                ports:
                    - 3306
                env:
                    MYSQL_ROOT_PASSWORD: wordpress
                    MYSQL_DATABASE: wordpress
                    MYSQL_USER: wordpress
                    MYSQL_PASSWORD: wordpress
        steps:
            - uses: actions/checkout@v4
            - name: Setup Node.js (.node-version)
              uses: actions/setup-node@v4
              with:
                  node-version: 20.x
            - name: Cache multiple paths
              uses: actions/cache@v4
              with:
                  path: vendor
                  key: ${{ runner.os }}-php${{ matrix.php-versions }}-${{ hashFiles('**/composer.lock') }}
            - name: Setup PHP ${{ matrix.php-versions }}
              uses: shivammathur/setup-php@v2
              with:
                  php-version: ${{ matrix.php-versions }}
            - name: install npm scripts
              run: npm install
            - name: Install Composer Packages
              run: composer install
            - name: Install WP-CLI
              run: |
                  curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
                  chmod +x wp-cli.phar
                  mv wp-cli.phar /usr/local/bin/wp
            - name: Build
              run: npm run build
            - name: Install several WordPress version by wp-env.override.json
              run: |
                  n=0
                  until [ $n -ge 5 ]
                  do
                      WP_ENV_CORE=WordPress/WordPress#${{ matrix.wp-versions }} WP_ENV_PHP_VERSION=${{ matrix.php-versions }} npm run wp-env start --update && break
                      n=$((n+1))
                      echo "Retrying wp-env start --update ($n)..."
                      sleep 15
                  done
                  if [ $n -ge 5 ]; then
                      echo "::error::wp-env start failed after 5 retries"
                      exit 1
                  fi
            - name: Check WordPress Version
              run: npm run wp-env run cli wp core version
            - name: Change Permission
              run: sudo chown -R $(whoami) ~/wp-env
            - name: Run PHP Unit Test
              run: npm run phpunit
