rob-revisited/ide/tests/real/api-platform-real.php

152 lines
9.8 KiB
PHP

<?php
/**
* A real check of the API Platform window on a Symfony project (a COPY of one, with api-platform/core installed and a SQLite
* database): a resource made through the backend commands (entity, #[ApiResource], groups, filters, a state processor),
* `debug:router` listing its routes, the HTTP Client requests generated and then run, against `php -S`.
* Run through games/ide/tools/api-platform-check.sh (it runs this in the web image, which has PHP and the project's extensions).
*/
require '/workspace/ide/vendor/autoload.php';
use JumPHP\Ide\ApiPlatform\ApiCommands;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\Doctrine\DoctrineCommands;
use JumPHP\Ide\HttpClient\HttpClientCommands;
use JumPHP\Ide\HttpClient\Transport;
$root = rtrim($argv[1] ?? '/project', '/');
$fail = 0;
// a clean start on a copy used before
foreach (['src/Entity', 'src/Repository', 'src/State'] as $d) {
foreach (glob("$root/$d/*.php") ?: [] as $f) {
unlink($f);
}
}
exec('rm -rf ' . escapeshellarg("$root/http-requests") . ' ' . escapeshellarg("$root/var/cache"));
$check = function (bool $ok, string $what) use (&$fail): void {
echo ($ok ? ' ok ' : ' FAIL ') . $what . "\n";
$fail += $ok ? 0 : 1;
};
$console = function (array $argv, int $timeout = 120) use ($root): array {
$p = proc_open(['php', "$root/bin/console", ...$argv, '--no-interaction'], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, $root, ['APP_ENV' => 'dev'] + getenv());
$out = stream_get_contents($pipes[1]) . stream_get_contents($pipes[2]);
return ['code' => proc_close($p), 'output' => $out];
};
$consoleCmd = fn (array $p) => Deferred::resolved($console($p['argv']));
$handlers = [];
$reg = function (string $name, callable $h) use (&$handlers): void {
$handlers[$name] = $h;
};
DoctrineCommands::register($reg, $root, $consoleCmd);
ApiCommands::register($reg, $root, $consoleCmd);
$sender = new Transport();
HttpClientCommands::register($reg, $root, $sender);
$wait = function (mixed $d) use ($sender): mixed {
if (!$d instanceof Deferred) {
return $d;
}
$v = null;
$e = null;
$done = false;
$d->then(function ($x) use (&$v, &$done) { $v = $x; $done = true; }, function ($x) use (&$e, &$done) { $e = $x; $done = true; });
for ($end = microtime(true) + 20; !$done && microtime(true) < $end;) {
$sender->poll();
usleep(2000);
}
if ($e) {
throw $e;
}
return $v;
};
$apply = function (array $changes) use (&$handlers): array {
return $handlers['apiplatform.apply'](['changes' => $changes]);
};
echo "1. entities with an API resource, made by the Doctrine window's backend\n";
foreach ([['Category', [['name' => 'name', 'type' => 'string', 'length' => 120]]],
['Product', [['name' => 'name', 'type' => 'string', 'length' => 255], ['name' => 'price', 'type' => 'decimal', 'precision' => 10, 'scale' => 2], ['name' => 'inStock', 'type' => 'boolean']]]] as [$name, $fields]) {
$r = $handlers['doctrine.entity.new'](['entity' => ['name' => $name, 'api' => $name === 'Product', 'fields' => $fields]]);
$apply($r['changes']);
}
$r = $handlers['doctrine.relation.add'](['class' => 'App\\Entity\\Product', 'relation' => ['kind' => 'ManyToOne', 'property' => 'category', 'target' => 'App\\Entity\\Category', 'inverse' => 'products']]);
$apply($r['changes']);
$classes = array_column($handlers['apiplatform.classes']([])['classes'], null, 'name');
$check(($classes['Product']['api'] ?? false) === true && ($classes['Category']['api'] ?? true) === false, 'Product has #[ApiResource], Category has not');
echo "2. the resource edited from the window's backend: operations, groups, security, filters, a processor\n";
$r = $handlers['apiplatform.resource.update'](['class' => 'App\\Entity\\Category', 'spec' => ['index' => null, 'args' => ['normalizationGroups' => ['category:read'], 'denormalizationGroups' => ['category:write']],
'operations' => [['type' => 'GetCollection'], ['type' => 'Get'], ['type' => 'Post'], ['type' => 'Delete']]]]);
$apply($r['changes']);
$r = $handlers['apiplatform.properties.update'](['class' => 'App\\Entity\\Category', 'properties' => ['name' => ['groups' => ['category:read', 'category:write'], 'filters' => [['filter' => 'search', 'strategy' => 'partial']]]]]);
$apply($r['changes']);
$product = $handlers['apiplatform.class'](['class' => 'App\\Entity\\Product']);
$props = [];
foreach ($product['properties'] as $p) {
$props[$p['name']] = ['groups' => $p['name'] !== 'id' ? ['product:read', 'product:write'] : ['product:read']];
}
$props['name']['filters'] = [['filter' => 'search', 'strategy' => 'partial'], ['filter' => 'order']];
$props['price']['filters'] = [['filter' => 'range']];
$props['inStock']['filters'] = [['filter' => 'boolean']];
$props['inStock']['apiProperty'] = ['description' => 'Is it available?', 'example' => true];
unset($props['id']);
$r = $handlers['apiplatform.properties.update'](['class' => 'App\\Entity\\Product', 'properties' => $props, 'resource' => ['index' => 0, 'args' => ['normalizationGroups' => ['product:read'], 'denormalizationGroups' => ['product:write'], 'paginationItemsPerPage' => 5]]]);
$apply($r['changes']);
$r = $handlers['apiplatform.state.new'](['kind' => 'processor', 'name' => 'ProductProcessor', 'resource' => 'App\\Entity\\Product', 'decorate' => true, 'wire' => ['resource' => 0]]);
$apply($r['changes']);
echo shell_exec('sed -n 1,80p ' . escapeshellarg("$root/src/Entity/Product.php")) . "\n";
$lint = $console(['lint:container']);
$check($lint['code'] === 0, 'lint:container passes with the processor wired (' . trim(substr($lint['output'], 0, 200)) . ')');
echo "3. debug:router shows the routes\n";
$routes = $wait($handlers['apiplatform.routes']([]));
$paths = array_map(fn ($r) => preg_replace('/\|HEAD$/', '', $r['method']) . ' ' . preg_replace('/\.\{_format\}$/', '', $r['path']), $routes['routes']);
echo ' ' . implode("\n ", $paths) . "\n";
$check($routes['ok'] && in_array('GET /api/products', $paths, true) && in_array('POST /api/products', $paths, true) && in_array('GET /api/categories', $paths, true), 'the routes of both resources are in debug:router');
$overview = array_map(fn ($r) => $r['method'] . ' ' . $r['path'], $handlers['apiplatform.overview']([])['routes']);
$check(array_diff($overview, $paths) === [], 'the overview made from the code matches debug:router' . (array_diff($overview, $paths) ? ' (not in the router: ' . implode(', ', array_diff($overview, $paths)) . ')' : ''));
echo "4. database, server, requests\n";
@unlink("$root/var/data.db");
$schema = $console(['doctrine:schema:create']);
$check($schema['code'] === 0, 'doctrine:schema:create ' . trim(substr($schema['output'], -120)));
$port = 8099;
$server = proc_open(['php', '-S', "127.0.0.1:$port", '-t', "$root/public"], [['pipe', 'r'], ['file', '/dev/null', 'w'], ['file', '/dev/null', 'w']], $pipes, $root, ['APP_ENV' => 'dev', 'PHP_CLI_SERVER_WORKERS' => '4'] + getenv());
for ($i = 0; $i < 100 && !@fsockopen('127.0.0.1', $port); $i++) {
usleep(100000);
}
$plan = $handlers['apiplatform.requests.plan'](['classes' => ['App\\Entity\\Product', 'App\\Entity\\Category']]);
$written = $handlers['apiplatform.requests.apply'](['classes' => ['App\\Entity\\Product', 'App\\Entity\\Category']]);
echo ' ' . count($written['written']) . ' files: ' . implode(', ', $written['written']) . "\n";
file_put_contents("$root/http-requests/Product/http-client.env.json", json_encode(['local' => ['baseUrl' => "http://127.0.0.1:$port", 'productId' => '1', 'categoryId' => '1']]));
file_put_contents("$root/http-requests/Category/http-client.env.json", json_encode(['local' => ['baseUrl' => "http://127.0.0.1:$port", 'categoryId' => '1']]));
$run = function (string $collection, string $file) use ($handlers, $wait): array {
$req = $handlers['http.request.read'](['collection' => $collection, 'path' => $file])['request'];
$res = $wait($handlers['http.send'](['collection' => $collection, 'env' => 'local', 'request' => $req, 'overrides' => []]));
return $res;
};
// the order matters: create a category, then a product that links to it
foreach ([['Category', 'create.http', 201], ['Category', 'list.http', 200], ['Category', 'get.http', 200], ['Product', 'create.http', 201], ['Product', 'list.http', 200], ['Product', 'get.http', 200],
['Product', 'replace.http', 200], ['Product', 'update.http', 200], ['Product', 'delete.http', 204], ['Category', 'delete.http', 204]] as [$collection, $file, $status]) {
if (!is_file("$root/http-requests/$collection/$file")) {
echo " (no $collection/$file)\n";
continue;
}
try {
$res = $run($collection, $file);
$got = $res['response']['status'] ?? 0;
$tests = $res['tests'] ?? [];
$check($got === $status, "$collection/$file {$res['response']['url']} answered $got (wanted $status)" . ($got !== $status ? ' ' . json_encode($res['response']['redirects'] ?? []) . ' ' . (json_decode((string)($res['response']['body'] ?? ''), true)['detail'] ?? substr((string)($res['response']['body'] ?? ''), 0, 80)) : ''));
} catch (\Throwable $e) {
$check(false, "$collection/$file: " . $e->getMessage());
}
}
// the filters really filter
$sender->poll();
foreach (['/api/products?name=zzz-none', '/api/products?order[name]=desc', '/api/products?price[gte]=1', '/api/products?inStock=true'] as $path) {
$res = $wait($handlers['http.send'](['collection' => '', 'env' => '', 'request' => ['method' => 'GET', 'url' => "http://127.0.0.1:$port$path", 'headers' => [['Accept', 'application/ld+json']], 'body' => '', 'auth' => ['type' => 'none'],
'options' => ['redirects' => true, 'verify' => true, 'timeout' => 10.0], 'vars' => [], 'pre' => '', 'post' => '', 'name' => 'f', 'description' => '', 'seq' => 0], 'overrides' => []]));
$check(($res['response']['status'] ?? 0) === 200, "filter $path answers " . ($res['response']['status'] ?? '?'));
}
proc_terminate($server);
echo $fail === 0 ? "ALL GOOD\n" : "$fail FAILED\n";
exit($fail === 0 ? 0 : 1);