Skip to content

Instantly share code, notes, and snippets.

@xadh00m
Created February 25, 2021 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xadh00m/c5ebed161b9951eb965aeaf807f65797 to your computer and use it in GitHub Desktop.
Save xadh00m/c5ebed161b9951eb965aeaf807f65797 to your computer and use it in GitHub Desktop.
Kirby CMS JSON router config
<?php
return [
'api' => [
'allowInsecure' => true,
'basicAuth' => true
],
'languages' => true,
'routes' => [
[
'pattern' => '(:all)',
'action' => function () {
$path = kirby()->request()->path();
$page = kirby()->page($path);
if($page !== NULL) {
return new Response([
'body' => Data::encode(pageToObject($page), 'json'),
'type' => 'application/json',
'code' => 200,
'headers' => ['Access-Control-Allow-Origin' => '*']
]);
} else {
return NULL;
}
}
]
]
];
function getFields($page) {
$table = array();
foreach (array_values($page->blueprint()->fields()) as $field) {
$table[strtolower($field['name'])] = $field;
}
return $table;
}
function pageToObject($page) {
$object = array();
$fields = getFields($page);
foreach ($page->translations()->toArray() as $language => $data) {
foreach ($data['content'] as $key => $value) {
$field = $fields[$key] ?? [ 'type' => 'string', 'name' => $key];
switch($field['type']) {
case 'files':
if($file = $page->file(preg_replace('/^- [>\n\s]*/', '', $value))) {
$object[$field['name']][$language] = $file->url();
} else {
$object[$field['name']][$language] = null;
}
break;
case 'number':
$object[$field['name']][$language] = (double)$value;
break;
default: $object[$field['name']][$language] = $value;
};
}
}
if ($page->hasChildren()) {
foreach($page->children() as $child)
{
$object[$child->uid()] = pageToObject($child);
}
}
return $object;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment