PHP
Taking advantage of Git hooks, we will perform security analysis and style checks on our application before uploading it to the repository to minimize risks. To achieve this, we will configure the pre-commit file with the following Bash script, which will look for passwords, perform a static security analysis (SAST), run a code linter and launch the tests. Only if none of these checks fail will the commit be allowed.
#!/bin/bash
# Path to Gitleaks executable
docker run --rm -v $(pwd):/code zricethezav/gitleaks detect --source=/code -v
# Check Gitleaks output code
if [ $? -ne 0 ]; then
echo "Possible password leaks were detected. Please correct the problems before confirming."
exit 1
fi
# Run the linter (example: PHP_CodeSniffer)
# Make sure the linter is installed on your system
# Replace 'phpcs' with the appropriate command for your linter
docker run --rm -v "$(pwd):/app" osdo/php-pre-commit:8.1 /bin/sh -c "phpcs --standard=phpcs.xml --extensions=php"
# Check the linter output code
if [ $? -ne 0 ]; then
echo "Code style problems were encountered. Please correct the problems before confirming."
exit 1
fi
# Run static security analysis (SAST) (example: PHPStan)
# Make sure the SAST tool is installed on your system
# Replace 'phpstan' with the appropriate command for your SAST tool
docker run --rm -v "$(pwd):/app" osdo/php-pre-commit:8.1 /bin/sh -c "phpstan analyze www"
# Check the SAST output code
if [ $? -ne 0 ]; then
echo "Security vulnerabilities were detected in the code. Please correct the problems before confirming."
exit 1
fi
# Run unit tests (example: PHPUnit)
# Make sure PHPUnit is installed on your system
# Replace 'phpunit' with the appropriate command to run your unit tests
docker run --rm -v "$(pwd):/app" osdo/php-pre-commit:8.1 /bin/sh -c "phpunit -c www/phpunit.xml"
# Check the output code of the unit tests
if [ $? -ne 0 ]; then
echo "The unit tests did not pass. Please correct the problems before confirming."
exit 1
fi
# If all previous checks passed without problems, allow confirmation
exit 0