From 0a3a8ca0ba903aa12face3c4b7273d4da288172a Mon Sep 17 00:00:00 2001 From: "David T. Sadler" Date: Wed, 7 Jul 2021 14:46:40 +0100 Subject: Refactor existing API and implement reading or urls --- includes/functions.php | 14 ++++++++++++ public/bookmarks/add/index.php | 31 +++++++++++++++++++++++++++ public/bookmarks/index.php | 47 ----------------------------------------- public/bookmarks/read/index.php | 28 ++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 47 deletions(-) create mode 100644 includes/functions.php create mode 100644 public/bookmarks/add/index.php delete mode 100644 public/bookmarks/index.php create mode 100644 public/bookmarks/read/index.php diff --git a/includes/functions.php b/includes/functions.php new file mode 100644 index 0000000..b5208e6 --- /dev/null +++ b/includes/functions.php @@ -0,0 +1,14 @@ + $config['max_url_length']) { + respondAndExit(400, 'Bad Request'); +} + +if (!file_put_contents($config['path_to_file'], "$url\n", FILE_APPEND)) { + respondAndExit(500, 'Internal Server Error'); +} + +respondAndExit(201, 'Created'); + diff --git a/public/bookmarks/index.php b/public/bookmarks/index.php deleted file mode 100644 index 8ecfe24..0000000 --- a/public/bookmarks/index.php +++ /dev/null @@ -1,47 +0,0 @@ - 'Method Not Allowed']); -} - -if ('Bearer '.$config['bearer_token'] !== ($_SERVER['HTTP_AUTHORIZATION'] ?? null)) { - respondAndExit([ - 401 => 'Unauthorized', - 0 => 'WWW-Authenticate: Bearer realm="Bookmarks"', - ]); -} - -if ('application/x-www-form-urlencoded' !== ($_SERVER['CONTENT_TYPE'] ?? null)) { - respondAndExit([415 => 'Unsupported Media Type']); -} - -$url = filter_input(INPUT_POST, 'url', FILTER_VALIDATE_URL); - -if (!$url || !strlen($url) === 0 || strlen($url) > $config['max_url_length']) { - respondAndExit([400 => 'Bad Request']); -} - -if (!file_put_contents($config['path_to_file'], "$url\n", FILE_APPEND)) { - respondAndExit([500 => 'Internal Server Error']); -} - -respondAndExit([201 => 'Created']); - -function respondAndExit(array $headers): void -{ - foreach ($headers as $responseCode => $header) { - if ($responseCode) { - header($header, false, $responseCode); - } else { - header($header); - } - } - - header('Content-type: text/plain; charset=UTF-8'); - - exit(); -} diff --git a/public/bookmarks/read/index.php b/public/bookmarks/read/index.php new file mode 100644 index 0000000..a21dfac --- /dev/null +++ b/public/bookmarks/read/index.php @@ -0,0 +1,28 @@ + $config['max_url_length']) { + respondAndExit(400, 'Bad Request'); +} + +$urls = file($config['path_to_file'], FILE_IGNORE_NEW_LINES); + +foreach ($urls as $url) { + if ($requestedUrl == $url) { + respondAndExit(308, 'Permanent Redirect', ["Location: $url"]); + } +} + +respondAndExit(404, 'Not Found'); + -- cgit v1.2.3-13-gbd6f