110 lines
2.7 KiB
PHP
110 lines
2.7 KiB
PHP
<?php
|
|
require 'flight/Flight.php';
|
|
require 'model/model.php';
|
|
|
|
// Connexion à la base de données
|
|
R::setup('mysql:host=localhost;dbname=votre_base_de_donnees','votre_nom_utilisateur', 'votre_mot_de_passe');
|
|
R::freeze(true);
|
|
|
|
// CORS Headers
|
|
Flight::map('cors', function() {
|
|
header('Access-Control-Allow-Origin: *');
|
|
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
|
|
header('Access-Control-Allow-Headers: Content-Type, Authorization');
|
|
});
|
|
|
|
Flight::route('OPTIONS /todo(/@id)', function(){
|
|
Flight::cors();
|
|
return true;
|
|
});
|
|
|
|
// GET all todos or a single todo
|
|
Flight::route('GET /todo(/@id)', function($id = null) {
|
|
Flight::cors();
|
|
$filter = Flight::request()->query->filter ?? "all";
|
|
|
|
if ($id === null) {
|
|
switch($filter) {
|
|
case "done":
|
|
$todos = Todo::findCompleted();
|
|
break;
|
|
case "active":
|
|
$todos = Todo::findUnCompleted();
|
|
break;
|
|
default:
|
|
$todos = Todo::findAll();
|
|
}
|
|
Flight::json(["results" => $todos]);
|
|
} else {
|
|
$todo = Todo::find($id);
|
|
if ($todo) {
|
|
Flight::json($todo);
|
|
} else {
|
|
Flight::halt(404, 'Todo not found.');
|
|
}
|
|
}
|
|
});
|
|
|
|
// POST a new todo
|
|
Flight::route('POST /todo', function() {
|
|
Flight::cors();
|
|
$requestData = Flight::request()->data;
|
|
if (!isset($requestData->title)) {
|
|
Flight::halt(400, 'Title is required.');
|
|
}
|
|
|
|
$todoData = [
|
|
"title" => $requestData->title,
|
|
"done" => $requestData->done ?? false
|
|
];
|
|
|
|
$id = Todo::create($todoData);
|
|
$todoData['id'] = $id;
|
|
|
|
Flight::response()->header("Location", Flight::request()->url . $id);
|
|
Flight::json($todoData, 201);
|
|
});
|
|
|
|
// DELETE a todo
|
|
Flight::route('DELETE /todo/@id', function($id) {
|
|
Flight::cors();
|
|
$success = Todo::delete($id);
|
|
if ($success) {
|
|
Flight::halt(204);
|
|
} else {
|
|
Flight::halt(404, 'Todo not found.');
|
|
}
|
|
});
|
|
|
|
// PUT (update) a todo
|
|
Flight::route('PUT /todo/@id', function($id) {
|
|
Flight::cors();
|
|
$requestData = Flight::request()->data;
|
|
|
|
$todo = Todo::find($id);
|
|
if (!$todo) {
|
|
Flight::halt(404, 'Todo not found.');
|
|
}
|
|
|
|
$updateData = [];
|
|
if (isset($requestData->title)) {
|
|
$updateData['title'] = $requestData->title;
|
|
}
|
|
if (isset($requestData->done)) {
|
|
$updateData['done'] = $requestData->done;
|
|
}
|
|
|
|
if (empty($updateData)) {
|
|
Flight::halt(400, 'No data to update.');
|
|
}
|
|
|
|
$updatedTodo = Todo::update($id, $updateData);
|
|
if ($updatedTodo) {
|
|
Flight::json($updatedTodo);
|
|
} else {
|
|
Flight::halt(500, 'Update failed.');
|
|
}
|
|
});
|
|
|
|
Flight::start();
|
|
?>
|