#!/usr/bin/env bash
# scripts/checks/phpstan.sh — static analysis at level 4 (Phase 1.A start).
# Called by lefthook (pre-commit, staged files) and CI (pr-base.yml, PR-range files).
#
# Args:
#   $1 — space- or newline-separated list of PHP file paths to analyse, OR empty.
#        Empty input → exit 0.
#
# Config:
#   PHPSTAN_LEVEL — override level for a one-off commit (e.g. lower locally on a
#                   noisy file). Default: 4 (per phpstan.neon).
#   PHPSTAN_MEMORY — default 768M.
#
# Exit: 0 = clean, 1 = errors.

set -uo pipefail

files="${1:-}"
[ -z "$files" ] && exit 0

PHPSTAN_LEVEL="${PHPSTAN_LEVEL:-4}"
PHPSTAN_MEMORY="${PHPSTAN_MEMORY:-768M}"

# Signal common/config/phpstan-bootstrap.php that it's running under PHPStan and may
# instantiate the stub Yii::$app. Without this the bootstrap guard refuses to load
# (a safety net against accidental runtime inclusion).
export PHPSTAN_RUNNING=1

# shellcheck disable=SC2086
echo "$files" | tr ' ' '\n' | grep -E '\.php$' | xargs --no-run-if-empty \
    vendor/bin/phpstan analyse \
        --level="$PHPSTAN_LEVEL" \
        --memory-limit="$PHPSTAN_MEMORY" \
        --no-progress \
        --error-format=table
