jdecool/scaleway-runtimepublic Fork
⑂ 79f167d
Commits
⬇ Clone ▾
git clone https://git.rickub.com/jdecool/scaleway-runtime.git
git clone ssh://git@rickub.com/jdecool/scaleway-runtime.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

feat: add scaleway-doctor to check Platform Requirements against a Function RuntimeUnverified

Jérémy DECOOL committed 2026-11-22T12:52:57+01:00 Browse files
79f167d parent: 23b9c77
modified .php-cs-fixer.dist.php +1 -1
@@ -6,7 +6,7 @@ $finder = (new PhpCsFixer\Finder())
66 ->in([__DIR__.'/src', __DIR__.'/tests', __DIR__.'/resources'])
77 // The stub users commit stays as short as possible.
88 ->notPath('handler.php')
9- ->append([__FILE__, __DIR__.'/bin/scaleway-init', __DIR__.'/bin/scaleway-package', __DIR__.'/bin/scaleway-serve']);
9+ ->append([__FILE__, __DIR__.'/bin/scaleway-doctor', __DIR__.'/bin/scaleway-init', __DIR__.'/bin/scaleway-package', __DIR__.'/bin/scaleway-serve']);
1010
1111 return (new PhpCsFixer\Config())
1212 ->setRiskyAllowed(true)
@@ -6,7 +6,7 @@ $finder = (new PhpCsFixer\Finder())
6 ->in([__DIR__.'/src', __DIR__.'/tests', __DIR__.'/resources'])6 ->in([__DIR__.'/src', __DIR__.'/tests', __DIR__.'/resources'])
7 // The stub users commit stays as short as possible.7 // The stub users commit stays as short as possible.
8 ->notPath('handler.php')8 ->notPath('handler.php')
9- ->append([__FILE__, __DIR__.'/bin/scaleway-init', __DIR__.'/bin/scaleway-package', __DIR__.'/bin/scaleway-serve']);9+ ->append([__FILE__, __DIR__.'/bin/scaleway-doctor', __DIR__.'/bin/scaleway-init', __DIR__.'/bin/scaleway-package', __DIR__.'/bin/scaleway-serve']);
10 10
11 return (new PhpCsFixer\Config())11 return (new PhpCsFixer\Config())
12 ->setRiskyAllowed(true)12 ->setRiskyAllowed(true)
added bin/scaleway-doctor +28 -0
new file mode 100755
@@ -0,0 +1,28 @@
1+#!/usr/bin/env php
2+<?php
3+
4+declare(strict_types=1);
5+
6+use Composer\InstalledVersions;
7+use JDecool\ScalewayRuntime\Doctor;
8+use JDecool\ScalewayRuntime\FunctionRuntimeCatalogue;
9+
10+require $_composer_autoload_path ?? __DIR__.'/../vendor/autoload.php';
11+
12+$usage = 'Usage: scaleway-doctor --runtime=<function-runtime> (php84 or php85, as declared on the function)';
13+$arguments = array_slice($argv ?? [], 1);
14+if ([] !== array_intersect($arguments, ['-h', '--help'])) {
15+ echo $usage, \PHP_EOL;
16+ exit(0);
17+}
18+if (1 !== count($arguments) || 1 !== preg_match('/^--runtime=(.+)$/', $arguments[0], $match)) {
19+ fwrite(\STDERR, $usage.\PHP_EOL);
20+ exit(1);
21+}
22+
23+try {
24+ exit(new Doctor(FunctionRuntimeCatalogue::load(), \STDERR)->check((string) realpath(InstalledVersions::getRootPackage()['install_path']), $match[1]) ? 0 : 1);
25+} catch (Throwable $e) {
26+ fwrite(\STDERR, 'Check failed: '.$e->getMessage().\PHP_EOL);
27+ exit(1);
28+}
new file mode 100755
@@ -0,0 +1,28 @@
1+#!/usr/bin/env php
2+<?php
3+
4+declare(strict_types=1);
5+
6+use Composer\InstalledVersions;
7+use JDecool\ScalewayRuntime\Doctor;
8+use JDecool\ScalewayRuntime\FunctionRuntimeCatalogue;
9+
10+require $_composer_autoload_path ?? __DIR__.'/../vendor/autoload.php';
11+
12+$usage = 'Usage: scaleway-doctor --runtime=<function-runtime> (php84 or php85, as declared on the function)';
13+$arguments = array_slice($argv ?? [], 1);
14+if ([] !== array_intersect($arguments, ['-h', '--help'])) {
15+ echo $usage, \PHP_EOL;
16+ exit(0);
17+}
18+if (1 !== count($arguments) || 1 !== preg_match('/^--runtime=(.+)$/', $arguments[0], $match)) {
19+ fwrite(\STDERR, $usage.\PHP_EOL);
20+ exit(1);
21+}
22+
23+try {
24+ exit(new Doctor(FunctionRuntimeCatalogue::load(), \STDERR)->check((string) realpath(InstalledVersions::getRootPackage()['install_path']), $match[1]) ? 0 : 1);
25+} catch (Throwable $e) {
26+ fwrite(\STDERR, 'Check failed: '.$e->getMessage().\PHP_EOL);
27+ exit(1);
28+}
modified composer.json +1 -0
@@ -54,6 +54,7 @@
5454 }
5555 },
5656 "bin": [
57+ "bin/scaleway-doctor",
5758 "bin/scaleway-init",
5859 "bin/scaleway-package",
5960 "bin/scaleway-serve"
@@ -54,6 +54,7 @@
54 }54 }
55 },55 },
56 "bin": [56 "bin": [
57+ "bin/scaleway-doctor",
57 "bin/scaleway-init",58 "bin/scaleway-init",
58 "bin/scaleway-package",59 "bin/scaleway-package",
59 "bin/scaleway-serve"60 "bin/scaleway-serve"
modified phpstan.neon.dist +1 -0
@@ -8,6 +8,7 @@ parameters:
88 - src
99 - tests
1010 - resources
11+ - bin/scaleway-doctor
1112 - bin/scaleway-init
1213 - bin/scaleway-package
1314 - bin/scaleway-serve
@@ -8,6 +8,7 @@ parameters:
8 - src8 - src
9 - tests9 - tests
10 - resources10 - resources
11+ - bin/scaleway-doctor
11 - bin/scaleway-init12 - bin/scaleway-init
12 - bin/scaleway-package13 - bin/scaleway-package
13 - bin/scaleway-serve14 - bin/scaleway-serve
added src/Doctor.php +247 -0
new file mode 100644
@@ -0,0 +1,247 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime;
6+
7+use Composer\Semver\Constraint\Constraint;
8+use Composer\Semver\Constraint\ConstraintInterface;
9+use Composer\Semver\Constraint\MatchAllConstraint;
10+use Composer\Semver\VersionParser;
11+
12+/**
13+ * Checks the Platform Requirements Scaleway's "composer install --no-dev" checks against a Function Runtime of the
14+ * catalogue: an unmet one fails that install silently, and every Invocation then answers a 500.
15+ * See docs/adr/0013-check-platform-requirements-against-an-explicit-function-runtime.md.
16+ *
17+ * @phpstan-import-type FunctionRuntime from FunctionRuntimeCatalogue
18+ */
19+final readonly class Doctor
20+{
21+ // Composer's PlatformRepository::PLATFORM_PACKAGE_REGEX: any other name is a package, not a Platform Requirement.
22+ private const string PLATFORM_PACKAGE = '{^(?:php(?:-64bit|-ipv6|-zts|-debug)?|hhvm|(?:ext|lib)-[a-z0-9](?:[_.-]?[a-z0-9]+)*|composer(?:-(?:plugin|runtime)-api)?)$}iD';
23+
24+ // Scaleway installs with Composer 2, whose APIs every package of the ecosystem accepts.
25+ private const array IGNORED = ['composer', 'composer-plugin-api', 'composer-runtime-api'];
26+
27+ private const string SATISFIED = 'SATISFIED';
28+ private const string INCOMPATIBLE = 'INCOMPATIBLE';
29+ private const string UNKNOWN = 'UNKNOWN';
30+
31+ private VersionParser $parser;
32+
33+ /**
34+ * @param resource $log
35+ */
36+ public function __construct(
37+ private FunctionRuntimeCatalogue $catalogue,
38+ private mixed $log,
39+ ) {
40+ $this->parser = new VersionParser();
41+ }
42+
43+ /**
44+ * Writes the report to the log.
45+ *
46+ * @return bool false when a Platform Requirement is incompatible
47+ */
48+ public function check(string $appDir, string $functionRuntime): bool
49+ {
50+ $target = $this->catalogue->get($functionRuntime);
51+ foreach (['composer.json' => 'run "composer init"', 'composer.lock' => 'run "composer update" and commit it, Scaleway installs the dependencies from it'] as $file => $hint) {
52+ if (!is_file($appDir.'/'.$file)) {
53+ throw new \RuntimeException(\sprintf('"%s" is missing in "%s": %s.', $file, $appDir, $hint));
54+ }
55+ }
56+ $composerJson = (string) file_get_contents($appDir.'/composer.json');
57+ $composerLock = (string) file_get_contents($appDir.'/composer.lock');
58+ Packager::checkLock($composerJson, $composerLock);
59+ /** @var array<mixed> $composer checked by checkLock() */
60+ $composer = json_decode($composerJson, true);
61+ /** @var array<mixed> $lock checked by checkLock() */
62+ $lock = json_decode($composerLock, true);
63+
64+ $packages = array_values(array_filter(\is_array($lock['packages'] ?? null) ? $lock['packages'] : [], \is_array(...)));
65+ $providers = $this->providers($composer, $packages);
66+
67+ $counts = [self::SATISFIED => 0, self::UNKNOWN => 0, self::INCOMPATIBLE => 0];
68+ $rows = [];
69+ foreach ($this->requirements($lock, $packages) as [$declarer, $name, $constraint]) {
70+ $required = $this->constraint($constraint, $declarer);
71+ $outcome = $this->outcome($name, $required, $target, $providers);
72+ ++$counts[$outcome];
73+ if (self::SATISFIED === $outcome) {
74+ continue;
75+ }
76+ $rows[] = [$outcome, $name.' '.$constraint, 'required by '.$declarer, $this->targetValue($functionRuntime, $target, $name, $outcome)];
77+ if (self::INCOMPATIBLE === $outcome) {
78+ $rows[] = ['', $this->suggestion($functionRuntime, $name, $required, $providers)];
79+ }
80+ }
81+
82+ $this->report($rows);
83+ $this->write(\sprintf('%d satisfied, %d unknown, %d incompatible on %s (measured %s)', $counts[self::SATISFIED], $counts[self::UNKNOWN], $counts[self::INCOMPATIBLE], $functionRuntime, self::date($target)));
84+ $this->write('This covers declared Platform Requirements only, not whether the application runs.');
85+
86+ return 0 === $counts[self::INCOMPATIBLE];
87+ }
88+
89+ /**
90+ * What Composer checks when installing a lock without its dev packages: the root requirements it recorded under
91+ * "platform", and the requirements of every package it installs.
92+ *
93+ * @param array<mixed> $lock
94+ * @param list<array<mixed>> $packages
95+ *
96+ * @return list<array{string, string, string}> declarer, lowercase name and constraint of each Platform Requirement
97+ */
98+ private function requirements(array $lock, array $packages): array
99+ {
100+ $requirements = [];
101+ $add = static function (string $declarer, mixed $links) use (&$requirements): void {
102+ foreach (\is_array($links) ? $links : [] as $name => $constraint) {
103+ $name = strtolower((string) $name);
104+ if (\is_string($constraint) && 1 === preg_match(self::PLATFORM_PACKAGE, $name) && !\in_array($name, self::IGNORED, true)) {
105+ $requirements[] = [$declarer, $name, $constraint];
106+ }
107+ }
108+ };
109+ $add('the application', $lock['platform'] ?? null);
110+ foreach ($packages as $package) {
111+ $add(self::name($package), $package['require'] ?? null);
112+ }
113+
114+ return $requirements;
115+ }
116+
117+ /**
118+ * @param array<mixed> $composer
119+ * @param list<array<mixed>> $packages
120+ *
121+ * @return array<string, list<ConstraintInterface>> what the application and its packages provide or replace, by name
122+ */
123+ private function providers(array $composer, array $packages): array
124+ {
125+ $providers = [];
126+ foreach ([['the application', $composer], ...array_map(static fn (array $package): array => [self::name($package), $package], $packages)] as [$declarer, $package]) {
127+ foreach (['provide', 'replace'] as $section) {
128+ foreach (\is_array($package[$section] ?? null) ? $package[$section] : [] as $name => $constraint) {
129+ if (!\is_string($constraint)) {
130+ continue;
131+ }
132+ // The root package has no version of its own here: its "self.version" links match any.
133+ $providers[strtolower((string) $name)][] = 'self.version' === $constraint
134+ ? (\is_string($package['version'] ?? null) ? $this->constraint('=='.$package['version'], $declarer) : new MatchAllConstraint())
135+ : $this->constraint($constraint, $declarer);
136+ }
137+ }
138+ }
139+
140+ return $providers;
141+ }
142+
143+ /**
144+ * @param FunctionRuntime $target
145+ * @param array<string, list<ConstraintInterface>> $providers
146+ */
147+ private function outcome(string $name, ConstraintInterface $required, array $target, array $providers): string
148+ {
149+ foreach ($providers[$name] ?? [] as $provided) {
150+ if ($required->matches($provided)) {
151+ return self::SATISFIED;
152+ }
153+ }
154+ $version = match (true) {
155+ 'php' === $name => $target['php'],
156+ str_starts_with($name, 'ext-') => $target['extensions'][$name] ?? null,
157+ // lib-*, php-64bit and the like are not measured.
158+ default => false,
159+ };
160+ if (false === $version) {
161+ return self::UNKNOWN;
162+ }
163+
164+ return null !== $version && $required->matches(new Constraint('==', $this->parser->normalize($version))) ? self::SATISFIED : self::INCOMPATIBLE;
165+ }
166+
167+ /**
168+ * @param FunctionRuntime $target
169+ */
170+ private function targetValue(string $functionRuntime, array $target, string $name, string $outcome): string
171+ {
172+ if (self::UNKNOWN === $outcome) {
173+ return 'not in the Function Runtime Catalogue';
174+ }
175+ $version = 'php' === $name ? $target['php'] : ($target['extensions'][$name] ?? null);
176+
177+ return \sprintf('%s: %s (measured %s)', $functionRuntime, $version ?? 'not loaded', self::date($target));
178+ }
179+
180+ /**
181+ * @param array<string, list<ConstraintInterface>> $providers
182+ */
183+ private function suggestion(string $functionRuntime, string $name, ConstraintInterface $required, array $providers): string
184+ {
185+ $others = array_keys(array_filter(
186+ $this->catalogue->functionRuntimes,
187+ fn (array $other, string $otherName): bool => $otherName !== $functionRuntime && self::SATISFIED === $this->outcome($name, $required, $other, $providers),
188+ \ARRAY_FILTER_USE_BOTH,
189+ ));
190+ $suggestion = [] === $others
191+ ? 'No measured Function Runtime meets it: use Serverless Containers for custom extensions or versions.'
192+ : \sprintf('%s %s it: deploy on %s, or use Serverless Containers for custom extensions or versions.', implode(', ', $others), 1 === \count($others) ? 'meets' : 'meet', implode(' or ', $others));
193+
194+ // The catalogue may predate a PHP upgrade Scaleway made since.
195+ return 'php' === $name ? $suggestion.' If Scaleway has upgraded PHP since the measurement, update jdecool/scaleway-runtime or re-run its probe.' : $suggestion;
196+ }
197+
198+ private function constraint(string $constraint, string $declarer): ConstraintInterface
199+ {
200+ try {
201+ return $this->parser->parseConstraints($constraint);
202+ } catch (\UnexpectedValueException $e) {
203+ throw new \UnexpectedValueException(\sprintf('The invalid constraint "%s" is declared by %s: %s', $constraint, $declarer, $e->getMessage()), 0, $e);
204+ }
205+ }
206+
207+ /**
208+ * @param list<list<string>> $rows
209+ */
210+ private function report(array $rows): void
211+ {
212+ $widths = [];
213+ foreach ($rows as $row) {
214+ foreach (\array_slice($row, 0, -1) as $column => $cell) {
215+ $widths[$column] = max($widths[$column] ?? 0, \strlen($cell));
216+ }
217+ }
218+ foreach ($rows as $row) {
219+ $last = array_pop($row);
220+ $this->write(implode('', array_map(static fn (string $cell, int $column): string => str_pad($cell, $widths[$column] + 2), $row, array_keys($row))).$last);
221+ }
222+ if ([] !== $rows) {
223+ $this->write('');
224+ }
225+ }
226+
227+ /**
228+ * @param array<mixed> $package
229+ */
230+ private static function name(array $package): string
231+ {
232+ return trim((\is_string($package['name'] ?? null) ? $package['name'] : 'a package').' '.(\is_string($package['version'] ?? null) ? $package['version'] : ''));
233+ }
234+
235+ /**
236+ * @param FunctionRuntime $target
237+ */
238+ private static function date(array $target): string
239+ {
240+ return substr($target['measuredAt'], 0, 10);
241+ }
242+
243+ private function write(string $line): void
244+ {
245+ fwrite($this->log, $line.\PHP_EOL);
246+ }
247+}
new file mode 100644
@@ -0,0 +1,247 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime;
6+
7+use Composer\Semver\Constraint\Constraint;
8+use Composer\Semver\Constraint\ConstraintInterface;
9+use Composer\Semver\Constraint\MatchAllConstraint;
10+use Composer\Semver\VersionParser;
11+
12+/**
13+ * Checks the Platform Requirements Scaleway's "composer install --no-dev" checks against a Function Runtime of the
14+ * catalogue: an unmet one fails that install silently, and every Invocation then answers a 500.
15+ * See docs/adr/0013-check-platform-requirements-against-an-explicit-function-runtime.md.
16+ *
17+ * @phpstan-import-type FunctionRuntime from FunctionRuntimeCatalogue
18+ */
19+final readonly class Doctor
20+{
21+ // Composer's PlatformRepository::PLATFORM_PACKAGE_REGEX: any other name is a package, not a Platform Requirement.
22+ private const string PLATFORM_PACKAGE = '{^(?:php(?:-64bit|-ipv6|-zts|-debug)?|hhvm|(?:ext|lib)-[a-z0-9](?:[_.-]?[a-z0-9]+)*|composer(?:-(?:plugin|runtime)-api)?)$}iD';
23+
24+ // Scaleway installs with Composer 2, whose APIs every package of the ecosystem accepts.
25+ private const array IGNORED = ['composer', 'composer-plugin-api', 'composer-runtime-api'];
26+
27+ private const string SATISFIED = 'SATISFIED';
28+ private const string INCOMPATIBLE = 'INCOMPATIBLE';
29+ private const string UNKNOWN = 'UNKNOWN';
30+
31+ private VersionParser $parser;
32+
33+ /**
34+ * @param resource $log
35+ */
36+ public function __construct(
37+ private FunctionRuntimeCatalogue $catalogue,
38+ private mixed $log,
39+ ) {
40+ $this->parser = new VersionParser();
41+ }
42+
43+ /**
44+ * Writes the report to the log.
45+ *
46+ * @return bool false when a Platform Requirement is incompatible
47+ */
48+ public function check(string $appDir, string $functionRuntime): bool
49+ {
50+ $target = $this->catalogue->get($functionRuntime);
51+ foreach (['composer.json' => 'run "composer init"', 'composer.lock' => 'run "composer update" and commit it, Scaleway installs the dependencies from it'] as $file => $hint) {
52+ if (!is_file($appDir.'/'.$file)) {
53+ throw new \RuntimeException(\sprintf('"%s" is missing in "%s": %s.', $file, $appDir, $hint));
54+ }
55+ }
56+ $composerJson = (string) file_get_contents($appDir.'/composer.json');
57+ $composerLock = (string) file_get_contents($appDir.'/composer.lock');
58+ Packager::checkLock($composerJson, $composerLock);
59+ /** @var array<mixed> $composer checked by checkLock() */
60+ $composer = json_decode($composerJson, true);
61+ /** @var array<mixed> $lock checked by checkLock() */
62+ $lock = json_decode($composerLock, true);
63+
64+ $packages = array_values(array_filter(\is_array($lock['packages'] ?? null) ? $lock['packages'] : [], \is_array(...)));
65+ $providers = $this->providers($composer, $packages);
66+
67+ $counts = [self::SATISFIED => 0, self::UNKNOWN => 0, self::INCOMPATIBLE => 0];
68+ $rows = [];
69+ foreach ($this->requirements($lock, $packages) as [$declarer, $name, $constraint]) {
70+ $required = $this->constraint($constraint, $declarer);
71+ $outcome = $this->outcome($name, $required, $target, $providers);
72+ ++$counts[$outcome];
73+ if (self::SATISFIED === $outcome) {
74+ continue;
75+ }
76+ $rows[] = [$outcome, $name.' '.$constraint, 'required by '.$declarer, $this->targetValue($functionRuntime, $target, $name, $outcome)];
77+ if (self::INCOMPATIBLE === $outcome) {
78+ $rows[] = ['', $this->suggestion($functionRuntime, $name, $required, $providers)];
79+ }
80+ }
81+
82+ $this->report($rows);
83+ $this->write(\sprintf('%d satisfied, %d unknown, %d incompatible on %s (measured %s)', $counts[self::SATISFIED], $counts[self::UNKNOWN], $counts[self::INCOMPATIBLE], $functionRuntime, self::date($target)));
84+ $this->write('This covers declared Platform Requirements only, not whether the application runs.');
85+
86+ return 0 === $counts[self::INCOMPATIBLE];
87+ }
88+
89+ /**
90+ * What Composer checks when installing a lock without its dev packages: the root requirements it recorded under
91+ * "platform", and the requirements of every package it installs.
92+ *
93+ * @param array<mixed> $lock
94+ * @param list<array<mixed>> $packages
95+ *
96+ * @return list<array{string, string, string}> declarer, lowercase name and constraint of each Platform Requirement
97+ */
98+ private function requirements(array $lock, array $packages): array
99+ {
100+ $requirements = [];
101+ $add = static function (string $declarer, mixed $links) use (&$requirements): void {
102+ foreach (\is_array($links) ? $links : [] as $name => $constraint) {
103+ $name = strtolower((string) $name);
104+ if (\is_string($constraint) && 1 === preg_match(self::PLATFORM_PACKAGE, $name) && !\in_array($name, self::IGNORED, true)) {
105+ $requirements[] = [$declarer, $name, $constraint];
106+ }
107+ }
108+ };
109+ $add('the application', $lock['platform'] ?? null);
110+ foreach ($packages as $package) {
111+ $add(self::name($package), $package['require'] ?? null);
112+ }
113+
114+ return $requirements;
115+ }
116+
117+ /**
118+ * @param array<mixed> $composer
119+ * @param list<array<mixed>> $packages
120+ *
121+ * @return array<string, list<ConstraintInterface>> what the application and its packages provide or replace, by name
122+ */
123+ private function providers(array $composer, array $packages): array
124+ {
125+ $providers = [];
126+ foreach ([['the application', $composer], ...array_map(static fn (array $package): array => [self::name($package), $package], $packages)] as [$declarer, $package]) {
127+ foreach (['provide', 'replace'] as $section) {
128+ foreach (\is_array($package[$section] ?? null) ? $package[$section] : [] as $name => $constraint) {
129+ if (!\is_string($constraint)) {
130+ continue;
131+ }
132+ // The root package has no version of its own here: its "self.version" links match any.
133+ $providers[strtolower((string) $name)][] = 'self.version' === $constraint
134+ ? (\is_string($package['version'] ?? null) ? $this->constraint('=='.$package['version'], $declarer) : new MatchAllConstraint())
135+ : $this->constraint($constraint, $declarer);
136+ }
137+ }
138+ }
139+
140+ return $providers;
141+ }
142+
143+ /**
144+ * @param FunctionRuntime $target
145+ * @param array<string, list<ConstraintInterface>> $providers
146+ */
147+ private function outcome(string $name, ConstraintInterface $required, array $target, array $providers): string
148+ {
149+ foreach ($providers[$name] ?? [] as $provided) {
150+ if ($required->matches($provided)) {
151+ return self::SATISFIED;
152+ }
153+ }
154+ $version = match (true) {
155+ 'php' === $name => $target['php'],
156+ str_starts_with($name, 'ext-') => $target['extensions'][$name] ?? null,
157+ // lib-*, php-64bit and the like are not measured.
158+ default => false,
159+ };
160+ if (false === $version) {
161+ return self::UNKNOWN;
162+ }
163+
164+ return null !== $version && $required->matches(new Constraint('==', $this->parser->normalize($version))) ? self::SATISFIED : self::INCOMPATIBLE;
165+ }
166+
167+ /**
168+ * @param FunctionRuntime $target
169+ */
170+ private function targetValue(string $functionRuntime, array $target, string $name, string $outcome): string
171+ {
172+ if (self::UNKNOWN === $outcome) {
173+ return 'not in the Function Runtime Catalogue';
174+ }
175+ $version = 'php' === $name ? $target['php'] : ($target['extensions'][$name] ?? null);
176+
177+ return \sprintf('%s: %s (measured %s)', $functionRuntime, $version ?? 'not loaded', self::date($target));
178+ }
179+
180+ /**
181+ * @param array<string, list<ConstraintInterface>> $providers
182+ */
183+ private function suggestion(string $functionRuntime, string $name, ConstraintInterface $required, array $providers): string
184+ {
185+ $others = array_keys(array_filter(
186+ $this->catalogue->functionRuntimes,
187+ fn (array $other, string $otherName): bool => $otherName !== $functionRuntime && self::SATISFIED === $this->outcome($name, $required, $other, $providers),
188+ \ARRAY_FILTER_USE_BOTH,
189+ ));
190+ $suggestion = [] === $others
191+ ? 'No measured Function Runtime meets it: use Serverless Containers for custom extensions or versions.'
192+ : \sprintf('%s %s it: deploy on %s, or use Serverless Containers for custom extensions or versions.', implode(', ', $others), 1 === \count($others) ? 'meets' : 'meet', implode(' or ', $others));
193+
194+ // The catalogue may predate a PHP upgrade Scaleway made since.
195+ return 'php' === $name ? $suggestion.' If Scaleway has upgraded PHP since the measurement, update jdecool/scaleway-runtime or re-run its probe.' : $suggestion;
196+ }
197+
198+ private function constraint(string $constraint, string $declarer): ConstraintInterface
199+ {
200+ try {
201+ return $this->parser->parseConstraints($constraint);
202+ } catch (\UnexpectedValueException $e) {
203+ throw new \UnexpectedValueException(\sprintf('The invalid constraint "%s" is declared by %s: %s', $constraint, $declarer, $e->getMessage()), 0, $e);
204+ }
205+ }
206+
207+ /**
208+ * @param list<list<string>> $rows
209+ */
210+ private function report(array $rows): void
211+ {
212+ $widths = [];
213+ foreach ($rows as $row) {
214+ foreach (\array_slice($row, 0, -1) as $column => $cell) {
215+ $widths[$column] = max($widths[$column] ?? 0, \strlen($cell));
216+ }
217+ }
218+ foreach ($rows as $row) {
219+ $last = array_pop($row);
220+ $this->write(implode('', array_map(static fn (string $cell, int $column): string => str_pad($cell, $widths[$column] + 2), $row, array_keys($row))).$last);
221+ }
222+ if ([] !== $rows) {
223+ $this->write('');
224+ }
225+ }
226+
227+ /**
228+ * @param array<mixed> $package
229+ */
230+ private static function name(array $package): string
231+ {
232+ return trim((\is_string($package['name'] ?? null) ? $package['name'] : 'a package').' '.(\is_string($package['version'] ?? null) ? $package['version'] : ''));
233+ }
234+
235+ /**
236+ * @param FunctionRuntime $target
237+ */
238+ private static function date(array $target): string
239+ {
240+ return substr($target['measuredAt'], 0, 10);
241+ }
242+
243+ private function write(string $line): void
244+ {
245+ fwrite($this->log, $line.\PHP_EOL);
246+ }
247+}
added tests/DoctorTest.php +271 -0
new file mode 100644
@@ -0,0 +1,271 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Tests;
6+
7+use JDecool\ScalewayRuntime\Doctor;
8+use JDecool\ScalewayRuntime\FunctionRuntimeCatalogue;
9+use JDecool\ScalewayRuntime\Packager;
10+use PHPUnit\Framework\Attributes\TestWith;
11+use PHPUnit\Framework\TestCase;
12+use Symfony\Component\Filesystem\Filesystem;
13+
14+final class DoctorTest extends TestCase
15+{
16+ private const string SCOPE = 'This covers declared Platform Requirements only, not whether the application runs.';
17+
18+ private Filesystem $filesystem;
19+ private string $appDir;
20+ private FunctionRuntimeCatalogue $catalogue;
21+
22+ protected function setUp(): void
23+ {
24+ $this->filesystem = new Filesystem();
25+ $this->appDir = sys_get_temp_dir().'/scaleway-runtime-'.bin2hex(random_bytes(4));
26+ $this->catalogue = new FunctionRuntimeCatalogue([
27+ 'php84' => ['measuredAt' => '2026-11-22T11:47:13Z', 'php' => '8.4.28', 'extensions' => ['ext-ctype' => '8.4.28', 'ext-mysqlnd' => '0', 'ext-redis' => '6.3.0']],
28+ 'php85' => ['measuredAt' => '2026-11-21T09:00:00Z', 'php' => '8.5.13', 'extensions' => ['ext-ctype' => '8.5.13', 'ext-redis' => '6.3.0', 'ext-sodium' => '8.5.13']],
29+ ]);
30+ }
31+
32+ protected function tearDown(): void
33+ {
34+ $this->filesystem->remove($this->appDir);
35+ }
36+
37+ public function testSatisfiedRequirementsOnlyPrintTheSummary(): void
38+ {
39+ $this->application(['php' => '>=8.4', 'ext-ctype' => '*'], [self::package('acme/cache', ['php' => '^8.1', 'ext-Redis' => '^6.0'])]);
40+
41+ self::assertSame([true, "4 satisfied, 0 unknown, 0 incompatible on php84 (measured 2026-11-22)\n".self::SCOPE."\n"], $this->check('php84'));
42+ }
43+
44+ public function testIncompatibleRequirementsAreReportedWithTheirDeclarerAndASuggestion(): void
45+ {
46+ $this->application(['php' => '^8.5'], [
47+ self::package('acme/crypto', ['ext-sodium' => '*']),
48+ self::package('acme/queue', ['ext-redis' => '^7.0']),
49+ ]);
50+
51+ self::assertSame([false, <<<'TXT'
52+ INCOMPATIBLE php ^8.5 required by the application php84: 8.4.28 (measured 2026-11-22)
53+ php85 meets it: deploy on php85, or use Serverless Containers for custom extensions or versions. If Scaleway has upgraded PHP since the measurement, update jdecool/scaleway-runtime or re-run its probe.
54+ INCOMPATIBLE ext-sodium * required by acme/crypto v1.0.0 php84: not loaded (measured 2026-11-22)
55+ php85 meets it: deploy on php85, or use Serverless Containers for custom extensions or versions.
56+ INCOMPATIBLE ext-redis ^7.0 required by acme/queue v1.0.0 php84: 6.3.0 (measured 2026-11-22)
57+ No measured Function Runtime meets it: use Serverless Containers for custom extensions or versions.
58+
59+ 0 satisfied, 0 unknown, 3 incompatible on php84 (measured 2026-11-22)
60+ This covers declared Platform Requirements only, not whether the application runs.
61+
62+ TXT], $this->check('php84'));
63+ }
64+
65+ public function testMeasuredPhpPatchIsAuthoritative(): void
66+ {
67+ $this->application(['php' => '>=8.4.29']);
68+
69+ [$compatible, $report] = $this->check('php84');
70+
71+ self::assertFalse($compatible);
72+ self::assertStringContainsString('INCOMPATIBLE php >=8.4.29 required by the application php84: 8.4.28 (measured 2026-11-22)', $report);
73+ }
74+
75+ public function testComposersFallbackVersionOfAnExtensionIsCompared(): void
76+ {
77+ $this->application(['ext-mysqlnd' => '>=8.0']);
78+
79+ self::assertStringContainsString('php84: 0 (measured 2026-11-22)', $this->check('php84')[1]);
80+ }
81+
82+ public function testDevelopmentRequirementsAreNotChecked(): void
83+ {
84+ $this->application(['php' => '>=8.4'], [], [
85+ 'packages-dev' => [self::package('acme/profiler', ['ext-xdebug' => '*'])],
86+ 'platform-dev' => ['ext-pcov' => '*'],
87+ ]);
88+
89+ self::assertSame([true, "1 satisfied, 0 unknown, 0 incompatible on php84 (measured 2026-11-22)\n".self::SCOPE."\n"], $this->check('php84'));
90+ }
91+
92+ public function testProvidedAndReplacedExtensionsAreSatisfied(): void
93+ {
94+ $this->application(
95+ [],
96+ [
97+ self::package('acme/crypto', ['ext-sodium' => '*', 'ext-intl' => '^1.0', 'ext-gmp' => '^2.0']),
98+ self::package('acme/polyfill-sodium', [], ['provide' => ['ext-sodium' => '*']]),
99+ self::package('acme/polyfill-intl', [], ['replace' => ['ext-intl' => 'self.version']]),
100+ ],
101+ [],
102+ ['provide' => ['ext-gmp' => '2.1.0']],
103+ );
104+
105+ self::assertSame([true, "3 satisfied, 0 unknown, 0 incompatible on php84 (measured 2026-11-22)\n".self::SCOPE."\n"], $this->check('php84'));
106+ }
107+
108+ public function testProviderNotMatchingTheConstraintDoesNotSatisfyIt(): void
109+ {
110+ $this->application([], [
111+ self::package('acme/crypto', ['ext-sodium' => '^2.0']),
112+ self::package('acme/polyfill-sodium', [], ['provide' => ['ext-sodium' => '1.0.0']]),
113+ ]);
114+
115+ self::assertFalse($this->check('php84')[0]);
116+ }
117+
118+ public function testUnmeasuredPlatformPackagesAreUnknownWithoutFailing(): void
119+ {
120+ $this->application(['lib-icu' => '>=72', 'php-64bit' => '*']);
121+
122+ self::assertSame([true, <<<'TXT'
123+ UNKNOWN lib-icu >=72 required by the application not in the Function Runtime Catalogue
124+ UNKNOWN php-64bit * required by the application not in the Function Runtime Catalogue
125+
126+ 0 satisfied, 2 unknown, 0 incompatible on php84 (measured 2026-11-22)
127+ This covers declared Platform Requirements only, not whether the application runs.
128+
129+ TXT], $this->check('php84'));
130+ }
131+
132+ public function testComposerApisAndPackagesAreNotPlatformRequirements(): void
133+ {
134+ $this->application(['composer-runtime-api' => '^2.2', 'symfony/runtime' => '^8.0'], [self::package('symfony/runtime', ['composer-plugin-api' => '^1.0|^2.0', 'composer' => '^2.0', 'php' => '>=8.2'])]);
135+
136+ self::assertSame([true, "1 satisfied, 0 unknown, 0 incompatible on php84 (measured 2026-11-22)\n".self::SCOPE."\n"], $this->check('php84'));
137+ }
138+
139+ public function testUnmeasuredFunctionRuntimeIsRefused(): void
140+ {
141+ $this->application();
142+
143+ $this->expectExceptionMessage('"php83" is not a measured Function Runtime: use php84 or php85.');
144+
145+ $this->check('php83');
146+ }
147+
148+ #[TestWith(['composer.json'])]
149+ #[TestWith(['composer.lock'])]
150+ public function testMissingComposerFileIsRefused(string $file): void
151+ {
152+ $this->application();
153+ $this->filesystem->remove($this->appDir.'/'.$file);
154+
155+ $this->expectExceptionMessage(\sprintf('"%s" is missing in', $file));
156+
157+ $this->check('php84');
158+ }
159+
160+ public function testStaleLockIsRefused(): void
161+ {
162+ $this->application(['php' => '>=8.4']);
163+ $this->filesystem->dumpFile($this->appDir.'/composer.json', json_encode(['require' => ['php' => '>=8.5']], \JSON_THROW_ON_ERROR));
164+
165+ $this->expectExceptionMessage('composer.lock is not up to date with composer.json');
166+
167+ $this->check('php84');
168+ }
169+
170+ public function testInvalidConstraintIsRefused(): void
171+ {
172+ $this->application([], [self::package('acme/broken', ['php' => 'not a constraint'])]);
173+
174+ $this->expectExceptionMessage('The invalid constraint "not a constraint" is declared by acme/broken v1.0.0');
175+
176+ $this->check('php84');
177+ }
178+
179+ public function testInvalidConstraintOfTheApplicationIsRefused(): void
180+ {
181+ $this->application([], [], [], ['provide' => ['ext-gmp' => 'not a constraint']]);
182+
183+ $this->expectExceptionMessage('The invalid constraint "not a constraint" is declared by the application');
184+
185+ $this->check('php84');
186+ }
187+
188+ #[TestWith(['composer.json'])]
189+ #[TestWith(['composer.lock'])]
190+ public function testInvalidComposerFileIsRefused(string $file): void
191+ {
192+ $this->application();
193+ $this->filesystem->dumpFile($this->appDir.'/'.$file, '{');
194+
195+ $this->expectExceptionMessage($file.' must hold a JSON object.');
196+
197+ $this->check('php84');
198+ }
199+
200+ public function testCommandLine(): void
201+ {
202+ self::assertSame(0, self::runDoctor(['--help'])[0]);
203+ // This package's own lock, as the root package of the checkout: the report goes to stderr only.
204+ [$exitCode, $stderr, $stdout] = self::runDoctor(['--runtime=php84']);
205+ self::assertSame([0, ''], [$exitCode, $stdout]);
206+ self::assertStringContainsString('incompatible on php84', $stderr);
207+ [$exitCode, $stderr] = self::runDoctor([]);
208+ self::assertSame(1, $exitCode);
209+ self::assertStringStartsWith('Usage: scaleway-doctor --runtime=<function-runtime>', $stderr);
210+ self::assertSame(1, self::runDoctor(['--runtime=php83'])[0]);
211+ }
212+
213+ /**
214+ * @param array<string, string> $platform the root Platform Requirements, recorded by Composer in the lock
215+ * @param list<array<string, mixed>> $packages
216+ * @param array<string, mixed> $lock
217+ * @param array<string, mixed> $composer
218+ */
219+ private function application(array $platform = [], array $packages = [], array $lock = [], array $composer = []): void
220+ {
221+ $composer += ['require' => $platform];
222+ $this->filesystem->dumpFile($this->appDir.'/composer.json', json_encode($composer, \JSON_THROW_ON_ERROR));
223+ $this->filesystem->dumpFile($this->appDir.'/composer.lock', json_encode($lock + [
224+ 'content-hash' => Packager::contentHash($composer),
225+ 'packages' => $packages,
226+ 'packages-dev' => [],
227+ // Composer writes an empty JSON array, not an object.
228+ 'platform' => [] === $platform ? [] : $platform,
229+ 'platform-dev' => [],
230+ ], \JSON_THROW_ON_ERROR));
231+ }
232+
233+ /**
234+ * @param array<string, string> $require
235+ * @param array<string, mixed> $links
236+ *
237+ * @return array<string, mixed>
238+ */
239+ private static function package(string $name, array $require, array $links = []): array
240+ {
241+ return ['name' => $name, 'version' => 'v1.0.0', 'require' => $require] + $links;
242+ }
243+
244+ /**
245+ * @return array{bool, string}
246+ */
247+ private function check(string $functionRuntime): array
248+ {
249+ $log = fopen('php://memory', 'w+');
250+ self::assertNotFalse($log);
251+ $compatible = new Doctor($this->catalogue, $log)->check($this->appDir, $functionRuntime);
252+ rewind($log);
253+
254+ return [$compatible, (string) stream_get_contents($log)];
255+ }
256+
257+ /**
258+ * @param list<string> $arguments
259+ *
260+ * @return array{int, string, string} exit code, stderr and stdout
261+ */
262+ private static function runDoctor(array $arguments): array
263+ {
264+ $process = proc_open([\PHP_BINARY, __DIR__.'/../bin/scaleway-doctor', ...$arguments], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
265+ self::assertIsResource($process);
266+ $stdout = (string) stream_get_contents($pipes[1]);
267+ $stderr = (string) stream_get_contents($pipes[2]);
268+
269+ return [proc_close($process), $stderr, $stdout];
270+ }
271+}
new file mode 100644
@@ -0,0 +1,271 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Tests;
6+
7+use JDecool\ScalewayRuntime\Doctor;
8+use JDecool\ScalewayRuntime\FunctionRuntimeCatalogue;
9+use JDecool\ScalewayRuntime\Packager;
10+use PHPUnit\Framework\Attributes\TestWith;
11+use PHPUnit\Framework\TestCase;
12+use Symfony\Component\Filesystem\Filesystem;
13+
14+final class DoctorTest extends TestCase
15+{
16+ private const string SCOPE = 'This covers declared Platform Requirements only, not whether the application runs.';
17+
18+ private Filesystem $filesystem;
19+ private string $appDir;
20+ private FunctionRuntimeCatalogue $catalogue;
21+
22+ protected function setUp(): void
23+ {
24+ $this->filesystem = new Filesystem();
25+ $this->appDir = sys_get_temp_dir().'/scaleway-runtime-'.bin2hex(random_bytes(4));
26+ $this->catalogue = new FunctionRuntimeCatalogue([
27+ 'php84' => ['measuredAt' => '2026-11-22T11:47:13Z', 'php' => '8.4.28', 'extensions' => ['ext-ctype' => '8.4.28', 'ext-mysqlnd' => '0', 'ext-redis' => '6.3.0']],
28+ 'php85' => ['measuredAt' => '2026-11-21T09:00:00Z', 'php' => '8.5.13', 'extensions' => ['ext-ctype' => '8.5.13', 'ext-redis' => '6.3.0', 'ext-sodium' => '8.5.13']],
29+ ]);
30+ }
31+
32+ protected function tearDown(): void
33+ {
34+ $this->filesystem->remove($this->appDir);
35+ }
36+
37+ public function testSatisfiedRequirementsOnlyPrintTheSummary(): void
38+ {
39+ $this->application(['php' => '>=8.4', 'ext-ctype' => '*'], [self::package('acme/cache', ['php' => '^8.1', 'ext-Redis' => '^6.0'])]);
40+
41+ self::assertSame([true, "4 satisfied, 0 unknown, 0 incompatible on php84 (measured 2026-11-22)\n".self::SCOPE."\n"], $this->check('php84'));
42+ }
43+
44+ public function testIncompatibleRequirementsAreReportedWithTheirDeclarerAndASuggestion(): void
45+ {
46+ $this->application(['php' => '^8.5'], [
47+ self::package('acme/crypto', ['ext-sodium' => '*']),
48+ self::package('acme/queue', ['ext-redis' => '^7.0']),
49+ ]);
50+
51+ self::assertSame([false, <<<'TXT'
52+ INCOMPATIBLE php ^8.5 required by the application php84: 8.4.28 (measured 2026-11-22)
53+ php85 meets it: deploy on php85, or use Serverless Containers for custom extensions or versions. If Scaleway has upgraded PHP since the measurement, update jdecool/scaleway-runtime or re-run its probe.
54+ INCOMPATIBLE ext-sodium * required by acme/crypto v1.0.0 php84: not loaded (measured 2026-11-22)
55+ php85 meets it: deploy on php85, or use Serverless Containers for custom extensions or versions.
56+ INCOMPATIBLE ext-redis ^7.0 required by acme/queue v1.0.0 php84: 6.3.0 (measured 2026-11-22)
57+ No measured Function Runtime meets it: use Serverless Containers for custom extensions or versions.
58+
59+ 0 satisfied, 0 unknown, 3 incompatible on php84 (measured 2026-11-22)
60+ This covers declared Platform Requirements only, not whether the application runs.
61+
62+ TXT], $this->check('php84'));
63+ }
64+
65+ public function testMeasuredPhpPatchIsAuthoritative(): void
66+ {
67+ $this->application(['php' => '>=8.4.29']);
68+
69+ [$compatible, $report] = $this->check('php84');
70+
71+ self::assertFalse($compatible);
72+ self::assertStringContainsString('INCOMPATIBLE php >=8.4.29 required by the application php84: 8.4.28 (measured 2026-11-22)', $report);
73+ }
74+
75+ public function testComposersFallbackVersionOfAnExtensionIsCompared(): void
76+ {
77+ $this->application(['ext-mysqlnd' => '>=8.0']);
78+
79+ self::assertStringContainsString('php84: 0 (measured 2026-11-22)', $this->check('php84')[1]);
80+ }
81+
82+ public function testDevelopmentRequirementsAreNotChecked(): void
83+ {
84+ $this->application(['php' => '>=8.4'], [], [
85+ 'packages-dev' => [self::package('acme/profiler', ['ext-xdebug' => '*'])],
86+ 'platform-dev' => ['ext-pcov' => '*'],
87+ ]);
88+
89+ self::assertSame([true, "1 satisfied, 0 unknown, 0 incompatible on php84 (measured 2026-11-22)\n".self::SCOPE."\n"], $this->check('php84'));
90+ }
91+
92+ public function testProvidedAndReplacedExtensionsAreSatisfied(): void
93+ {
94+ $this->application(
95+ [],
96+ [
97+ self::package('acme/crypto', ['ext-sodium' => '*', 'ext-intl' => '^1.0', 'ext-gmp' => '^2.0']),
98+ self::package('acme/polyfill-sodium', [], ['provide' => ['ext-sodium' => '*']]),
99+ self::package('acme/polyfill-intl', [], ['replace' => ['ext-intl' => 'self.version']]),
100+ ],
101+ [],
102+ ['provide' => ['ext-gmp' => '2.1.0']],
103+ );
104+
105+ self::assertSame([true, "3 satisfied, 0 unknown, 0 incompatible on php84 (measured 2026-11-22)\n".self::SCOPE."\n"], $this->check('php84'));
106+ }
107+
108+ public function testProviderNotMatchingTheConstraintDoesNotSatisfyIt(): void
109+ {
110+ $this->application([], [
111+ self::package('acme/crypto', ['ext-sodium' => '^2.0']),
112+ self::package('acme/polyfill-sodium', [], ['provide' => ['ext-sodium' => '1.0.0']]),
113+ ]);
114+
115+ self::assertFalse($this->check('php84')[0]);
116+ }
117+
118+ public function testUnmeasuredPlatformPackagesAreUnknownWithoutFailing(): void
119+ {
120+ $this->application(['lib-icu' => '>=72', 'php-64bit' => '*']);
121+
122+ self::assertSame([true, <<<'TXT'
123+ UNKNOWN lib-icu >=72 required by the application not in the Function Runtime Catalogue
124+ UNKNOWN php-64bit * required by the application not in the Function Runtime Catalogue
125+
126+ 0 satisfied, 2 unknown, 0 incompatible on php84 (measured 2026-11-22)
127+ This covers declared Platform Requirements only, not whether the application runs.
128+
129+ TXT], $this->check('php84'));
130+ }
131+
132+ public function testComposerApisAndPackagesAreNotPlatformRequirements(): void
133+ {
134+ $this->application(['composer-runtime-api' => '^2.2', 'symfony/runtime' => '^8.0'], [self::package('symfony/runtime', ['composer-plugin-api' => '^1.0|^2.0', 'composer' => '^2.0', 'php' => '>=8.2'])]);
135+
136+ self::assertSame([true, "1 satisfied, 0 unknown, 0 incompatible on php84 (measured 2026-11-22)\n".self::SCOPE."\n"], $this->check('php84'));
137+ }
138+
139+ public function testUnmeasuredFunctionRuntimeIsRefused(): void
140+ {
141+ $this->application();
142+
143+ $this->expectExceptionMessage('"php83" is not a measured Function Runtime: use php84 or php85.');
144+
145+ $this->check('php83');
146+ }
147+
148+ #[TestWith(['composer.json'])]
149+ #[TestWith(['composer.lock'])]
150+ public function testMissingComposerFileIsRefused(string $file): void
151+ {
152+ $this->application();
153+ $this->filesystem->remove($this->appDir.'/'.$file);
154+
155+ $this->expectExceptionMessage(\sprintf('"%s" is missing in', $file));
156+
157+ $this->check('php84');
158+ }
159+
160+ public function testStaleLockIsRefused(): void
161+ {
162+ $this->application(['php' => '>=8.4']);
163+ $this->filesystem->dumpFile($this->appDir.'/composer.json', json_encode(['require' => ['php' => '>=8.5']], \JSON_THROW_ON_ERROR));
164+
165+ $this->expectExceptionMessage('composer.lock is not up to date with composer.json');
166+
167+ $this->check('php84');
168+ }
169+
170+ public function testInvalidConstraintIsRefused(): void
171+ {
172+ $this->application([], [self::package('acme/broken', ['php' => 'not a constraint'])]);
173+
174+ $this->expectExceptionMessage('The invalid constraint "not a constraint" is declared by acme/broken v1.0.0');
175+
176+ $this->check('php84');
177+ }
178+
179+ public function testInvalidConstraintOfTheApplicationIsRefused(): void
180+ {
181+ $this->application([], [], [], ['provide' => ['ext-gmp' => 'not a constraint']]);
182+
183+ $this->expectExceptionMessage('The invalid constraint "not a constraint" is declared by the application');
184+
185+ $this->check('php84');
186+ }
187+
188+ #[TestWith(['composer.json'])]
189+ #[TestWith(['composer.lock'])]
190+ public function testInvalidComposerFileIsRefused(string $file): void
191+ {
192+ $this->application();
193+ $this->filesystem->dumpFile($this->appDir.'/'.$file, '{');
194+
195+ $this->expectExceptionMessage($file.' must hold a JSON object.');
196+
197+ $this->check('php84');
198+ }
199+
200+ public function testCommandLine(): void
201+ {
202+ self::assertSame(0, self::runDoctor(['--help'])[0]);
203+ // This package's own lock, as the root package of the checkout: the report goes to stderr only.
204+ [$exitCode, $stderr, $stdout] = self::runDoctor(['--runtime=php84']);
205+ self::assertSame([0, ''], [$exitCode, $stdout]);
206+ self::assertStringContainsString('incompatible on php84', $stderr);
207+ [$exitCode, $stderr] = self::runDoctor([]);
208+ self::assertSame(1, $exitCode);
209+ self::assertStringStartsWith('Usage: scaleway-doctor --runtime=<function-runtime>', $stderr);
210+ self::assertSame(1, self::runDoctor(['--runtime=php83'])[0]);
211+ }
212+
213+ /**
214+ * @param array<string, string> $platform the root Platform Requirements, recorded by Composer in the lock
215+ * @param list<array<string, mixed>> $packages
216+ * @param array<string, mixed> $lock
217+ * @param array<string, mixed> $composer
218+ */
219+ private function application(array $platform = [], array $packages = [], array $lock = [], array $composer = []): void
220+ {
221+ $composer += ['require' => $platform];
222+ $this->filesystem->dumpFile($this->appDir.'/composer.json', json_encode($composer, \JSON_THROW_ON_ERROR));
223+ $this->filesystem->dumpFile($this->appDir.'/composer.lock', json_encode($lock + [
224+ 'content-hash' => Packager::contentHash($composer),
225+ 'packages' => $packages,
226+ 'packages-dev' => [],
227+ // Composer writes an empty JSON array, not an object.
228+ 'platform' => [] === $platform ? [] : $platform,
229+ 'platform-dev' => [],
230+ ], \JSON_THROW_ON_ERROR));
231+ }
232+
233+ /**
234+ * @param array<string, string> $require
235+ * @param array<string, mixed> $links
236+ *
237+ * @return array<string, mixed>
238+ */
239+ private static function package(string $name, array $require, array $links = []): array
240+ {
241+ return ['name' => $name, 'version' => 'v1.0.0', 'require' => $require] + $links;
242+ }
243+
244+ /**
245+ * @return array{bool, string}
246+ */
247+ private function check(string $functionRuntime): array
248+ {
249+ $log = fopen('php://memory', 'w+');
250+ self::assertNotFalse($log);
251+ $compatible = new Doctor($this->catalogue, $log)->check($this->appDir, $functionRuntime);
252+ rewind($log);
253+
254+ return [$compatible, (string) stream_get_contents($log)];
255+ }
256+
257+ /**
258+ * @param list<string> $arguments
259+ *
260+ * @return array{int, string, string} exit code, stderr and stdout
261+ */
262+ private static function runDoctor(array $arguments): array
263+ {
264+ $process = proc_open([\PHP_BINARY, __DIR__.'/../bin/scaleway-doctor', ...$arguments], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
265+ self::assertIsResource($process);
266+ $stdout = (string) stream_get_contents($pipes[1]);
267+ $stderr = (string) stream_get_contents($pipes[2]);
268+
269+ return [proc_close($process), $stderr, $stdout];
270+ }
271+}