Router/tests/segment.php
2024-09-07 13:02:52 -05:00

80 lines
2.2 KiB
PHP

<?php
/*
This test file puts the SegmentRouter to the test by running a million lookups on a handful
of routes. The routes are read from two files, blog.txt and github.txt, and added to two separate
routers. The lookups are then run in two separate loops, one for each router.
Each lookup is timed and the memory usage is also printed out at regular intervals.
The requests are randomly picked from the array of routes.
*/
require_once __DIR__ . '/../SegmentRouter.php';
require_once 'tools.php';
// Blog router
$b = new SegmentRouter();
$blog = readAndAddRoutes('blog.txt', $b);
// Github router
$g = new SegmentRouter();
$github = readAndAddRoutes('github.txt', $g);
// Big router
$big = new SegmentRouter();
$bigRoutes = readAndAddRoutes('big.txt', $big);
echoTitle("Starting github lookups");
runIterations(100000, $b, $blog);
runIterations(1000000, $b, $blog);
echoTitle("Starting github lookups");
runIterations(10000, $g, $github);
runIterations(100000, $g, $github);
runIterations(1000000, $g, $github);
echoTitle("Starting big lookups");
runIterations(10000, $big, $bigRoutes);
runIterations(100000, $big, $bigRoutes);
runIterations(1000000, $big, $bigRoutes);
echoTitle("Testing parameters");
$routes = [
['GET', '/blog/:id', function($id) {
echo $id."\n";
}],
['GET', '/blog/:id/:slug', function($id, $slug) {
echo $id . ' - ' . $slug."\n";
}],
['GET', '/blog/:id/:slug/:page', function($id, $slug, $page) {
echo $id . ' - ' . $slug . ' - ' . $page."\n";
}],
['GET', '/blog/:id/:slug/:page/:extra', function($id, $slug, $page, $extra) {
echo $id . ' - ' . $slug . ' - ' . $page . ' - ' . $extra."\n";
}],
];
$r = new SegmentRouter();
foreach ($routes as $route) {
[$method, $path, $handler] = $route;
$r->add($method, $path, $handler);
}
for ($i = 0; $i < 10; $i++) {
[$method, $uri] = $routes[array_rand($routes)];
// Generate some random parameters
$uri = str_replace(':id', rand(1, 100), $uri);
$uri = str_replace(':slug', 'slug-' . rand(1, 100), $uri);
$uri = str_replace(':page', rand(1, 100), $uri);
$uri = str_replace(':extra', 'extra-' . rand(1, 100), $uri);
$res = $r->lookup($method, $uri);
if ($res !== 200) {
echo "Failed to handle request for $uri - $res\n";
exit(1);
}
}
exit(0);