Skip to content

Commit c3379fb

Browse files
committed
chore: analyse the PHP samples of the user guide with PHPStan
1 parent b15eadf commit c3379fb

4 files changed

Lines changed: 327 additions & 9 deletions

File tree

‎.github/workflows/test-phpstan.yml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ on:
1515
- composer.json
1616
- phpstan.dist.neon
1717
- phpstan-baseline.php
18+
- 'docs/**'
19+
- 'admin/lint-docs-samples.php'
20+
- 'admin/docs-phpstan-baseline.php'
1821
- '.github/workflows/test-phpstan.yml'
1922

2023
push:
@@ -29,6 +32,9 @@ on:
2932
- composer.json
3033
- phpstan.dist.neon
3134
- phpstan-baseline.php
35+
- 'docs/**'
36+
- 'admin/lint-docs-samples.php'
37+
- 'admin/docs-phpstan-baseline.php'
3238
- '.github/workflows/test-phpstan.yml'
3339

3440
concurrency:
@@ -89,3 +95,6 @@ jobs:
8995

9096
- name: Run static analysis
9197
run: composer phpstan:check
98+
99+
- name: Run static analysis on the user guide samples
100+
run: php admin/lint-docs-samples.php --phpstan

‎admin/docs-phpstan-baseline.php‎

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
/**
15+
* PHPStan exceptions for the PHP samples of the user guide.
16+
*
17+
* An entry is a page relative to the project root, for all of its samples, or `page:line`, for the sample
18+
* whose opening ```php fence is on that line.
19+
*
20+
* - `excludePaths`: samples that are skipped, for errors that PHPStan does not allow to be ignored.
21+
* - `ignoreErrors`: an error identifier, optionally narrowed by a `message` pattern, ignored in the samples of the
22+
* listed `paths` or, without them, in all samples.
23+
*
24+
* @return array{
25+
* excludePaths: list<string>,
26+
* ignoreErrors: list<array{identifier: string, message?: string, paths?: list<string>}>
27+
* }
28+
*/
29+
return [
30+
'excludePaths' => [
31+
'docs/cli/cli_signals.md:201',
32+
'docs/cli/cli_signals.md:413',
33+
'docs/cli/cli_signals.md:608',
34+
'docs/cli/cli_signals.md:654',
35+
'docs/cli/cli_signals.md:700',
36+
'docs/concepts/services.md:135',
37+
'docs/dbmgmt/migration.md:78',
38+
'docs/extending/core_classes.md:64',
39+
'docs/guides/api/controller.md:21',
40+
'docs/guides/first-app/static_pages.md:55',
41+
'docs/incoming/filters.md:18',
42+
'docs/incoming/filters.md:59',
43+
'docs/installation/upgrade_412.md:37',
44+
'docs/libraries/encryption.md:182',
45+
'docs/models/entities.md:659',
46+
'docs/models/model.md:73',
47+
'docs/models/model.md:562',
48+
'docs/testing/fabricator.md:9',
49+
],
50+
'ignoreErrors' => [
51+
// Samples are fragments: they leave out code, and the classes and functions that they refer to.
52+
['identifier' => 'class.notFound'],
53+
['identifier' => 'codeigniter.configArgumentInstanceof'],
54+
['identifier' => 'codeigniter.configArgumentType'],
55+
['identifier' => 'codeigniter.modelArgumentType'],
56+
['identifier' => 'codeigniter.unknownServiceMethod'],
57+
['identifier' => 'expr.resultUnused'],
58+
['identifier' => 'function.notFound'],
59+
['identifier' => 'method.unused'],
60+
['identifier' => 'variable.undefined'],
61+
62+
// A class that a sample declares, and that several samples declare differently, is resolved to one of them.
63+
[
64+
'identifier' => 'method.notFound',
65+
'message' => '#^Call to an undefined method (App\\\\|Tests\\\\|SampleCommand::|MyRules::|MyTestClass::)#',
66+
],
67+
[
68+
'identifier' => 'property.notFound',
69+
'message' => '#^Access to an undefined property (App\\\\|Config\\\\|SampleCommand::)#',
70+
],
71+
72+
// A value that PHP coerces, a function or class that the sample does not define, or the Session of CodeIgniter 3.
73+
[
74+
'identifier' => 'argument.type',
75+
'paths' => [
76+
'docs/cli/cli_commands.md:78',
77+
'docs/cli/cli_library.md:240',
78+
'docs/extending/events.md:25',
79+
'docs/extending/events.md:50',
80+
'docs/extending/events.md:89',
81+
'docs/outgoing/api_responses.md:510',
82+
'docs/outgoing/api_transformers.md:118',
83+
'docs/outgoing/api_transformers.md:415',
84+
'docs/testing/controllers.md:285',
85+
],
86+
],
87+
[
88+
'identifier' => 'method.nonObject',
89+
'paths' => [
90+
'docs/outgoing/api_transformers.md:235',
91+
'docs/outgoing/api_transformers.md:309',
92+
'docs/outgoing/api_transformers.md:684',
93+
'docs/outgoing/view_cells.md:324',
94+
'docs/outgoing/view_cells.md:347',
95+
],
96+
],
97+
[
98+
'identifier' => 'property.notFound',
99+
'paths' => ['docs/installation/upgrade_sessions.md:39'],
100+
],
101+
102+
// Samples that write the array of CodeIgniter 3 or of a configuration in the way that the page describes.
103+
[
104+
'identifier' => 'variable.implicitArray',
105+
'paths' => [
106+
'docs/general/configuration.md:245',
107+
'docs/incoming/routing.md:621',
108+
'docs/installation/upgrade_localization.md:45',
109+
],
110+
],
111+
112+
// Samples that show alternatives one after the other, or code that a sample does not complete.
113+
[
114+
'identifier' => 'catch.neverThrown',
115+
'paths' => ['docs/cli/cli_commands.md:144', 'docs/general/logging.md:125'],
116+
],
117+
[
118+
'identifier' => 'deadCode.unreachable',
119+
'paths' => [
120+
'docs/installation/upgrade_localization.md:61',
121+
'docs/outgoing/localization.md:271',
122+
'docs/outgoing/localization.md:310',
123+
'docs/outgoing/localization.md:377',
124+
'docs/outgoing/response.md:31',
125+
'docs/outgoing/view_parser.md:273',
126+
],
127+
],
128+
[
129+
'identifier' => 'if.alwaysFalse',
130+
'paths' => ['docs/cli/cli_signals.md:527'],
131+
],
132+
[
133+
'identifier' => 'outOfClass.self',
134+
'paths' => ['docs/testing/overview.md:293'],
135+
],
136+
[
137+
'identifier' => 'property.onlyWritten',
138+
'paths' => ['docs/installation/deployment.md:78'],
139+
],
140+
141+
// Samples that use a class that the samples declare differently, or a name that they do not define.
142+
[
143+
'identifier' => 'new.noConstructor',
144+
'paths' => [
145+
'docs/concepts/services.md:150',
146+
'docs/concepts/services.md:204',
147+
'docs/extending/core_classes.md:81',
148+
'docs/testing/fabricator.md:50',
149+
],
150+
],
151+
[
152+
'identifier' => 'parameterByRef.type',
153+
'paths' => ['docs/libraries/validation.md:1041'],
154+
],
155+
[
156+
'identifier' => 'return.type',
157+
'paths' => [
158+
'docs/concepts/services.md:150',
159+
'docs/concepts/services.md:204',
160+
'docs/extending/core_classes.md:81',
161+
],
162+
],
163+
[
164+
'identifier' => 'property.defaultValue',
165+
'paths' => ['docs/outgoing/view_parser.md:518', 'docs/testing/database.md:73'],
166+
],
167+
[
168+
'identifier' => 'property.nonObject',
169+
'paths' => ['docs/testing/fabricator.md:87'],
170+
],
171+
[
172+
'identifier' => 'property.protected',
173+
'paths' => ['docs/libraries/time.md:417'],
174+
],
175+
],
176+
];

