lepisi-pengumuman/App/Controllers/Api.php

137 lines
4.0 KiB
PHP

<?php
namespace App\Controllers;
class Api
{
public function index()
{
$index = [];
$index['data'] = [
"get_url" => "/api/{tablename}{/id}",
"put_url" => "/api/{table}",
"post_url" => "/api/{table}",
"delete_url" => "/api/{table}"
];
$index['count'] = count($index['data']);
header("Content-Type: application/json");
echo json_encode($index, JSON_UNESCAPED_SLASHES);
}
public function get($table, $id = "", $args = [])
{
$get = [];
$model = 'App\Models\ApiModel';
if ($table == 'pengumuman') {
$model = 'App\Models\Pengumuman';
}
if ($args == []) {
$get['data'] = $id == "" ? $model::showAll($table) : $model::fetch(
$table,
[
[$table.'.id', '=', $id]
]);
} else {
if ($args['status'] != 3) {
$get['data'] = $model::showAll($table, [
["$table.status", '=', $args['status']]
]);
} else {
$get['data'] = $model::showAll($table);
}
}
$get['count'] = count($get['data']);
if ($table == 'kategori' && $get['count'] != 0) {
if (isset($get['data'][0])) {
for ($i=0; $i < count($get['data']); $i++) {
$get['data'][$i]['posts'] = count(\App\Models\Pengumuman::showAll('pengumuman', [
['pengumuman.status', '=', 1],
['pengumuman.category', '=', $get['data'][$i]['id']]
]));
}
} else {
$get['data']['posts'] = count(\App\Models\Pengumuman::showAll('pengumuman', [
['pengumuman.status', '=', 1],
['pengumuman.category', '=', $get['data']['id']]
]));
}
}
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);
if (isset($args['posts'])) unset($args['posts']);
$update = \App\Models\ApiModel::update($table, $args);
if (!is_array($update)) {
$put['status'] = false;
$put['message'] = $update;
} else {
$put['status'] = true;
$put['data'] = $update;
$put['count'] = count($put['data']);
$put['message'] = 'Proses berhasil';
}
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);
$entry = \App\Models\ApiModel::entry($table, $args);
$entry = \App\Models\ApiModel::showAll($table, [
['id', '=', $entry[0]]
]);
if (!is_array($entry)) {
$post['status'] = false;
$post['message'] = $entry;
} else {
$post['status'] = true;
$post['data'] = $entry;
$post['count'] = count($post['data']);
$post['message'] = 'Proses berhasil';
}
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);
$remove = \App\Models\ApiModel::remove($table, $args['id']);
if (!is_array($delete['data'])) {
$delete['status'] = false;
$delete['messsage'] = $remove;
} else {
$delete['status'] = true;
$delete['data'] = $remove;
$delete['count'] = count($delete['data']);
}
header('Content-Type: application/json');
echo json_encode($delete);
}
}