Skip to content

Commit 4f4ce95

Browse files
committed
Add PHPStan analysis for PHP blocks in feature files
Feature files embed PHP snippets in docstrings that no static analysis tool currently looks at. This extracts those snippets into standalone PHP files padded so that their line numbers match the feature file, runs PHPStan over them, and reports the findings against the feature file they came from. PHPStan needs a few things that a code style check does not: * The opening tag has to come first. Padding in front of it counts as inline HTML, which makes a `declare()` or `namespace` statement in a block a fatal error, so the tag a block brings along itself is dropped instead. * Blocks that are not standalone PHP have to be left out, since a single file that fails to parse makes PHPStan abort the whole run. Feature files hold deliberately broken snippets as well as Behat placeholders such as `{POST_ID}` that are substituted before the snippet is written to disk. * Blocks declaring the same class or function are analysed separately from each other, so that a name is not resolved to another block's declaration. The analysis is opt-in through a `phpstan-feature-files.neon[.dist]` file in the package root, layered on top of the defaults in `phpstan/feature-files.neon`. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01M4oxq4G2FxhwJfHd3w6VLw
1 parent 4b2caf3 commit 4f4ce95

8 files changed

Lines changed: 1654 additions & 4 deletions

File tree

‎.readme-partials/USING.md‎

Lines changed: 62 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,66 @@ 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+
```
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 set of parameters is enough to run with the defaults:
129+
130+
```yaml
131+
parameters:
132+
level: 5
133+
```
134+
135+
Do note that snippets in feature files are fixtures, not production code, and that they run inside a
136+
WordPress installation the analysis knows nothing about. Expect to have to ignore errors that are
137+
not actually wrong, such as functions a scenario deliberately leaves undefined:
138+
139+
```yaml
140+
parameters:
141+
level: 5
142+
ignoreErrors:
143+
-
144+
identifier: function.notFound
145+
path: features/shutdown-handler.feature
146+
```
147+
148+
Two kinds of blocks are left out of the analysis, and are listed at the end of the run:
149+
150+
* Blocks that are not standalone PHP, such as snippets holding a placeholder that Behat substitutes
151+
(`get_the_title( {POST_ID} )`) or code that is deliberately broken to test error handling. PHPStan
152+
stops analysing altogether when a single file fails to parse, so these have to be skipped.
153+
* Docstrings that do not belong to a step creating a `.php` file, since those are not necessarily
154+
PHP at all.
155+
156+
Blocks that declare the same class or function as another block are analysed separately from each
157+
other, so that PHPStan does not resolve a name to the wrong block's declaration.
158+
98159
### Controlling what to test
99160

100161
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: 62 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,66 @@ 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+
```
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 set of parameters is enough to run with the defaults:
140+
141+
```yaml
142+
parameters:
143+
level: 5
144+
```
145+
146+
Do note that snippets in feature files are fixtures, not production code, and that they run inside a
147+
WordPress installation the analysis knows nothing about. Expect to have to ignore errors that are
148+
not actually wrong, such as functions a scenario deliberately leaves undefined:
149+
150+
```yaml
151+
parameters:
152+
level: 5
153+
ignoreErrors:
154+
-
155+
identifier: function.notFound
156+
path: features/shutdown-handler.feature
157+
```
158+
159+
Two kinds of blocks are left out of the analysis, and are listed at the end of the run:
160+
161+
* Blocks that are not standalone PHP, such as snippets holding a placeholder that Behat substitutes
162+
(`get_the_title( {POST_ID} )`) or code that is deliberately broken to test error handling. PHPStan
163+
stops analysing altogether when a single file fails to parse, so these have to be skipped.
164+
* Docstrings that do not belong to a step creating a `.php` file, since those are not necessarily
165+
PHP at all.
166+
167+
Blocks that declare the same class or function as another block are analysed separately from each
168+
other, so that PHPStan does not resolve a name to the wrong block's declaration.
169+
109170
### Controlling what to test
110171

111172
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: 67 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,72 @@
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=$?
9+
fi
10+
11+
# 2. Run PHPStan over the PHP blocks in .feature files if the package opted in.
12+
DIR="$(cd "$(dirname "$0")/.." && pwd)"
13+
FEATURE_CONFIG=""
14+
for CANDIDATE in "phpstan-feature-files.neon" "phpstan-feature-files.neon.dist"
15+
do
16+
if [ -f "$CANDIDATE" ]
17+
then
18+
FEATURE_CONFIG="$(pwd)/$CANDIDATE"
19+
break
20+
fi
21+
done
22+
23+
if [ -d "features" ] && [ -n "$FEATURE_CONFIG" ] && [ -f "$DIR/utils/phpstan-feature-files.php" ]
24+
then
25+
TEMP_DIR=$(mktemp -d 2>/dev/null || mktemp -d -t 'feature_phpstan')
26+
trap 'rm -rf "$TEMP_DIR"' EXIT HUP INT TERM
27+
28+
# Results are only reported when the extraction they are based on succeeded.
29+
if php "$DIR/utils/phpstan-feature-files.php" extract features "$TEMP_DIR/blocks"
30+
then
31+
{
32+
echo "includes:"
33+
echo " - $DIR/phpstan/feature-files.neon"
34+
echo " - $FEATURE_CONFIG"
35+
36+
# The functions in the `WP_CLI\Utils` namespace are pulled in through the
37+
# `files` autoloader, which does not make them known to PHPStan.
38+
if [ -d "vendor/wp-cli/wp-cli" ]
39+
then
40+
echo "parameters:"
41+
echo " scanDirectories:"
42+
echo " - $(pwd)/vendor/wp-cli/wp-cli"
43+
fi
44+
} > "$TEMP_DIR/phpstan-feature-files.neon"
45+
46+
# Blocks are spread over batches that do not declare the same symbol twice,
47+
# so that PHPStan does not resolve a name to another block's declaration.
48+
for BATCH in "$TEMP_DIR"/blocks/batch*
49+
do
50+
[ -d "$BATCH" ] || continue
51+
52+
vendor/bin/phpstan --memory-limit=2048M analyse \
53+
--configuration="$TEMP_DIR/phpstan-feature-files.neon" \
54+
--error-format=json \
55+
--no-progress \
56+
"$BATCH" > "$TEMP_DIR/$(basename "$BATCH").json" 2>"$TEMP_DIR/$(basename "$BATCH").stderr"
57+
58+
# Anything PHPStan itself has to say goes to the terminal, while its
59+
# findings are reported against the feature files they came from.
60+
if [ -s "$TEMP_DIR/$(basename "$BATCH").stderr" ]
61+
then
62+
cat "$TEMP_DIR/$(basename "$BATCH").stderr" >&2
63+
fi
64+
done
65+
66+
php "$DIR/utils/phpstan-feature-files.php" report "$TEMP_DIR/blocks" "$TEMP_DIR"/batch*.json || EXIT_CODE=$?
67+
else
68+
EXIT_CODE=1
69+
fi
770
fi
71+
72+
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
"php-parallel-lint/php-console-highlighter": "^1.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)