72 lines
2.6 KiB
PHP
72 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Models;
|
|
|
|
use IriksIT\Manager\Support\Blocks;
|
|
use IriksIT\Manager\Support\Fields;
|
|
|
|
/**
|
|
* A page of the site. A page with a definition (config `manager.pages.definitions`) keeps its texts in
|
|
* `content`, one value per defined field; any other page keeps one text in `body`.
|
|
*
|
|
* The public site reads it with `Page::contentFor('home')`: the stored values over the defaults, so a page
|
|
* that was never saved still has all its keys.
|
|
*/
|
|
class Page extends Model
|
|
{
|
|
protected function casts(): array
|
|
{
|
|
return ['content' => 'array', 'blocks' => 'array', 'is_published' => 'boolean'];
|
|
}
|
|
|
|
/**
|
|
* The definitions of the pages: slug => ['title' => ..., 'fields' => normalized fields].
|
|
*
|
|
* @return array<string, array{title: string, simple_title: ?string, fields: array<string, array<string, mixed>>, blocks: bool|list<string>}>
|
|
*/
|
|
public static function definitions(): array
|
|
{
|
|
$out = [];
|
|
|
|
foreach ((array) config('manager.pages.definitions', []) as $slug => $definition) {
|
|
if (is_string($slug) && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) && is_array($definition)) {
|
|
$out[$slug] = ['title' => (string) ($definition['title'] ?? ucfirst(str_replace('-', ' ', $slug))), 'simple_title' => Fields::simpleText($definition, 'title'), 'fields' => Fields::normalize((array) ($definition['fields'] ?? [])), 'blocks' => $definition['blocks'] ?? false];
|
|
}
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* What the public site shows on a page: every defined key, stored or default.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
public static function contentFor(string $slug): array
|
|
{
|
|
$fields = self::definitions()[$slug]['fields'] ?? [];
|
|
$page = self::query()->where('slug', $slug)->first();
|
|
|
|
return Fields::values($fields, is_array($page?->content) ? $page->content : []);
|
|
}
|
|
|
|
/**
|
|
* The block types a page may hold: a page with a definition says so in `blocks` (`true` for every type, or a list of types);
|
|
* a free page follows `manager.blocks.free_pages`. Empty: the page has no blocks.
|
|
*
|
|
* @return list<string>
|
|
*/
|
|
public static function blockTypesFor(string $slug): array
|
|
{
|
|
$definition = self::definitions()[$slug] ?? null;
|
|
$allowed = $definition !== null ? $definition['blocks'] : config('manager.blocks.free_pages', false);
|
|
$known = array_keys(Blocks::types());
|
|
|
|
if ($allowed === true) {
|
|
return $known;
|
|
}
|
|
|
|
return is_array($allowed) ? array_values(array_intersect($known, array_map('strval', $allowed))) : [];
|
|
}
|
|
}
|