dumbo/examples/index.php

84 lines
1.7 KiB
PHP
Raw Normal View History

2024-07-15 14:27:57 +01:00
<?php
require "vendor/autoload.php";
use Dumbo\Dumbo;
$app = new Dumbo();
2024-07-15 16:18:47 +01:00
$user = new Dumbo();
$userData = [
2024-07-15 19:11:45 +01:00
[
"id" => 1,
"name" => "Jamie Barton",
"email" => "jamie@notrab.dev",
],
2024-07-15 16:18:47 +01:00
];
2024-07-15 16:24:38 +01:00
$user->get("/", function ($c) use ($userData) {
return $c->json($userData);
2024-07-15 16:18:47 +01:00
});
$user->get("/:id", function ($c) use ($userData) {
2024-07-15 18:59:04 +01:00
$id = (int) $c->req->param("id");
2024-07-15 16:18:47 +01:00
2024-07-15 19:11:45 +01:00
$user =
array_values(array_filter($userData, fn($u) => $u["id"] === $id))[0] ??
null;
if (!$user) {
2024-07-15 16:18:47 +01:00
return $c->json(["error" => "User not found"], 404);
}
2024-07-15 19:11:45 +01:00
return $c->json($user);
2024-07-15 16:18:47 +01:00
});
2024-07-15 14:27:57 +01:00
2024-07-15 19:11:45 +01:00
$user->post("/", function ($c) use ($userData) {
$body = $c->req->body();
if (!isset($body["name"]) || !isset($body["email"])) {
return $c->json(["error" => "Name and email are required"], 400);
}
$newId = max(array_column($userData, "id")) + 1;
$newUserData = array_merge(["id" => $newId], $body);
return $c->json($newUserData, 201);
});
$user->delete("/:id", function ($c) {
$id = (int) $c->req->param("id");
if ($id !== $userData["id"]) {
return $c->json(["error" => "User not found"], 404);
}
return $c->json(["message" => "User deleted successfully"]);
2024-07-15 14:27:57 +01:00
});
2024-07-15 18:59:04 +01:00
$app->get("/greet/:greeting", function ($c) {
$greeting = $c->req->param("greeting");
$name = $c->req->query("name");
2024-07-15 16:18:47 +01:00
2024-07-15 14:27:57 +01:00
return $c->json([
"message" => "$greeting, $name!",
]);
});
2024-07-15 16:18:47 +01:00
$app->route("/users", $user);
2024-07-15 16:42:42 +01:00
$app->use(function ($c, $next) {
2024-07-15 18:59:04 +01:00
$c->header("X-Powered-By", "Dumbo");
2024-07-15 16:42:42 +01:00
return $next($c);
});
2024-07-15 19:11:45 +01:00
$app->get("/", function ($c) {
return $c->html("<h1>Hello from Dumbo!</h1>", 200, [
"X-Hello" => "World",
]);
});
2024-07-15 14:27:57 +01:00
$app->run();