<?php
namespace App\Controller;
use App\Controller\Base\BaseController;
use App\Repository\TPublikasiRepository;
use App\Repository\TVariabelRepository;
use DateTime;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ApiController extends BaseController
{
/**
* @Route("/api/{id}", name="api", methods={"GET", "POST"})
*/
public function index(?string $id, Request $request, TPublikasiRepository $tPublikasiRepo)
{
$publikasi = $tPublikasiRepo->find($id);
$url = $this->base_url();
// dump($url); exit;
return $this->render('api/index.html.twig', [
'publikasi' => $publikasi,
'url' => $url,
]);
}
/**
* @Route("/api/{id}/get/{row}", name="api_get", methods={"GET"})
*/
public function getApi(?string $id, string $row = null, Request $request, TVariabelRepository $tVariabelRepo, TPublikasiRepository $tPublikasiRepo)
{
$tVariabel = $tVariabelRepo->findBy(['pub' => $id, 'is_tampil' => true], ['id'=>'asc']);
$tPublikasi = $tPublikasiRepo->find($id);
$dataset = $this->getDataTable($id, $request->get('limit', null), $request->get('skip', null), null, 1, $row);
if (!$dataset) {
$result['message'] = 'Data not found';
$result['status'] = 404;
$result['data'] = [];
return $this->json($result);
}
$variabel = array();
foreach($tVariabel as $var){
$variabel[] = $var->getNama();
}
foreach($dataset as $k => $dt)
{
foreach($variabel as $key => $var)
{
$dataset[$k][$var] = $dataset[$k][$key];
unset($dataset[$k][$key]);
}
}
$result['result'][0]['message'] = 'Get data successfull';
$result['result'][0]['status'] = 200;
$result['result'][0]['total'] = count($dataset);
$result['result'][0]['title'] = $tPublikasi->getJudul();
$result['result'][0]['description'] = $tPublikasi->getDeskripsi();
$result['result'][0]['unit'] = $tPublikasi->getSatuan();
$result['result'][0]['source'] = $tPublikasi->getSumber();
$result['result'][0]['year'] = $tPublikasi->getTahun();
// $result['result'][0]['urusan_code'] = ($tPublikasi->getUrusan()) ? $tPublikasi->getUrusan()->getKode() : '';
$result['result'][0]['urusan_code'] = '9';
// $result['result'][0]['sektor_code'] = ($tPublikasi->getSektor()) ? $tPublikasi->getSektor()->getKode() : '';
$result['result'][0]['sektor_code'] = '901';
$result['result'][0]['created_at'] = $tPublikasi->getCreatedAt()->format("Y-m-d H:i:s");
$result['result'][0]['updated_at'] = $tPublikasi->getUpdatedAt()->format("Y-m-d H:i:s");
$result['result'][0]['data'] = $dataset;
return $this->json($result);
}
/**
* @Route("/get/api", name="api_get_data", methods={"GET"})
*/
public function getData(Request $request)
{
// $token = "4a81432adf56aeb6aadfffa65ab70ab1";
$headers = apache_request_headers();
// if (!isset($headers['token']) || $headers['token'] != $token) {
// return $this->json(['status' => 400]);
// }
// $getToken = $headers['token'];
$request_body = file_get_contents('php://input');
header('Content-Type: application/json');
$get = json_decode($request_body, true);
if(isset($get['limit'])) {
if(!is_numeric($get['limit'])) {
$response = $this->deliver_response(400,"invalid request");
return $this->json($response);
}
}
if(isset($get['page'])) {
if(!is_numeric($get['page'])) {
$response = $this->deliver_response(400,"invalid request");
return $this->json($response);
}
}
if(isset($get['key'])) {
if(!is_numeric($get['key'])) {
$response = $this->deliver_response(400,"invalid request");
return $this->json($response);
}
}
// $conn = pg_connect("host=localhost port=5432 dbname=open user='postgres' password='piramida123'");
$conn = $this->getDoctrine()->getConnection();
if (!$conn) {
$response = $this->deliver_response(400,"connection failed");
return $this->json($response);
}
$key = isset($get['key']) ? ' AND a.id = ' . $get['key'] : '';
$limit = isset($get['limit']) ? $get['limit'] : 1;
$offset = null;
if (isset($get['limit']) && isset($get['page'])) {
$offset = $limit * ($get['page'] - 1);
}
else if(isset($get['page'])) {
$offset = $get['page'];
}
$sql_limit = " LIMIT $limit";
$sql_offset = " OFFSET $offset";
$ids_pub = "SELECT a.id
FROM t_publikasi a
WHERE a.status_id = 3 $key
ORDER BY a.id ASC";
if (!isset($get['key'])) {
if (isset($get['limit'])) {
$ids_pub .= $sql_limit;
}
if (isset($get['page'])) {
$ids_pub .= $sql_offset;
}
}
$stmt = $conn->prepare($ids_pub);
$stmt->execute();
// $result = pg_prepare($conn, 'ids', $ids_pub);
// $result = pg_execute($conn, 'ids', array());
$rs_ids = [];
foreach ($stmt->fetchAll() as $row)
{
$rs_ids[] = $row['id'];
}
// return $this->json($rs_ids);
$isHeader = true;
$isVariable = true;
$isData = true;
if (isset($get['type'])) {
$tipe = $get['type'];
switch ($tipe) {
case 'header':
$isHeader = true;
$isVariable = false;
$isData = false;
break;
case 'variable':
$isHeader = false;
$isVariable = true;
$isData = false;
break;
case 'data':
$isHeader = false;
$isVariable = false;
$isData = true;
break;
default:
break;
}
}
$hasil = [];
foreach ($rs_ids as $id) {
if ($isHeader) {
$sql = "SELECT a.id, a.kode as kode, a.judul as judul, a.satuan, a.sumber as sumber, c.periode,
a.tahun as tahun, a.deskripsi as deskripsi, d.div_nama as perangkat_daerah, e.nama as urusan,
f.nama as sektor, g.nama as status_verifikasi, a.updated_at as tanggal
FROM t_publikasi a
JOIN m_periode c
ON a.periode_id = c.id
JOIn t_div d
On a.div_id = d.id
JOIN m_urusan e
ON a.urusan_id = e.id
JOIN m_sektor f
ON a.sektor_id = f.id
JOIN m_status g
ON a.status_id = g.id
WHERE a.id = $id";
$stmt = $conn->prepare($sql);
$stmt->execute();
// $result = pg_prepare($conn, '', $sql);
// $result = pg_execute($conn, '', array());
foreach ($stmt->fetchAll() as $row)
{
$hasil[$id]['header'] = $row;
}
}
if ($isVariable) {
$sql = "SELECT a.nama
FROM t_variabel a
WHERE a.pub_id = $id AND is_tampil is true order by a.id asc";
$stmt = $conn->prepare($sql);
$stmt->execute();
// $result = pg_prepare($conn, '', $sql);
// $result = pg_execute($conn, '', array());
foreach ($stmt->fetchAll() as $row)
{
$hasil[$id]['variable'][] = $row['nama'];
}
}
if ($isData) {
$as_columns = "";
$sql = "SELECT a.*
FROM t_variabel a
WHERE a.pub_id = $id order by a.id asc";
$stmt = $conn->prepare($sql);
$stmt->execute();
// $result = pg_prepare($conn, '', $sql);
// $result = pg_execute($conn, '', array());
$as_columns = "";
$sel_columns = "row_id";
foreach ($stmt->fetchAll() as $row)
{
$as_columns .= ', "' . $row['nama'] . '" text';
if($row['nama'] != "periode_order") {
$sel_columns .= ", " .$row['nama'] .":: text";
}
}
$sql = "SELECT $sel_columns FROM crosstab($$ select a.row_id, b.id, a.isi
from t_data a
join t_variabel b
on a.variabel_id = b.id
where a.pub_id = $id order by 1, 2 $$)
AS ct (row_id int" .$as_columns. ") where 1=1
ORDER BY row_id";
$stmt = $conn->prepare($sql);
$stmt->execute();
// $rs = pg_prepare($conn, '', $sql);
// $rs = pg_execute($conn, '', array());
$hasil[$id]['data'] = [];
foreach ($stmt->fetchAll() as $row)
{
$hasil[$id]['data'][] = $row;
}
}
}
$data = (isset($hasil)) ? $hasil : [];
$response = $this->deliver_response(200, 'data found', $data);
return $this->json($response);
// return $this->json($get);
}
function deliver_response($status, $status_message, $data = [], $type = '')
{
// header("HTTP/1.1 $status $status_message");
$response = array();
$response['status'] = $status;
$response['status_message'] = $status_message;
// if($type == 'data') {
$response['total_data'] = count($data);
// }
$response['result'] = $data;
// $json = json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// echo $json;
return $response;
}
/**
* @Route("/data.json", name="api_json", methods={"GET"})
*/
public function getJsonData(Request $request, TPublikasiRepository $tPublikasiRepo)
{
header('Content-Type: application/json');
$data = array(
"@context" => "https://project-open-data.cio.gov/v1.1/schema/catalog.jsonld",
"@id" => "https://opendata.kedirikab.go.id/data.json",
"@type" => "dcat:Catalog",
"conformsTo" => "https://project-open-data.cio.gov/v1.1/schema",
"describedBy" => "https://project-open-data.cio.gov/v1.1/schema/catalog.json",
);
$dataset = [];
$publikasi = $tPublikasiRepo->findBy(["status" => 3]);
foreach ($publikasi as $pub) {
$dataset[] = [
"@type" => "dcat:Dataset",
"accessLevel" => "public",
"contactPoint" => [
"fn" => "Rustam",
"hasEmail" => "mailto:noemailprovided@usa.gov"
],
"distribution" => [
[
"@type" => "dcat:Distribution",
"downloadURL" => "https://opendata.kedirikab.go.id/dataset/" .$pub->getId(). "/csv/download_excel",
"mediaType" => "text/csv",
"format" => "csv",
"title" => $pub->getJudul()
]
],
"identifier" => md5($pub->getId()),
"issued" => "-",
"landingPage" => "https://opendata.kedirikab.go.id/dataset/" .$pub->getId(). "/detail",
"modified" => $pub->getCreatedAt()->format("Y-m-d"),
"publisher" => [
"@type" => "org:Organization",
"name" => "https://opendata.kedirikab.go.id/"
],
"title" => $pub->getJudul(),
"description" => $pub->getDeskripsi() ? strip_tags($pub->getDeskripsi()) : "",
"keyword" => is_array($pub->getKeyword()) ? implode(",", $pub->getKeyword()) : ""
];
}
$data['dataset'] = $dataset;
return $this->json($data);
}
}