‎admin/lint-docs-samples.php‎

Lines changed: 135 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,12 @@
2020
* rewritten in place. Otherwise, nothing is changed, and the script exits
2121
* with 1 when a sample needs fixing.
2222
*
23-
* Usage: php admin/lint-docs-samples.php [--fix] [--docs=<directory>]
23+
* With --phpstan, the samples are analysed by PHPStan instead, using the
24+
* configuration at the project root unless --phpstan-config is given, and
25+
* each error is reported against its page and line. The samples that are
26+
* excluded, and the errors that are ignored, are listed in admin/docs-phpstan-baseline.php.
27+
*
28+
* Usage: php admin/lint-docs-samples.php [--fix | --phpstan [--phpstan-config=<file>]] [--docs=<directory>]
2429
*/
2530

2631
/**
@@ -103,13 +108,105 @@ function find_samples(array $lines): array
103108
function remove_directory(string $directory): void
104109
{
105110
foreach (glob($directory . '/*') ?: [] as $file) {
106-
unlink($file);
111+
is_dir($file) ? remove_directory($file) : unlink($file);
107112
}
108113

109114
rmdir($directory);
110115
}
111116

112-
$options = getopt('', ['fix', 'docs::']);
117+
/**
118+
* @param list<array{page: string, start: int}> $found
119+
* @param array<int, string> $files
120+
*/
121+
function analyse_with_phpstan(string $root, string $work, array $found, array $files, ?string $config): int
122+
{
123+
foreach (['phpstan.neon', 'phpstan.neon.dist', 'phpstan.dist.neon'] as $name) {
124+
if ($config === null && is_file($root . '/' . $name)) {
125+
$config = $root . '/' . $name;
126+
}
127+
}
128+
129+
$pageSamples = [];
130+
$fenceSamples = [];
131+
132+
foreach ($found as $id => $sample) {
133+
$page = substr($sample['page'], strlen($root) + 1);
134+
135+
$pageSamples[$page][] = $files[$id];
136+
$fenceSamples[$page . ':' . $sample['start']] = $files[$id];
137+
}
138+
139+
$unmatched = [];
140+
141+
$expand = static function (array $entries) use ($pageSamples, $fenceSamples, &$unmatched): array {
142+
$resolved = [];
143+
144+
foreach ($entries as $entry) {
145+
$samples = isset($fenceSamples[$entry]) ? [$fenceSamples[$entry]] : ($pageSamples[$entry] ?? []);
146+
147+
if ($samples === []) {
148+
$unmatched[] = $entry;
149+
}
150+
151+
array_push($resolved, ...$samples);
152+
}
153+
154+
return $resolved;
155+
};
156+
157+
/** @var array{excludePaths: list<string>, ignoreErrors: list<array{identifier: string, paths?: list<string>}>} $exceptions */
158+
$exceptions = require __DIR__ . '/docs-phpstan-baseline.php';
159+
$ignoreErrors = [];
160+
161+
foreach ($exceptions['ignoreErrors'] as $ignore) {
162+
if (! isset($ignore['paths'])) {
163+
$ignoreErrors[] = $ignore;
164+
165+
continue;
166+
}
167+
168+
if (($ignore['paths'] = $expand($ignore['paths'])) !== []) {
169+
$ignoreErrors[] = $ignore;
170+
}
171+
}
172+
173+
file_put_contents($work . '/phpstan.neon', sprintf(
174+
"includes:\n - %s\n\nparameters: %s\n",
175+
$config,
176+
json_encode([
177+
'excludePaths' => ['analyse' => $expand($exceptions['excludePaths'])],
178+
'ignoreErrors' => $ignoreErrors,
179+
], JSON_UNESCAPED_SLASHES),
180+
));
181+
182+
exec(sprintf(
183+
'cd %s && %s %s analyse --configuration=%s --ansi --no-progress --memory-limit=1G %s 2>&1',
184+
escapeshellarg($root),
185+
escapeshellarg(PHP_BINARY),
186+
escapeshellarg($root . '/vendor/bin/phpstan'),
187+
escapeshellarg($work . '/phpstan.neon'),
188+
escapeshellarg($work),
189+
), $output, $status);
190+
191+
$pages = [];
192+
193+
foreach ($found as $id => $sample) {
194+
$page = substr($sample['page'], strlen($root) + 1);
195+
196+
$pages[$files[$id]] = $sample['page'];
197+
$pages[substr($files[$id], strlen($work) + 1)] = $page;
198+
}
199+
200+
echo strtr(implode("\n", $output), $pages), "\n";
201+
202+
foreach (array_unique($unmatched) as $entry) {
203+
printf("\n%s is listed in admin/docs-phpstan-baseline.php, but it matches no PHP sample.\n", $entry);
204+
}
205+
206+
return $status !== 0 ? $status : ($unmatched === [] ? 0 : 1);
207+
}
208+
209+
$options = getopt('', ['fix', 'phpstan', 'phpstan-config:', 'docs::']);
113210
$fix = isset($options['fix']);
114211
$root = dirname(__DIR__);
115212
$docs = rtrim(is_string($options['docs'] ?? null) ? $options['docs'] : $root . '/docs', '/');
@@ -125,12 +222,43 @@ function remove_directory(string $directory): void
125222
}
126223
}
127224

