#!/bin/bash
USE_PHP_CS_FIXER=1
USE_PHP_STAN=1

PHP_FILES=""
while read line; do
    PHP_FILES+="${line} "
done < <(git diff --cached --name-only --diff-filter=ACRM | grep -E '\.php$');

if [[ "${USE_PHP_STAN}" == 1 ]]; then

    if [ -n "$PHP_FILES" ]; then

        docker run --rm --volume "$(pwd)":/app composer:2.5.5 /bin/bash -c "vendor/bin/phpstan analyze -c phpstan.dist.neon"

        if [[ $? -ne 0 ]]; then
            printf "There are errors in your code quality. Check with phpstan\n"
            printf "vendor/bin/phpstan analyze -c phpstan.dist.neon"
            exit 1
        else
            printf "No errors found, fixed files staged."
        fi

    fi
fi

if [[ "${USE_PHP_CS_FIXER}" == 1 ]]; then

    printf ${PHP_FILES}

    if [ -n "$PHP_FILES" ]; then

        docker run --rm --volume "$(pwd)":/app composer:2.5.5 /bin/bash -c "vendor/bin/php-cs-fixer fix --ansi -v --config=.php-cs-fixer.dist.php --path-mode=intersection ${PHP_FILES}"

        if [[ $? -ne 0 ]]; then
            printf "Tried fixing code with PHP CS Fixer, but something went wront.\n"
            exit 1
        else
            git add ${PHP_FILES}
            printf "No errors found, fixed files staged.\n"
        fi

    fi
fi
