diff --git a/App/Controllers/Api.php b/App/Controllers/Api.php index ae299d9..65d772e 100644 --- a/App/Controllers/Api.php +++ b/App/Controllers/Api.php @@ -1,8 +1,7 @@ model = new Post(); + $this->model = new ApiModel(); } - public function posts($args = ['id' => '1']) + public function index() + { + $index = []; + $index['data'] = [ + "get_url" => "http://lepisi.dev/api/{tablename}{/id}", + "put_url" => "http://lepisi.dev/api/{table}", + "post_url" => "http://lepisi.dev/api/{table}", + "delete_url" => "http://lepisi.dev/api/{table}" + ]; + $index['count'] = count($index['data']); + + header("Content-Type: application/json"); + echo json_encode($index, JSON_UNESCAPED_SLASHES); + } + + // public function posts($args = ['id' => '1']) + // { + // $get = []; + // + // if ($args['id'] == 3) { + // $get['data'] = $this->model->showJoin(); + // } else { + // $get['data'] = $this->model->showJoin([ + // ['pengumuman.status', '=', $args['id']] + // ]); + // } + // + // if ($get['data'] == false) { + // $get['data']['content'] = 'Tidak ada pengumuman'; + // $get['data']['valid_at'] = ''; + // $get['data']['expired_at'] = ''; + // $get['data']['status'] = 0; + // $get['data']['background'] = '#333'; + // $get['data']['foreground'] = '#888'; + // } + // + // if (array_key_exists(0, $get['data']) == false) { + // $temp_data = $get['data']; + // unset($get['data']); + // $get['data'][] = $temp_data; + // $temp_data = []; + // } + // + // header('Content-Type: application/json'); + // echo json_encode($get); + // } + + public function get($table, $id = "") { $get = []; - - if ($args['id'] == 3) { - $get['data'] = $this->model->showJoin(); - } else { - $get['data'] = $this->model->showJoin([ - ['pengumuman.status', '=', $args['id']] - ]); - } - - if ($get['data'] == false) { - $get['data']['content'] = 'Tidak ada pengumuman'; - $get['data']['valid_at'] = ''; - $get['data']['expired_at'] = ''; - $get['data']['status'] = 0; - $get['data']['background'] = '#333'; - $get['data']['foreground'] = '#888'; - } - - if (array_key_exists(0, $get['data']) == false) { - $temp_data = $get['data']; - unset($get['data']); - $get['data'][] = $temp_data; - $temp_data = []; - } + $get['data'] = $this->model->showAll( + ($id == "") ? [] : [ + ['id', '=', $id] + ], $table + ); + $get['count'] = count($get['data']); header('Content-Type: application/json'); echo json_encode($get); } + + public function put($table) + { + $put = []; + + $args = file_get_contents("php://input"); + $args = json_decode($args, true); + + $put['data'] = $this->model->update($table, $args); + $put['count'] = count($put['data']); + + header('Content-Type: application/json'); + echo json_encode($put); + } + + public function post($table) + { + $post = []; + $args = file_get_contents("php://input"); + $args = json_decode($args, true); + + $post['data'] = $this->model->entry($table, $args); + $post['data'] = $this->model->showAll([ + ['id', '=', $post['data'][0]] + ], $table); + $post['count'] = count($post['data']); + + header('Content-Type: application/json'); + echo json_encode($post); + } + + public function delete($table) + { + $delete = []; + $args = file_get_contents("php://input"); + $args = json_decode($args, true); + + $delete['data'] = $this->model->remove($table, $args['id']); + $delete['count'] = count($delete['data']); + + header('Content-Type: application/json'); + echo json_encode($delete); + } } diff --git a/App/Models/ApiModel.php b/App/Models/ApiModel.php new file mode 100644 index 0000000..08e4d31 --- /dev/null +++ b/App/Models/ApiModel.php @@ -0,0 +1,159 @@ +setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + } + return self::$conn; + } catch (PDOException $e) { + throw new \Exception($e->getMessage, 444); + } + } + + public function showAll($conditions = [], $table) + { + $sql = "SELECT * FROM {$table}"; + + if ($conditions) { + $sql .= " WHERE"; + foreach ($conditions as $condition) { + + $keys[] = $condition[0]; + $operators[] = $condition[1]; + $values[] = $condition[2]; + } + + $x = 0; + foreach ($keys as $key) { + $sql .= " $key $operators[$x] ?"; + $x++; + if ($x < count($keys)) { + $sql .= " AND"; + } + } + } + + try { + $con = static::connectDB(); + $query = $con->prepare($sql); + + if (count($conditions)) { + $x = 1; + foreach ($values as $value) { + $query->bindValue($x, $value); + $x++; + } + } + + $query->execute(); + return $query->fetchAll(\PDO::FETCH_ASSOC); + } catch (PDOException $e) { + echo "Error: $e->getMessage()"; + } + } + + public function update($table, $args) + { + $sql = "UPDATE {$table} SET"; + + $id = $args['id']; + unset($args['id']); + + $keys = array_keys($args); + $fields = []; + foreach ($keys as $key) { + $fields[] = $key . " = ?"; + } + if (count($fields) > 1) { + $fields = implode(', ', $fields); + } else { + $fields = implode('', $fields); + } + + try { + $con = static::connectDB(); + $sql .= " {$fields} WHERE id = ?"; + + $query = $con->prepare($sql); + $x = 1; + foreach ($args as $value) { + $query->bindValue($x, $value); + $x++; + } + $query->bindValue($x, $id); + + $query->execute(); + + return $this->showAll([ + ['id', '=', $id] + ], $table); + } catch (PDOException $e) { + echo "Error: $e->getMessage()"; + } + } + + public function entry($table, $args) + { + $sql = "INSERT INTO {$table}"; + + $fields = array_keys($args); + $fields = implode(", ", $fields); + + $values = ""; + for ($i=1; $i <= count($args); $i++) { + $values .= "?"; + if ($i < count($args)) $values .= ", "; + } + + $sql .= " ({$fields}) VALUES ({$values})"; + + try { + $con = static::connectDB(); + + $query = $con->prepare($sql); + $x = 1; + foreach ($args as $value) { + $query->bindValue($x, $value); + $x++; + } + + $query->execute(); + + $last_entry = "SELECT LAST_INSERT_ID()"; + $last_entry = $con->prepare($last_entry); + $last_entry->execute(); + + return $last_entry->fetch(); + } catch (PDOException $e) { + echo "Error: $e->getMessage()"; + } + } + + public function remove($table, $id) + { + $sql = "UPDATE {$table} SET `status` = 0 WHERE `id` = ?"; + try { + $con = static::connectDB(); + + $query = $con->prepare($sql); + $query->bindValue(1, $id); + $query->execute(); + + return true; + } catch (PDOException $e) { + echo "Error: $e->getMessage()"; + } + } +} diff --git a/Core/Router.php b/Core/Router.php index 74f5f79..845c1ba 100644 --- a/Core/Router.php +++ b/Core/Router.php @@ -3,7 +3,7 @@ namespace Core; class Router { - private + protected $routes = [], $params = []; @@ -32,6 +32,7 @@ class Router { $url = htmlspecialchars($url); $url = substr_replace($url, '', 0, 1); + $url = rtrim($url, '/'); foreach ($this->routes as $route => $params) { if (preg_match($route, $url, $matches)) { @@ -106,17 +107,17 @@ class Router return $url = $parts[0]; } - private function convertToStudlyCaps($string) + protected function convertToStudlyCaps($string) { return str_replace(' ', '', ucwords(str_replace('-', ' ', $string))); } - private function getNamespace($controller) + protected function getNamespace($controller) { return $namespace = 'App\Controllers\\' . $controller; } - private function convertToCamelCaps($string) + protected function convertToCamelCaps($string) { return lcfirst($this->convertToStudlyCaps($string)); } diff --git a/Core/RouterApi.php b/Core/RouterApi.php new file mode 100644 index 0000000..9566f70 --- /dev/null +++ b/Core/RouterApi.php @@ -0,0 +1,24 @@ +params['action'])) { + $action = $this->params['action']; + return $object->$action(); + } else { + $method = $_SERVER['REQUEST_METHOD']; + $model = $this->params['model']; + + return (isset($this->params['id'])) ? + $object->$method($model, $this->params['id']) + : + $object->$method($model); + } + } +} diff --git a/lepisi.sql b/lepisi.sql index 5784ee0..26aacb0 100644 --- a/lepisi.sql +++ b/lepisi.sql @@ -38,10 +38,11 @@ CREATE TABLE `pengumuman` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `pengumuman` (`id`, `category`, `created_at`, `valid_at`, `expired_at`, `creator`, `edited_at`, `editor`, `content`, `status`, `delay`) VALUES -(1, 2, '2017-09-20 00:00:00', '2017-09-26 00:00:00', '2017-09-29 00:00:00', 1, '2017-10-06 00:00:00', 1, 'Pengambilan & pengisian KRS tanggal **21 - 26 Agustus 2017**.', 1, 5460), -(2, 1, '2017-08-15 00:00:00', '2017-09-16 00:00:00', '2017-09-20 00:00:00', 1, '2017-10-06 00:00:00', 1, '**Almamater gelombang 3** sudah dapat diambil di ruang **Student Admission Officer (Marketing)**.', 1, 8148), -(3, 1, '2017-09-10 00:00:00', '2017-09-11 00:00:00', '2017-09-30 00:00:00', 1, '2017-10-05 00:00:00', 1, 'Perkuliahan semester ganjil dimulai pada tanggal **11 September 2017**', 1, 5880), -(4, 3, '0000-00-00 00:00:00', '2017-09-30 00:00:00', '2017-09-30 00:00:00', 1, '2017-10-06 00:00:00', 1, 'Kelas **TI-123** pindah ke ruangan **321** untuk hari ini *30 Sep 2017*', 1, 5964) +(1, 2, '2017-09-20 00:00:00', '2017-09-26 00:00:00', '2017-09-29 00:00:00', 1, '2017-10-06 00:00:00', 1, 'Pengambilan & pengisian KRS tanggal **21 - 26 Agustus 2017**.', 5, 5460), +(2, 1, '2017-08-15 00:00:00', '2017-09-16 00:00:00', '2017-09-20 00:00:00', 1, '2017-10-06 00:00:00', 1, '**Almamater gelombang 3** sudah dapat diambil di ruang **Student Admission Officer (Marketing)**.', 0, 8148), +(3, 1, '2017-09-10 00:00:00', '2017-09-11 00:00:00', '2017-09-30 00:00:00', 1, '2017-10-05 00:00:00', 1, 'Perkuliahan semester ganjil dimulai pada tanggal **11 September 2017**', 0, 5880), +(4, 3, '0000-00-00 00:00:00', '2017-09-30 00:00:00', '2017-09-30 00:00:00', 1, '2017-10-06 00:00:00', 1, 'Kelas **TI-123** pindah ke ruangan **321** untuk hari ini *30 Sep 2017*', 0, 5964), +(5, 3, '0000-00-00 00:00:00', '2017-10-06 00:00:00', '2017-10-07 00:00:00', 1, NULL, NULL, 'Kelas **TI-345** pindah ke ruangan **543** di *Lantai 1 Gedung 1*', 1, 5460) ON DUPLICATE KEY UPDATE `id` = VALUES(`id`), `category` = VALUES(`category`), `created_at` = VALUES(`created_at`), `valid_at` = VALUES(`valid_at`), `expired_at` = VALUES(`expired_at`), `creator` = VALUES(`creator`), `edited_at` = VALUES(`edited_at`), `editor` = VALUES(`editor`), `content` = VALUES(`content`), `status` = VALUES(`status`), `delay` = VALUES(`delay`); DROP TABLE IF EXISTS `users`; @@ -54,12 +55,15 @@ CREATE TABLE `users` ( `registered_at` timestamp NOT NULL DEFAULT current_timestamp(), `privilege` tinyint(1) NOT NULL DEFAULT 0, `max_user` int(1) NOT NULL DEFAULT 5, + `status` int(1) NOT NULL DEFAULT 1, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -INSERT INTO `users` (`id`, `username`, `password`, `salt`, `full_name`, `registered_at`, `privilege`, `max_user`) VALUES -(1, 'root', '14Ll9fZ15hncw', '146012323259b6163952e48', 'Administrator', '2017-09-09 00:00:00', 1, 0), -(2, 'user', '18jL3uoFwSAx.', '18211527759b374b270bd3', 'User', '2017-09-09 00:00:00', 0, 5) -ON DUPLICATE KEY UPDATE `id` = VALUES(`id`), `username` = VALUES(`username`), `password` = VALUES(`password`), `salt` = VALUES(`salt`), `full_name` = VALUES(`full_name`), `registered_at` = VALUES(`registered_at`), `privilege` = VALUES(`privilege`), `max_user` = VALUES(`max_user`); +INSERT INTO `users` (`id`, `username`, `password`, `salt`, `full_name`, `registered_at`, `privilege`, `max_user`, `status`) VALUES +(1, 'root', '14Ll9fZ15hncw', '146012323259b6163952e48', 'Administrator', '2017-09-09 00:00:00', 1, 0, 1), +(2, 'user', '18jL3uoFwSAx.', '18211527759b374b270bd3', 'User', '2017-09-09 00:00:00', 0, 5, 1), +(3, 'newuser', '17/2pUCpKXr.s', '178345152259dad9f3f19f1', 'New User', '2017-10-09 02:14:30', 0, 5, 1), +(4, 'newuser', 'abcdefg', '123', 'New User', '2017-10-09 03:58:10', 0, 5, 1) +ON DUPLICATE KEY UPDATE `id` = VALUES(`id`), `username` = VALUES(`username`), `password` = VALUES(`password`), `salt` = VALUES(`salt`), `full_name` = VALUES(`full_name`), `registered_at` = VALUES(`registered_at`), `privilege` = VALUES(`privilege`), `max_user` = VALUES(`max_user`), `status` = VALUES(`status`); --- 2017-10-06 04:25:21 +-- 2017-10-09 04:01:03 diff --git a/public/index.php b/public/index.php index 65c294f..35097a4 100644 --- a/public/index.php +++ b/public/index.php @@ -24,6 +24,7 @@ if (Core\Session::exists('info')) { } $router = new Core\Router(); +$routerapi = new Core\RouterApi(); $router->add('', ['controller' => 'posts', 'action' => 'index']); $router->add('{controller}/{action}'); @@ -31,5 +32,10 @@ $router->add('{controller}/{action}/{id:\d+}'); $router->add('{action}', ['controller' => 'home']); $router->add('{?status:\d+}', ['controller' => 'posts', 'action' => 'index']); +$routerapi->add('api', ['action' => 'index']); +$routerapi->add('api/{model}'); +$routerapi->add('api/{model}/{id:\d+}'); + $url = $_SERVER['REQUEST_URI']; -$router->dispatch($url); +if ($routerapi->match($url)) { $routerapi->dispatchApi($url); } +else { $router->dispatch($url); }