Created
February 25, 2021 12:12
-
-
Save xadh00m/c5ebed161b9951eb965aeaf807f65797 to your computer and use it in GitHub Desktop.
Kirby CMS JSON router config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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