name: Setup PHP
description: Setup PHP with Composer dependencies

inputs:
  php-version:
    description: PHP version to use
    required: false
    default: '8.1'

runs:
  using: composite
  steps:
    - name: Install PHP (DIY)
      shell: bash
      run: |
        set -euo pipefail

        PHPV="${{ inputs.php-version }}"

        sudo apt-get update
        sudo apt-get install -y \
          software-properties-common \
          ca-certificates \
          lsb-release \
          curl \
          unzip

        sudo add-apt-repository -y ppa:ondrej/php
        sudo apt-get update

        sudo apt-get install -y \
          "php${PHPV}-cli" \
          "php${PHPV}-mbstring" \
          "php${PHPV}-pgsql" \
          "php${PHPV}-xml" \
          "php${PHPV}-curl" \
          "php${PHPV}-zip"

        sudo update-alternatives --set php "/usr/bin/php${PHPV}"

        php -v
        php -m | grep -E 'mbstring|PDO|pgsql' || true

    - name: Install Composer (verified)
      shell: bash
      run: |
        set -euo pipefail

        EXPECTED="$(curl -fsSL https://composer.github.io/installer.sig)"
        php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
        ACTUAL="$(php -r "echo hash_file('sha384', 'composer-setup.php');")"

        if [ "$EXPECTED" != "$ACTUAL" ]; then
          echo "Composer installer signature mismatch" >&2
          rm -f composer-setup.php
          exit 1
        fi

        sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
        rm -f composer-setup.php

        composer -V

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

    - name: Cache Composer dependencies
      uses: actions/cache@v4
      with:
        path: ${{ steps.composer-cache.outputs.dir }}
        key: ${{ runner.os }}-php${{ inputs.php-version }}-composer-${{ hashFiles('**/composer.lock') }}
        restore-keys: |
          ${{ runner.os }}-php${{ inputs.php-version }}-composer-

    - name: Install dependencies
      shell: bash
      run: composer install --prefer-dist --no-progress --no-interaction
