Skip to content

Commit d8c33f5

Browse files
authored
Merge pull request #354 from wp-cli/claude/phpstan-integration-pr-340-wxxccy
Add PHPStan analysis for PHP blocks in feature files
2 parents 0f5daf3 + e94758a commit d8c33f5

8 files changed

Lines changed: 1849 additions & 4 deletions

File tree

‎.readme-partials/USING.md‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,13 @@ To make use of the WP-CLI testing framework, you need to complete the following
1313
"lint": "run-linter-tests",
1414
"phpcs": "run-phpcs-tests",
1515
"phpcbf": "run-phpcbf-cleanup",
16+
"phpstan": "run-phpstan-tests",
1617
"phpunit": "run-php-unit-tests",
1718
"prepare-tests": "install-package-tests",
1819
"test": [
1920
"@lint",
2021
"@phpcs",
22+
"@phpstan",
2123
"@phpunit",
2224
"@behat"
2325
]
@@ -76,7 +78,9 @@ To make use of the WP-CLI testing framework, you need to complete the following
7678
```
7779
7880
All other [PHPCS configuration options](https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki/Annotated-Ruleset) are, of course, available.
79-
6. Update your composer dependencies and regenerate your autoloader and binary folders:
81+
6. Optionally add a `phpstan-feature-files.neon.dist` file to the package root to also run PHPStan over the PHP snippets embedded in your feature files. See [Analysing the PHP blocks in feature files](#analysing-the-php-blocks-in-feature-files) below.
82+
83+
7. Update your composer dependencies and regenerate your autoloader and binary folders:
8084
```bash
8185
composer update
8286
```
@@ -92,9 +96,75 @@ You can use the following commands to control the tests:
9296
* `composer lint` - Run only the linting test suite.
9397
* `composer phpcs` - Run only the code sniffer test suite.
9498
* `composer phpcbf` - Run only the code sniffer cleanup.
99+
* `composer phpstan` - Run only the static analysis.
95100
* `composer phpunit` - Run only the unit test suite.
96101
* `composer behat` - Run only the functional test suite.
97102
103+
### Analysing the PHP blocks in feature files
104+
105+
Feature files embed PHP snippets in docstrings, which none of the static analysis tools normally
106+
look at:
107+
108+
```gherkin
109+
Given a wp-content/mu-plugins/test-harness.php file:
110+
"""
111+
<?php
112+
WP_CLI::add_command( 'test-harness', 'Test_Harness' );
113+
"""
114+
```
115+
116+
Adding a `phpstan-feature-files.neon.dist` file to the package root makes `composer phpstan` analyse
117+
those snippets as well. The blocks are extracted into standalone PHP files that are padded so their
118+
line numbers match the feature file, which is what allows errors to be reported against the feature
119+
file itself:
120+
121+
```text
122+
features/command.feature
123+
438 Parameter #1 $message of static method WP_CLI::log() expects string, int<0, max> given.
124+
🪪 argument.type
125+
```
126+
127+
The defaults in `phpstan/feature-files.neon` are applied first, so the file only needs to hold what
128+
it wants to change. An empty file is enough to run with the defaults, and a level of its own looks
129+
like this:
130+
131+
```neon
132+
parameters:
133+
level: 4
134+
```
135+
136+
Do note that snippets in feature files are fixtures, not production code, and that they run inside a
137+
WordPress installation the analysis knows nothing about. Expect to have to ignore errors that are
138+
not actually wrong, such as functions a scenario deliberately leaves undefined.
139+
140+
An ignore matches against the extracted file rather than the feature file it came from. Those files
141+
are named `<feature file>_L<first line>_E<last line>.php`, with the feature file relative to the
142+
`features` directory, so ignoring an error for a whole feature file takes a pattern:
143+
144+
```neon
145+
parameters:
146+
ignoreErrors:
147+
-
148+
identifier: function.notFound
149+
path: */shutdown-handler.feature_L*.php
150+
```
151+
152+
Since the blocks are analysed in more than one run (see below), an ignore that no run matches is not
153+
reported. A pattern that matches nothing at all therefore goes unnoticed, so it is worth checking
154+
that the error it targets is really gone.
155+
156+
Two kinds of blocks are left out of the analysis, and are listed at the end of the run:
157+
158+
* Blocks that are not standalone PHP, such as snippets holding a placeholder that Behat substitutes
159+
(`get_the_title( {POST_ID} )`) or code that is deliberately broken to test error handling. PHPStan
160+
stops analysing altogether when a single file fails to parse, so these have to be skipped.
161+
* Docstrings that neither belong to a step creating a `.php` file nor open with `<?php`, since those
162+
are not necessarily PHP at all. The second rule covers PHP files that are not named `*.php`, such
163+
as the `.maintenance` file of a WordPress installation.
164+
165+
Blocks that declare the same class or function as another block are analysed separately from each
166+
other, so that PHPStan does not resolve a name to the wrong block's declaration.
167+
98168
### Controlling what to test
99169

100170
To send one or more arguments to one of the test tools, prepend the argument(s) with a double dash. As an example, here's how to run the functional tests for a specific feature file only:

‎README.md‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,13 @@ To make use of the WP-CLI testing framework, you need to complete the following
2424
"lint": "run-linter-tests",
2525
"phpcs": "run-phpcs-tests",
2626
"phpcbf": "run-phpcbf-cleanup",
27+
"phpstan": "run-phpstan-tests",
2728
"phpunit": "run-php-unit-tests",
2829
"prepare-tests": "install-package-tests",
2930
"test": [
3031
"@lint",
3132
"@phpcs",
33+
"@phpstan",
3234
"@phpunit",
3335
"@behat"
3436
]
@@ -87,7 +89,9 @@ To make use of the WP-CLI testing framework, you need to complete the following
8789
```
8890
8991
All other [PHPCS configuration options](https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki/Annotated-Ruleset) are, of course, available.
90-
6. Update your composer dependencies and regenerate your autoloader and binary folders:
92+
6. Optionally add a `phpstan-feature-files.neon.dist` file to the package root to also run PHPStan over the PHP snippets embedded in your feature files. See [Analysing the PHP blocks in feature files](#analysing-the-php-blocks-in-feature-files) below.
93+
94+
7. Update your composer dependencies and regenerate your autoloader and binary folders:
9195
```bash
9296
composer update
9397
```
@@ -103,9 +107,75 @@ You can use the following commands to control the tests:
103107
* `composer lint` - Run only the linting test suite.
104108
* `composer phpcs` - Run only the code sniffer test suite.
105109
* `composer phpcbf` - Run only the code sniffer cleanup.
110+
* `composer phpstan` - Run only the static analysis.
106111
* `composer phpunit` - Run only the unit test suite.
107112
* `composer behat` - Run only the functional test suite.
108113
114+
### Analysing the PHP blocks in feature files
115+
116+
Feature files embed PHP snippets in docstrings, which none of the static analysis tools normally
117+
look at:
118+
119+
```gherkin
120+
Given a wp-content/mu-plugins/test-harness.php file:
121+
"""
122+
<?php
123+
WP_CLI::add_command( 'test-harness', 'Test_Harness' );
124+
"""
125+
```
126+
127+
Adding a `phpstan-feature-files.neon.dist` file to the package root makes `composer phpstan` analyse
128+
those snippets as well. The blocks are extracted into standalone PHP files that are padded so their
129+
line numbers match the feature file, which is what allows errors to be reported against the feature
130+
file itself:
131+
132+
```text
133+
features/command.feature
134+
438 Parameter #1 $message of static method WP_CLI::log() expects string, int<0, max> given.
135+
🪪 argument.type
136+
```
137+
138+
The defaults in `phpstan/feature-files.neon` are applied first, so the file only needs to hold what
139+
it wants to change. An empty file is enough to run with the defaults, and a level of its own looks
140+
like this:
141+
142+
```neon
143+
parameters:
144+
level: 4
145+
```
146+
147+
Do note that snippets in feature files are fixtures, not production code, and that they run inside a
148+
WordPress installation the analysis knows nothing about. Expect to have to ignore errors that are
149+
not actually wrong, such as functions a scenario deliberately leaves undefined.
150+
151+
An ignore matches against the extracted file rather than the feature file it came from. Those files
152+
are named `<feature file>_L<first line>_E<last line>.php`, with the feature file relative to the
153+
`features` directory, so ignoring an error for a whole feature file takes a pattern:
154+
155+
```neon
156+
parameters:
157+
ignoreErrors:
158+
-
159+
identifier: function.notFound
160+
path: */shutdown-handler.feature_L*.php
161+
```
162+
163+
Since the blocks are analysed in more than one run (see below), an ignore that no run matches is not
164+
reported. A pattern that matches nothing at all therefore goes unnoticed, so it is worth checking
165+
that the error it targets is really gone.
166+
167+
Two kinds of blocks are left out of the analysis, and are listed at the end of the run:
168+
169+
* Blocks that are not standalone PHP, such as snippets holding a placeholder that Behat substitutes
170+
(`get_the_title( {POST_ID} )`) or code that is deliberately broken to test error handling. PHPStan
171+
stops analysing altogether when a single file fails to parse, so these have to be skipped.
172+
* Docstrings that neither belong to a step creating a `.php` file nor open with `<?php`, since those
173+
are not necessarily PHP at all. The second rule covers PHP files that are not named `*.php`, such
174+
as the `.maintenance` file of a WordPress installation.
175+
176+
Blocks that declare the same class or function as another block are analysed separately from each
177+
other, so that PHPStan does not resolve a name to the wrong block's declaration.
178+
109179
### Controlling what to test
110180

111181
To send one or more arguments to one of the test tools, prepend the argument(s) with a double dash. As an example, here's how to run the functional tests for a specific feature file only:

‎bin/run-phpstan-tests‎

Lines changed: 91 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,96 @@
11
#!/bin/sh
22

3-
# Run the code style check only if a configuration file exists.
3+
EXIT_CODE=0
4+
5+
# 1. Run the static analysis only if a configuration file exists.
46
if [ -f "phpstan.dist.neon" ] || [ -f "phpstan.neon.dist" ] || [ -f "phpstan.neon" ]
57
then
6-
vendor/bin/phpstan --memory-limit=2048M analyse "$@"
8+
vendor/bin/phpstan --memory-limit=2048M analyse "$@" || EXIT_CODE=$?
79
fi
10+
11+
# 2. Run PHPStan over the PHP blocks in .feature files if the package opted in.
12+
# Composer installs this script as a symlink in the vendor binary directory, so
13+
# it has to be resolved before the root of this package can be derived from it.
14+
SOURCE="$0"
15+
while [ -h "$SOURCE" ]
16+
do
17+
SOURCE_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
18+
SOURCE="$(readlink "$SOURCE")"
19+
# A relative symlink is resolved against the directory holding the symlink.
20+
case "$SOURCE" in
21+
/*) ;;
22+
*) SOURCE="$SOURCE_DIR/$SOURCE" ;;
23+
esac
24+
done
25+
DIR="$(cd -P "$(dirname "$SOURCE")/.." && pwd)"
26+
FEATURE_CONFIG=""
27+
for CANDIDATE in "phpstan-feature-files.neon" "phpstan-feature-files.neon.dist"
28+
do
29+
if [ -f "$CANDIDATE" ]
30+
then
31+
FEATURE_CONFIG="$(pwd)/$CANDIDATE"
32+
break
33+
fi
34+
done
35+
36+
if [ -d "features" ] && [ -n "$FEATURE_CONFIG" ] && [ -f "$DIR/utils/phpstan-feature-files.php" ]
37+
then
38+
TEMP_DIR=$(mktemp -d 2>/dev/null || mktemp -d -t 'feature_phpstan')
39+
trap 'rm -rf "$TEMP_DIR"' EXIT HUP INT TERM
40+
41+
# Results are only reported when the extraction they are based on succeeded.
42+
if php "$DIR/utils/phpstan-feature-files.php" extract features "$TEMP_DIR/blocks"
43+
then
44+
{
45+
echo "includes:"
46+
echo " - $DIR/phpstan/feature-files.neon"
47+
echo " - $FEATURE_CONFIG"
48+
49+
# The functions in the `WP_CLI\Utils` namespace are pulled in through the
50+
# `files` autoloader, which does not make them known to PHPStan.
51+
if [ -d "vendor/wp-cli/wp-cli" ]
52+
then
53+
echo "parameters:"
54+
echo " scanDirectories:"
55+
echo " - $(pwd)/vendor/wp-cli/wp-cli"
56+
fi
57+
} > "$TEMP_DIR/phpstan-feature-files.neon"
58+
59+
# Blocks are spread over batches that do not declare the same symbol twice,
60+
# so that PHPStan does not resolve a name to another block's declaration.
61+
for BATCH in "$TEMP_DIR"/blocks/batch*
62+
do
63+
[ -d "$BATCH" ] || continue
64+
65+
NAME="$(basename "$BATCH")"
66+
67+
vendor/bin/phpstan --memory-limit=2048M analyse \
68+
--configuration="$TEMP_DIR/phpstan-feature-files.neon" \
69+
--error-format=json \
70+
--no-progress \
71+
"$BATCH" > "$TEMP_DIR/$NAME.json" 2>"$TEMP_DIR/$NAME.stderr"
72+
73+
# The findings are reported against the feature files they came from,
74+
# so PHPStan's own output is only of interest when it produced none.
75+
if [ ! -s "$TEMP_DIR/$NAME.json" ] && [ -s "$TEMP_DIR/$NAME.stderr" ]
76+
then
77+
cat "$TEMP_DIR/$NAME.stderr" >&2
78+
fi
79+
done
80+
81+
# The glob stays unexpanded when no batch produced results, which is the
82+
# case for a package whose feature files hold no PHP block at all. The
83+
# report is still worth running, as it lists the blocks that were skipped.
84+
set -- "$TEMP_DIR"/batch*.json
85+
if [ -f "$1" ]
86+
then
87+
php "$DIR/utils/phpstan-feature-files.php" report "$TEMP_DIR/blocks" "$@" || EXIT_CODE=$?
88+
else
89+
php "$DIR/utils/phpstan-feature-files.php" report "$TEMP_DIR/blocks" || EXIT_CODE=$?
90+
fi
91+
else
92+
EXIT_CODE=1
93+
fi
94+
fi
95+
96+
exit $EXIT_CODE

‎composer.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"type": "phpcodesniffer-standard",
1111
"require": {
1212
"php": ">=7.2.24",
13+
"ext-tokenizer": "*",
1314
"behat/behat": "^v3.15.0",
1415
"dealerdirect/phpcodesniffer-composer-installer": "^0.4.3 || ^0.5 || ^0.6.2 || ^0.7.1 || ^1.0.0",
1516
"johnbillion/wp-compat": "^2.0",

‎phpstan-feature-files.neon.dist‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Opts this package into the static analysis of the PHP blocks in its feature files.
2+
#
3+
# The defaults in `phpstan/feature-files.neon` are applied first. Packages using the
4+
# testing framework pick up `extension.neon` through phpstan/extension-installer, so
5+
# they do not have to include it themselves.
6+
7+
includes:
8+
- extension.neon

‎phpstan/feature-files.neon‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Defaults for the static analysis of the PHP blocks embedded in Behat feature files.
2+
#
3+
# A package opts into the analysis by adding a `phpstan-feature-files.neon` (or
4+
# `phpstan-feature-files.neon.dist`) file to its root. These defaults are always
5+
# applied first, so that file only needs to hold what it wants to change.
6+
#
7+
# The snippets in feature files are fixtures rather than production code, so the
8+
# level is kept below the one that asks for type declarations everywhere.
9+
10+
parameters:
11+
level: 5
12+
treatPhpDocTypesAsCertain: false
13+
14+
# Most packages will not run into all of the errors ignored below.
15+
reportUnmatchedIgnoredErrors: false
16+
17+
ignoreErrors:
18+
# `wp eval-file` passes the remaining positional arguments to the file it runs.
19+
-
20+
identifier: variable.undefined
21+
message: '#^Variable \$args might not be defined\.$#'
22+
23+
# Files a snippet pulls in are created by other steps while the scenario runs.
24+
- identifier: include.fileNotFound
25+
- identifier: includeOnce.fileNotFound
26+
- identifier: require.fileNotFound
27+
- identifier: requireOnce.fileNotFound

0 commit comments

Comments
 (0)