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@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0

      - name: Setup PHP
        uses: shivammathur/setup-php@bf6b4fbd49ca58e4608c9c89fba0b8d90bd2a39f # 2.35.5
        with:
          php-version: ${{ inputs.phpVersion }}
          coverage: none
          ini-values: phar.readonly=Off, error_reporting=-1, display_errors=On, display_startup_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@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3.0.0
        with:
          subject-path: |
            ${{ github.workspace }}/phpcs.phar
            ${{ github.workspace }}/phpcbf.phar

      - name: Upload the PHPCS phar
        if: ${{ inputs.uploadArtifacts == true }}
        uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
        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@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
        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
