Skip to content

Instantly share code, notes, and snippets.

@Isinlor
Last active January 21, 2022 09:59
Show Gist options
  • Save Isinlor/9a321c814747c75f06566892df99f50b to your computer and use it in GitHub Desktop.
Save Isinlor/9a321c814747c75f06566892df99f50b to your computer and use it in GitHub Desktop.
Basic Makefile and Git Hook with static code analysis
/bin/
/vendor/
{
"name": "isinlor/makefile",
"type": "project",
"license": "MIT",
"authors": [
{
"name": "Tomasz Darmetko",
"email": "tomasz.darmetko@gmail.com"
}
],
"require": {},
"require-dev": {
"sebastian/phpcpd": "@dev",
"squizlabs/php_codesniffer": "@dev",
"phpmd/phpmd": "@dev",
"phpstan/phpstan": "@dev",
"vimeo/psalm": "@dev"
},
"config": {
"bin-dir": "bin"
},
"prefer-stable": true
}
#
# Makefile
#
# You can run it from command line by typing eg.:
# make review
#
# You can read an user friendly introduction to Makefile basics here:
# https://gist.github.com/Isinlor/035399fe952f5e3ced4280a5cc635a84
#
# provides an automatic review of the code
review: phplint phpcpd phpmd phpstan psalm phpcs
# checks syntax of source files and spec files
phplint: src
php -l ./src
# runs copy paste detection
phpcpd: install
bin/phpcpd ./src --min-lines=1 --min-tokens=35
# runs PHP Code Sniffer
phpcs: install
bin/phpcs ./src --runtime-set ignore_warnings_on_exit 1
# runs PHP Code Sniffer automatic fixer
phpcs-fix: install
bin/phpcbf ./src --runtime-set ignore_warnings_on_exit 1
# runs PHP Mess Detector
phpmd: install
bin/phpmd ./src text ruleset.xml
# runs PHPStan
phpstan: install
bin/phpstan analyse ./src --level=max --no-progress
# runs Psalm
psalm: install
bin/psalm
# install dependencies allowing algorithm to run
install: vendor/autoload.php .git/hooks/pre-commit
# install dependencies trough the composer
vendor/autoload.php:
composer install --quiet
# check if git hooks exits; if it does then create pre commit hook by linking pre-commit.sh
.git/hooks/pre-commit:
[ ! -d .git/hooks ] || [ -L .git/hooks/pre-commit ] || ln -s -f ../../pre-commit.sh .git/hooks/pre-commit
src:
mkdir src
<?xml version="1.0"?>
<ruleset name="PSR2">
<description>The PSR-2 coding standard.</description>
<arg name="tab-width" value="4"/>
<!-- 2. General -->
<!-- 2.1 Basic Coding Standard -->
<!-- Include the whole PSR-1 standard -->
<rule ref="PSR1"/>
<!-- 2.2 Files -->
<!-- All PHP files MUST use the Unix LF (linefeed) line ending. -->
<rule ref="Generic.Files.LineEndings">
<properties>
<property name="eolChar" value="\n"/>
</properties>
</rule>
<!-- All PHP files MUST end with a single blank line. -->
<!-- checked in Files/EndFileNewlineSniff -->
<!-- The closing ?> tag MUST be omitted from files containing only PHP. -->
<!-- checked in Files/ClosingTagSniff -->
<!-- 2.3 Lines -->
<!-- The soft limit on line length MUST be 120 characters; automated style checkers MUST warn but MUST NOT error at the soft limit. -->
<rule ref="Generic.Files.LineLength">
<properties>
<property name="lineLimit" value="120"/>
<property name="absoluteLineLimit" value="0"/>
</properties>
</rule>
<!-- There MUST NOT be trailing whitespace at the end of non-blank lines. -->
<rule ref="Squiz.WhiteSpace.SuperfluousWhitespace">
<properties>
<property name="ignoreBlankLines" value="true"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.SuperfluousWhitespace.StartFile">
<severity>0</severity>
</rule>
<rule ref="Squiz.WhiteSpace.SuperfluousWhitespace.EndFile">
<severity>0</severity>
</rule>
<rule ref="Squiz.WhiteSpace.SuperfluousWhitespace.EmptyLines">
<severity>0</severity>
</rule>
<!-- There MUST NOT be more than one statement per line. -->
<rule ref="Generic.Formatting.DisallowMultipleStatements"/>
<!-- 2.4 Indenting -->
<!-- Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting. -->
<rule ref="Generic.WhiteSpace.ScopeIndent">
<properties>
<property name="ignoreIndentationTokens" type="array" value="T_COMMENT,T_DOC_COMMENT_OPEN_TAG"/>
</properties>
</rule>
<rule ref="Generic.WhiteSpace.DisallowTabIndent"/>
<!-- 2.5 Keywords and True/False/Null -->
<!-- PHP keywords MUST be in lower case. -->
<rule ref="Generic.PHP.LowerCaseKeyword"/>
<!-- The PHP constants true, false, and null MUST be in lower case. -->
<rule ref="Generic.PHP.LowerCaseConstant"/>
<!-- 3. Namespace and Use Declarations -->
<!-- When present, there MUST be one blank line after the namespace declaration. -->
<!-- checked in Namespaces/NamespaceDeclarationSniff -->
<!-- When present, all use declarations MUST go after the namespace declaration.
There MUST be one use keyword per declaration.
There MUST be one blank line after the use block. -->
<!-- checked in Namespaces/UseDeclarationSniff -->
<!-- 4. Classes, Properties, and Methods -->
<!-- 4.1. Extends and Implements -->
<!-- The extends and implements keywords MUST be declared on the same line as the class name.
The opening brace for the class go MUST go on its own line; the closing brace for the class MUST go on the next line after the body.
Lists of implements MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one interface per line. -->
<!-- checked in Classes/ClassDeclarationSniff -->
<!-- 4.2. Properties -->
<!-- Visibility MUST be declared on all properties.
The var keyword MUST NOT be used to declare a property.
There MUST NOT be more than one property declared per statement.
Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility. -->
<!-- checked in Classes/PropertyDeclarationSniff -->
<!-- 4.3 Methods -->
<!-- Visibility MUST be declared on all methods. -->
<rule ref="Squiz.Scope.MethodScope"/>
<rule ref="Squiz.WhiteSpace.ScopeKeywordSpacing"/>
<!-- Method names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility. -->
<!-- checked in Methods/MethodDeclarationSniff -->
<!-- Method names MUST NOT be declared with a space after the method name. The opening brace MUST go on its own line, and the closing brace MUST go on the next line following the body. There MUST NOT be a space after the opening parenthesis, and there MUST NOT be a space before the closing parenthesis. -->
<!-- checked in Methods/FunctionClosingBraceSniff -->
<rule ref="Squiz.Functions.FunctionDeclaration"/>
<rule ref="Squiz.Functions.LowercaseFunctionKeywords"/>
<!-- 4.4 Method Arguments -->
<!-- In the argument list, there MUST NOT be a space before each comma, and there MUST be one space after each comma. -->
<rule ref="Squiz.Functions.FunctionDeclarationArgumentSpacing">
<properties>
<property name="equalsSpacing" value="1"/>
</properties>
</rule>
<rule ref="Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingAfterHint">
<severity>0</severity>
</rule>
<!-- Method arguments with default values MUST go at the end of the argument list. -->
<rule ref="PEAR.Functions.ValidDefaultValue"/>
<!-- Argument lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument per line. When the argument list is split across multiple lines, the closing parenthesis and opening brace MUST be placed together on their own line with one space between them. -->
<rule ref="Squiz.Functions.MultiLineFunctionDeclaration"/>
<!-- 4.5 abstract, final, and static -->
<!-- When present, the abstract and final declarations MUST precede the visibility declaration.
When present, the static declaration MUST come after the visibility declaration. -->
<!-- checked in Methods/MethodDeclarationSniff -->
<!-- 4.6 Method and Function Calls -->
<!-- When making a method or function call, there MUST NOT be a space between the method or function name and the opening parenthesis, there MUST NOT be a space after the opening parenthesis, and there MUST NOT be a space before the closing parenthesis. In the argument list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.
Argument lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument per line. -->
<rule ref="Generic.Functions.FunctionCallArgumentSpacing"/>
<rule ref="PSR2.Methods.FunctionCallSignature.SpaceAfterCloseBracket">
<severity>0</severity>
</rule>
<!-- 5. Control Structures -->
<!-- The general style rules for control structures are as follows:
There MUST be one space after the control structure keyword
There MUST NOT be a space after the opening parenthesis
There MUST NOT be a space before the closing parenthesis
There MUST be one space between the closing parenthesis and the opening brace
The structure body MUST be indented once
The closing brace MUST be on the next line after the body -->
<rule ref="Squiz.ControlStructures.ControlSignature"/>
<!-- Controversial rules, see https://github.com/squizlabs/PHP_CodeSniffer/issues/883#issuecomment-216686359 -->
<!--<rule ref="Squiz.WhiteSpace.ControlStructureSpacing"/>-->
<!--
When 3.0 is released, change this to:
<rule ref="Squiz.WhiteSpace.ControlStructureSpacing.SpacingAfterOpen" />
<rule ref="Squiz.WhiteSpace.ControlStructureSpacing.SpacingBeforeClose" />
-->
<!--<rule ref="Squiz.WhiteSpace.ControlStructureSpacing.SpacingAfterOpenBrace">-->
<!--<severity>0</severity>-->
<!--</rule>-->
<!--<rule ref="Squiz.WhiteSpace.ControlStructureSpacing.SpaceBeforeCloseBrace">-->
<!--<severity>0</severity>-->
<!--</rule>-->
<!--<rule ref="Squiz.WhiteSpace.ControlStructureSpacing.LineAfterClose">-->
<!--<severity>0</severity>-->
<!--</rule>-->
<!--<rule ref="Squiz.WhiteSpace.ControlStructureSpacing.NoLineAfterClose">-->
<!--<severity>0</severity>-->
<!--</rule>-->
<rule ref="Squiz.WhiteSpace.ScopeClosingBrace"/>
<rule ref="Squiz.ControlStructures.ForEachLoopDeclaration"/>
<rule ref="Squiz.ControlStructures.ForLoopDeclaration"/>
<rule ref="Squiz.ControlStructures.LowercaseDeclaration"/>
<!-- checked in ControlStructures/ControlStructureSpacingSniff -->
<!-- The body of each structure MUST be enclosed by braces. This standardizes how the structures look, and reduces the likelihood of introducing errors as new lines get added to the body. -->
<rule ref="Generic.ControlStructures.InlineControlStructure"/>
<!-- 5.1. if, elseif, else -->
<!-- The keyword elseif SHOULD be used instead of else if so that all control keywords look like single words. -->
<!-- checked in ControlStructures/ElseIfDeclarationSniff -->
<!-- 5.2. switch, case -->
<!-- The case statement MUST be indented once from switch, and the break keyword (or other terminating keyword) MUST be indented at the same level as the case body. There MUST be a comment such as // no break when fall-through is intentional in a non-empty case body. -->
<!-- checked in ControlStructures/SwitchDeclarationSniff -->
<!-- 6. Closures -->
<!-- Closures MUST be declared with a space after the function keyword, and a space before and after the use keyword.
The opening brace MUST go on the same line, and the closing brace MUST go on the next line following the body.
There MUST NOT be a space after the opening parenthesis of the argument list or variable list, and there MUST NOT be a space before the closing parenthesis of the argument list or variable list.
In the argument list and variable list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.
Closure arguments with default values MUST go at the end of the argument list.
Argument lists and variable lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument or variable per line.
When the ending list (whether or arguments or variables) is split across multiple lines, the closing parenthesis and opening brace MUST be placed together on their own line with one space between them. -->
<!-- checked in Squiz.Functions.MultiLineFunctionDeclaration -->
</ruleset>
#!/usr/bin/env bash
#
# This is a script that should be run before each commit, so called Git Hook (see: http://githooks.com/)
#
# This file will be linked in .git/hooks/pre-commit by the recipe in the Makefile and therefore run before each commit.
#
# What does it exactly do?
# The main objective of this file is to run `make review` command on the state of the code in your git index (staging).
#
# To do this it will try to:
# - Create a temporary directory. This is necessary, because the working copy may contain changes that you are
# currently working on and do not want to commit yet. Therefore the changes should not affect the outcome of the
# review. Using a temporary directory instead of git stash makes sure that there will be no issue with eventual conflicts.
# See: http://stackoverflow.com/questions/20479794/how-do-i-properly-git-stash-pop-in-pre-commit-hooks-to-get-a-clean-working-tree
# - Checkout the state of the index of your git repository (i.e. what you are trying to commit) to the temporary directory.
# - Run `make review` command.
# - Remove the temporary directory.
#
# To learn more about bash scripting, please read: http://s.ntnu.no/bashguide.pdf
#
# !!!DEBUGGING!!!
#
# In order to debug this script you will probably want to comment out the line removing temporary directory.
# (See removeTmpReviewDir function)
#
# Then inspect the process manually.
#
# !!!DEBUGGING!!!
#
# fix for SourceTree, on MacOS terminals and full .apps have completely different environments (and PATH variables)
# see: https://community.atlassian.com/t5/Bitbucket-questions/SourceTree-Hook-failing-because-paths-don-t-seem-to-be-set/qaq-p/274792
source ~/.bash_profile
# the directory of the script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# temporary review directory
TMP_REVIEW_DIR="$DIR/tmp-review"
GREEN_COLOR='\033[0;32m' # green color
RED_COLOR='\033[0;31m' # red color
RESET_COLOR='\033[0m' # reset color
# inform about failed review
function reviewFailed {
echo ''
echo -e "${RED_COLOR}✗ Review failed... You can not commit!${RESET_COLOR}"
echo ''
exit 1;
}
# remove temporary directory
function removeTmpReviewDir {
rm -rf "$TMP_REVIEW_DIR"
}
# check if temporary directory exists and prompt to remove it if it does
if [ -d "$TMP_REVIEW_DIR" ]; then
echo ''
echo "The temporary directory $TMP_REVIEW_DIR already exists!"
echo "Run a following command to remove the directory:"
echo ''
echo "rm -rf $TMP_REVIEW_DIR"
echo ''
exit 1;
fi
# create temporary directory to make the review there
# making review in a separate directory avoids changing files in the working directory
# see http://stackoverflow.com/questions/20479794/how-do-i-properly-git-stash-pop-in-pre-commit-hooks-to-get-a-clean-working-tree
mkdir -p "$TMP_REVIEW_DIR"
# check if temporary directory was created
if [[ ! -d "$TMP_REVIEW_DIR" ]]; then
echo ''
echo -e "${RED_COLOR}Could not create temporary directory!${RESET_COLOR}"
echo ''
exit 1
fi
# register the reviewFailed function to be called on the ERR signal
trap reviewFailed ERR
# register the removeTmpReviewDir function to be called on exit
trap removeTmpReviewDir EXIT
# checkout all files from the index to the temporary directory
git checkout-index --prefix="$TMP_REVIEW_DIR/" -a
cd "$TMP_REVIEW_DIR"
echo ''
echo "The review is running, please wait..."
echo ''
# make the review (run jobs in parallel); ignore standard output
make review -j > /dev/null
echo ''
echo -e "${GREEN_COLOR}✓ All done! You are fine to commit! :)${RESET_COLOR}"
echo ''
<?xml version="1.0"?>
<psalm
totallyTyped="false"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config file:///mnt/c/Users/Tomek/Projects/Makefile/vendor/vimeo/psalm/config.xsd"
>
<projectFiles>
<directory name="src" />
</projectFiles>
<issueHandlers>
<LessSpecificReturnType errorLevel="info" />
<!-- level 3 issues - slightly lazy code writing, but provably low false-negatives -->
<DeprecatedMethod errorLevel="info" />
<DeprecatedProperty errorLevel="info" />
<DeprecatedClass errorLevel="info" />
<DeprecatedInterface errorLevel="info" />
<MissingClosureReturnType errorLevel="info" />
<MissingReturnType errorLevel="info" />
<MissingPropertyType errorLevel="info" />
<InvalidDocblock errorLevel="info" />
<MisplacedRequiredParam errorLevel="info" />
<PropertyNotSetInConstructor errorLevel="info" />
<MissingConstructor errorLevel="info" />
<MissingClosureParamType errorLevel="info" />
<MissingParamType errorLevel="info" />
<RedundantCondition errorLevel="info" />
<DocblockTypeContradiction errorLevel="info" />
<RedundantConditionGivenDocblockType errorLevel="info" />
<UnresolvableInclude errorLevel="info" />
<RawObjectIteration errorLevel="info" />
</issueHandlers>
</psalm>
<?xml version="1.0"?>
<ruleset name="Distribution Algorithm"
xmlns="http://pmd.sf.net/ruleset/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0
http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:noNamespaceSchemaLocation="
http://pmd.sf.net/ruleset_xml_schema.xsd">
<description>
Rule set for maintaining code quality.
Therefore the rules about code complexity are quite strict.
I would highly recommend reading "Clean Code: A Handbook of Agile Software Craftsmanship".
Especially "Code smells and heuristics" chapter.
Also make sure to take a look at: https://sourcemaking.com/refactoring/smells
</description>
<!--
PHP Mess Detector documentation:
- built-in rule sets: https://phpmd.org/rules/index.html
- creating a custom rule set: https://phpmd.org/documentation/creating-a-ruleset.html
-->
<!-- Rule Sets -->
<rule ref="rulesets/codesize.xml">
<exclude name="CyclomaticComplexity" />
<exclude name="NPathComplexity" />
<exclude name="ExcessiveMethodLength" />
<exclude name="ExcessiveClassLength" />
<exclude name="ExcessiveParameterList" />
<exclude name="ExcessivePublicCount" />
</rule>
<rule ref="rulesets/controversial.xml" />
<rule ref="rulesets/design.xml">
<exclude name="CouplingBetweenObjects" />
</rule>
<rule ref="rulesets/naming.xml">
<exclude name="ShortVariable" />
<exclude name="LongVariable" />
<exclude name="BooleanGetMethodName" />
</rule>
<rule ref="rulesets/unusedcode.xml">
<exclude name="UnusedLocalVariable" />
</rule>
<!-- Specific rules configuration -->
<!-- Low NPathComplexity improve comprehensibility of your code and helps keep your unit tests simple and thorough.
See https://modess.io/npath-complexity-cyclomatic-complexity-explained/ -->
<rule ref="rulesets/codesize.xml/NPathComplexity">
<properties>
<property name="minimum" value="64"/>
</properties>
</rule>
<!-- This rule force you to keep your methods simple.
You should extract sub-methods from your method if you exceed this limit.
It will make your code more readable, reusable and self documented. -->
<rule ref="rulesets/codesize.xml/ExcessiveMethodLength">
<properties>
<property name="minimum" value="50"/>
<property name="ignore-whitespace" value="true"/>
</properties>
</rule>
<!-- This rule force you to keep your classes simple.
You should split your class if you exceed this limit. -->
<rule ref="rulesets/codesize.xml/ExcessiveClassLength">
<properties>
<property name="minimum" value="125"/>
<property name="ignore-whitespace" value="true"/>
</properties>
</rule>
<!-- This rule force you to keep your classes simple.
You should split your class or make a new one to keep your parameters together as a coherent concept.
This will help you reduce amount of mocking in the test, therefore make them less brittle.
It will make your code more readable, reusable and self documented. -->
<rule ref="rulesets/codesize.xml/ExcessiveParameterList">
<properties>
<property name="minimum" value="6"/>
</properties>
</rule>
<!-- This rule force you to keep your classes simple.
You should split your class if you exceed this limit.
You may want to take a look at ValueObjects. -->
<rule ref="rulesets/codesize.xml/ExcessivePublicCount">
<properties>
<property name="minimum" value="10"/>
</properties>
</rule>
<!-- This rule force you to keep your classes simple.
You should split your class if you exceed this limit.
Low coupling helps keep unit tests simple and thorough. -->
<rule ref="rulesets/design.xml/CouplingBetweenObjects">
<properties>
<property name="minimum" value="10"/>
</properties>
</rule>
<!-- Naming is hard to control by machine. However one can be sure that variable should not be poem. -->
<rule ref="rulesets/naming.xml/LongVariable">
<properties>
<property name="maximum" value="50"/>
</properties>
</rule>
</ruleset>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment