#!/usr/bin/env bash

#ddev-generated
## Command provided by https://github.com/ddev/ddev-drupal-contrib
## Description: Run phpstan inside the web container
## Usage: phpstan [flags] [args]
## Example: "ddev phpstan" or "ddev phpstan -n"
## ExecRaw: true
## MutagenSync: true

set -eu -o pipefail

if ! command -v phpstan >/dev/null; then
  echo "phpstan is not available. You may need to 'ddev poser'"
  exit 1
fi
# PHPStan discovers phpstan.neon.dist and phpstan.dist.neon on its own, so only scaffold when neither exists.
if [ -e phpstan.neon ] || { [ ! -e phpstan.neon.dist ] && [ ! -e phpstan.dist.neon ]; }; then
  test -e phpstan.neon || curl -OL https://git.drupalcode.org/project/gitlab_templates/-/raw/default-ref/assets/phpstan.neon
  # See https://git.drupalcode.org/project/gitlab_templates/-/commit/a107b7f1f79af12e0b09f70be47b68e3f69b4504
  sed -i 's/BASELINE_PLACEHOLDER/phpstan-baseline.neon/g' phpstan.neon
  # Add an empty baseline file to ensure it exists.
  test -e phpstan-baseline.neon || touch phpstan-baseline.neon
fi

EXTENSION_DIRECTORY=$DDEV_DOCROOT/$DRUPAL_PROJECTS_PATH/${DDEV_SITENAME//-/_}
cd "$EXTENSION_DIRECTORY" || exit 1
# Ensure PHPStan configuration is symlinked from project root.
ln -s $DDEV_DOCROOT/phpstan.neon 2>/dev/null || true
ln -s $DDEV_DOCROOT/phpstan-baseline.neon 2>/dev/null || true
phpstan analyze . "$@"
