name: Build PHAR files

on:
  workflow_call:
    inputs:
      phpVersion:
        description: "The PHP version to use. Defaults to PHP 8.0 as used for the releases."
        type: string
        required: false
        default: '8.0'
      uploadArtifacts:
        description: "Whether or not to upload the artifacts. Defaults to false."
        type: boolean
        required: false
        default: false
      retentionDays:
        description: "How long uploaded artifacts should remain available (in days). Defaults to 1 day."
        type: string
        required: false
        default: 1
      createAttestations:
        description: "Whether or not to create attestations for the artifacts. Defaults to false."
        type: boolean
        required: false
        default: false

jobs:
  build:
    runs-on: ubuntu-latest
    name: "Build Phar on PHP: ${{ inputs.phpVersion }}"

    continue-on-error: ${{ inputs.phpVersion == 'nightly' }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: ${{ inputs.phpVersion }}
          coverage: none
          ini-values: phar.readonly=Off, error_reporting=-1, display_errors=On

      - name: Build the phar files
        run: php scripts/build-phar.php

      # Provide provenance for generated binaries.
      - name: Generate artifact attestations
        if: ${{ inputs.createAttestations == true }}
        uses: actions/attest-build-provenance@v2
        with:
          subject-path: |
            ${{ github.workspace }}/phpcs.phar
            ${{ github.workspace }}/phpcbf.phar

      - name: Upload the PHPCS phar
        if: ${{ inputs.uploadArtifacts == true }}
        uses: actions/upload-artifact@v4
        with:
          name: phpcs-phar
          path: ./phpcs.phar
          if-no-files-found: error
          retention-days: ${{ inputs.retentionDays }}

      - name: Upload the PHPCBF phar
        if: ${{ inputs.uploadArtifacts == true }}
        uses: actions/upload-artifact@v4
        with:
          name: phpcbf-phar
          path: ./phpcbf.phar
          if-no-files-found: error
          retention-days: ${{ inputs.retentionDays }}

      # Both the below only check a file which is rarely changed and therefore unlikely to have issues.
      # This test is about testing that the phars are functional, *not* about whether the code style complies.
      - name: 'PHPCS: check code style using the Phar file to test the Phar is functional'
        run: php phpcs.phar ./scripts

      - name: 'PHPCBF: fix code style using the Phar file to test the Phar is functional'
        run: php phpcbf.phar ./scripts
