API_Controller.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * v1 API Controller file.
  4. *
  5. * Provides a class to handle all posible API requests.
  6. *
  7. * @author Iñigo Valentin <i@inigovalentin.com>
  8. * @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License V3
  9. * @package SWDB
  10. */
  11. /**
  12. * v1 API controller.
  13. *
  14. * Handles every API request.
  15. *
  16. * @category API
  17. */
  18. class API_Controller {
  19. /**
  20. * Constructor.
  21. *
  22. * Handles every request, creating the required models and selecting the
  23. * view.
  24. *
  25. * @param string[] $query GET parameters of the request.
  26. */
  27. public function __construct($query){
  28. // Remove /API/
  29. array_shift($query);
  30. // Remove /v1/
  31. array_shift($query);
  32. // API call: Use API controller
  33. $method = $_SERVER["REQUEST_METHOD"];
  34. if (!in_array($method, ["GET", "POST", "PUT", "DELETE"])){
  35. $method = "GET";
  36. }
  37. if (count($query) == 0 || $query[0] == null || $query[0] == ""){
  38. require_once(__DIR__ . "/main.php");
  39. }
  40. else{
  41. $command = strtolower($query[0]);
  42. // Remove /<command>/
  43. array_shift($query);
  44. switch ($command){
  45. case "help":
  46. require_once(__DIR__ . "/help/index.php");
  47. break;
  48. case "profile":
  49. case "run":
  50. case "logbook":
  51. case "collection":
  52. case "run":
  53. case "units":
  54. if (file_exists(__DIR__ . "/$command/$method.php")){
  55. require_once(__DIR__ . "/$command/$method.php");
  56. }
  57. else{
  58. header("HTTP/1.1 404");
  59. }
  60. break;
  61. default:
  62. header("HTTP/1.1 404");
  63. }
  64. }
  65. }
  66. }