128-
$work = sys_get_temp_dir() . '/docs-samples-' . getmypid();
129-
mkdir($work);
225+
$phpstan = isset($options['phpstan']);
226+
$work = $phpstan ? $root . '/build/docs-samples' : sys_get_temp_dir() . '/docs-samples-' . getmypid();
227+
228+
if (is_dir($work)) {
229+
remove_directory($work);
230+
}
231+
232+
mkdir($work, 0777, true);
130233

131234
foreach ($found as $id => $sample) {
132-
$files[$id] = sprintf('%s/%05d.php', $work, $id);
133-
file_put_contents($files[$id], $sample['code']);
235+
if (! $phpstan) {
236+
$files[$id] = sprintf('%s/%05d.php', $work, $id);
237+
file_put_contents($files[$id], $sample['code']);
238+
239+
continue;
240+
}
241+
242+
// Padding after the opening tag keeps the lines of the sample on the lines of its page.
243+
$files[$id] = sprintf('%s/%s@%d.php', $work, substr($sample['page'], strlen($root) + 1), $sample['start']);
244+
$padded = preg_replace('/^<\?php\n/', '<?php' . str_repeat("\n", $sample['start'] + 1), $sample['code'], 1);
245+
246+
is_dir(dirname($files[$id])) || mkdir(dirname($files[$id]), 0777, true);
247+
file_put_contents($files[$id], $padded);
248+
}
249+
250+
if ($phpstan) {
251+
$status = analyse_with_phpstan(
252+
$root,
253+
$work,
254+
$found,
255+
$files,
256+
is_string($options['phpstan-config'] ?? null) ? $options['phpstan-config'] : null,
257+
);
258+
259+
remove_directory($work);
260+
261+
exit($status);
134262
}
135263

136264
$command = sprintf(

‎contributing/documentation.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,13 @@ $pager = service('pager');
163163
```
164164
````
165165

166-
A PHP sample that starts with `<?php` and parses is checked by `composer cs`, and `composer cs-fix` rewrites it in place.
167-
To skip a sample, such as CodeIgniter 3 code, put `<!-- lint-ignore -->` on the line above its fence.
166+
A PHP sample that starts with `<?php` and parses is checked by `composer cs`, and `composer cs-fix` rewrites
167+
it in place. To skip a sample, such as CodeIgniter 3 code, put `<!-- lint-ignore -->` on the line above its fence.
168+
169+
These are also analysed by PHPStan, with the configuration at the root of the project,
170+
when you run `php admin/lint-docs-samples.php --phpstan`. Each error is reported against its page and line.
171+
A sample that PHPStan cannot analyse, or an error that a sample cannot avoid, is listed in
172+
**admin/docs-phpstan-baseline.php**, by page or by the line of the opening fence of the sample.
168173

169174
### CLI Command
170175

0 commit comments

Comments
 (0)