Add pages with fields, a field schema and the screens to edit them
This commit is contained in:
1 parent
ce1a8a1370
commit
517039b625
19 files changed
+660
-13
No files matched your search
+47
-1
@@ -2,4 +2,50 @@
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
class Page extends Model {}
|
||||
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', 'is_published' => 'boolean'];
|
||||
}
|
||||
|
||||
/**
|
||||
* The definitions of the pages: slug => ['title' => ..., 'fields' => normalized fields].
|
||||
*
|
||||
* @return array<string, array{title: string, fields: array<string, array<string, mixed>>}>
|
||||
*/
|
||||
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))), 'fields' => Fields::normalize((array) ($definition['fields'] ?? []))];
|
||||
}
|
||||
}
|
||||
|
||||
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 : []);
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,120 @@
|
||||
|
||||
namespace IriksIT\Manager\Modules\Pages;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Fields;
|
||||
|
||||
/**
|
||||
* Pages: the ones a site defines (config `manager.pages.definitions`: a title and fields per slug) and free
|
||||
* pages with one text. A defined page needs no setup: it is made the first time it is saved.
|
||||
*/
|
||||
class PagesController
|
||||
{
|
||||
/** First opzet: lists the records as JSON. The screens come with the frontend. */
|
||||
public function index()
|
||||
private const SLUG = '[a-z0-9]+(?:-[a-z0-9]+)*';
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return response()->json(Page::query()->latest()->paginate(25));
|
||||
$definitions = Page::definitions();
|
||||
$stored = Page::query()->orderBy('title')->get()->keyBy('slug');
|
||||
$pages = [];
|
||||
|
||||
foreach ($definitions as $slug => $definition) {
|
||||
$pages[] = ['slug' => $slug, 'title' => $definition['title'], 'defined' => true, 'saved' => $stored->has($slug), 'updated_at' => $stored[$slug]->updated_at ?? null];
|
||||
}
|
||||
|
||||
foreach ($stored as $slug => $page) {
|
||||
if (! isset($definitions[$slug])) {
|
||||
$pages[] = ['slug' => $slug, 'title' => $page->title, 'defined' => false, 'saved' => true, 'is_published' => $page->is_published, 'updated_at' => $page->updated_at];
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json(['pages' => $pages]);
|
||||
}
|
||||
|
||||
public function show(string $slug): JsonResponse
|
||||
{
|
||||
return response()->json(['page' => $this->payload($slug)]);
|
||||
}
|
||||
|
||||
/** Makes a free page. A defined page is made by saving it. */
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'slug' => ['required', 'string', 'max:120', 'regex:/^'.self::SLUG.'$/', Rule::unique(Page::query()->getModel()->getTable(), 'slug'), Rule::notIn(array_keys(Page::definitions()))],
|
||||
'title' => ['required', 'string', 'max:255'],
|
||||
]);
|
||||
|
||||
$page = Page::query()->create($data + ['is_published' => false]);
|
||||
app(AuditTrail::class)->about($page);
|
||||
|
||||
return response()->json(['page' => $this->payload($page->slug)], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
$definition = Page::definitions()[$slug] ?? null;
|
||||
$page = Page::query()->where('slug', $slug)->first();
|
||||
abort_if($definition === null && $page === null, 404);
|
||||
|
||||
$rules = [
|
||||
'title' => ['required', 'string', 'max:255'],
|
||||
'meta_description' => ['nullable', 'string', 'max:255'],
|
||||
];
|
||||
|
||||
if ($definition !== null) {
|
||||
$rules = [...$rules, 'content' => ['nullable', 'array'], ...Fields::rules($definition['fields'], 'content.')];
|
||||
} else {
|
||||
$rules = [...$rules, 'body' => ['nullable', 'string', 'max:200000'], 'is_published' => ['boolean']];
|
||||
}
|
||||
|
||||
$data = $request->validate($rules);
|
||||
$values = ['title' => $data['title'], 'meta_description' => ($data['meta_description'] ?? '') ?: null];
|
||||
|
||||
if ($definition !== null) {
|
||||
$values['content'] = Fields::clean($definition['fields'], (array) ($data['content'] ?? []));
|
||||
} else {
|
||||
$values += ['body' => $data['body'] ?? null, 'is_published' => (bool) ($data['is_published'] ?? false)];
|
||||
}
|
||||
|
||||
$page = $page ?? new Page(['slug' => $slug]);
|
||||
$page->fill($values)->save();
|
||||
app(AuditTrail::class)->about($page);
|
||||
|
||||
return response()->json(['page' => $this->payload($slug)]);
|
||||
}
|
||||
|
||||
/** Removes a free page; a defined page stays (its values go back to the defaults when it is emptied by saving). */
|
||||
public function destroy(string $slug): JsonResponse
|
||||
{
|
||||
abort_if(isset(Page::definitions()[$slug]), 422, __('A page with fields of its own cannot be removed.'));
|
||||
|
||||
$page = Page::query()->where('slug', $slug)->firstOrFail();
|
||||
app(AuditTrail::class)->about($page);
|
||||
$page->delete();
|
||||
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function payload(string $slug): array
|
||||
{
|
||||
$definition = Page::definitions()[$slug] ?? null;
|
||||
$page = Page::query()->where('slug', $slug)->first();
|
||||
abort_if($definition === null && $page === null, 404);
|
||||
|
||||
return [
|
||||
'slug' => $slug,
|
||||
'title' => $page->title ?? $definition['title'],
|
||||
'meta_description' => $page->meta_description ?? '',
|
||||
'defined' => $definition !== null,
|
||||
'fields' => array_values($definition['fields'] ?? []),
|
||||
'content' => $definition !== null ? Fields::values($definition['fields'], is_array($page?->content) ? $page->content : []) : null,
|
||||
'body' => $definition === null ? (string) $page->body : null,
|
||||
'is_published' => $definition === null ? (bool) $page->is_published : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -47,11 +47,20 @@ class PagesModule extends BaseModule
|
||||
/** Where the media library looks for the use of a file: the texts of the pages. */
|
||||
public function views(): array
|
||||
{
|
||||
return ['pages.index' => 'Opened the pages'];
|
||||
return ['pages.index' => 'Opened the pages', 'pages.show' => 'Opened a page'];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [
|
||||
'pages.store' => ['Created a page'],
|
||||
'pages.update' => ['Changed a page'],
|
||||
'pages.destroy' => ['Removed a page'],
|
||||
];
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
app(MediaUsage::class)->register(fn () => Page::query()->get(['body'])->flatMap(fn (Page $row) => array_values($row->only(['body']))));
|
||||
app(MediaUsage::class)->register(fn () => Page::query()->get(['body', 'content'])->flatMap(fn (Page $row) => [$row->body, ...array_values(array_filter((array) $row->content, 'is_string'))]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** The structured texts of a page (one value per defined field) and its description for search engines. */
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table(Names::table('pages'), function (Blueprint $table) {
|
||||
$table->string('meta_description', 255)->nullable()->after('title');
|
||||
$table->json('content')->nullable()->after('body');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table(Names::table('pages'), function (Blueprint $table) {
|
||||
$table->dropColumn(['meta_description', 'content']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -3,4 +3,10 @@
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Pages\PagesController;
|
||||
|
||||
Route::get('/pages', [PagesController::class, 'index'])->name('pages.index')->middleware('can:pages.edit');
|
||||
Route::middleware('can:pages.edit')->group(function () {
|
||||
Route::get('/pages', [PagesController::class, 'index'])->name('pages.index');
|
||||
Route::post('/pages', [PagesController::class, 'store'])->name('pages.store');
|
||||
Route::get('/pages/{slug}', [PagesController::class, 'show'])->name('pages.show')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*');
|
||||
Route::put('/pages/{slug}', [PagesController::class, 'update'])->name('pages.update')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*');
|
||||
Route::delete('/pages/{slug}', [PagesController::class, 'destroy'])->name('pages.destroy')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*');
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* Field definitions: what a page, or any other record a site manages without code of its own, is made of.
|
||||
* One definition drives the form of the screens, the validation and the cleaning of what is stored, so a
|
||||
* field is declared once:
|
||||
*
|
||||
* 'hero_title' => ['label' => 'Title on the photo', 'type' => 'text', 'help' => 'One line.', 'max' => 120]
|
||||
*
|
||||
* Types: `text` (one line), `textarea` (paragraphs), `markdown` (a long text in Markdown), `lines` (one item
|
||||
* per line), `media` (a picture from the media library; the value is its address), `url`, `number`, `date`,
|
||||
* `toggle` (a switch) and `select` (needs `options`: a list of values, or value => label). `required`, `default` and
|
||||
* `rules` (extra Laravel rules) are optional on every type.
|
||||
*/
|
||||
final class Fields
|
||||
{
|
||||
public const TYPES = ['text', 'textarea', 'markdown', 'lines', 'media', 'url', 'number', 'date', 'toggle', 'select'];
|
||||
|
||||
private const LENGTHS = ['text' => 255, 'textarea' => 20000, 'markdown' => 100000, 'lines' => 10000, 'media' => 2048, 'url' => 2048, 'date' => 40, 'select' => 255];
|
||||
|
||||
/**
|
||||
* The definitions in one shape, with a key, a label and a known type; what is wrong is dropped.
|
||||
*
|
||||
* @param array<array-key, mixed> $fields key => definition
|
||||
* @return array<string, array{key: string, label: string, type: string, help: ?string, required: bool, default: mixed, options: array<string, string>, max: ?int, rules: list<mixed>}>
|
||||
*/
|
||||
public static function normalize(array $fields): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,59}$/', $key) || ! is_array($field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$type = in_array($field['type'] ?? 'text', self::TYPES, true) ? ($field['type'] ?? 'text') : 'text';
|
||||
$options = [];
|
||||
|
||||
$given = (array) ($field['options'] ?? []);
|
||||
|
||||
foreach ($given as $value => $label) {
|
||||
$options[(string) (array_is_list($given) ? $label : $value)] = (string) $label;
|
||||
}
|
||||
|
||||
if ($type === 'select' && $options === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$out[$key] = [
|
||||
'key' => $key,
|
||||
'label' => (string) ($field['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
||||
'type' => $type,
|
||||
'help' => isset($field['help']) ? (string) $field['help'] : null,
|
||||
'required' => (bool) ($field['required'] ?? false),
|
||||
'default' => $field['default'] ?? self::empty($type),
|
||||
'options' => $options,
|
||||
'max' => isset($field['max']) ? max(1, (int) $field['max']) : null,
|
||||
'rules' => array_values((array) ($field['rules'] ?? [])),
|
||||
];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Laravel rules for the values, keyed `<prefix><key>`.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $fields normalized
|
||||
* @return array<string, list<mixed>>
|
||||
*/
|
||||
public static function rules(array $fields, string $prefix = ''): array
|
||||
{
|
||||
$rules = [];
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
$type = $field['type'];
|
||||
$max = $field['max'] ?? self::LENGTHS[$type] ?? null;
|
||||
$presence = $field['required'] ? 'required' : 'nullable';
|
||||
|
||||
$rules[$prefix.$key] = [$presence, ...match ($type) {
|
||||
'toggle' => ['boolean'],
|
||||
'number' => ['numeric'],
|
||||
'date' => ['date'],
|
||||
'select' => ['string', Rule::in(array_keys($field['options']))],
|
||||
'media', 'url' => ['string', 'max:'.$max, 'regex:'.self::ADDRESS],
|
||||
default => ['string', 'max:'.$max],
|
||||
}, ...$field['rules']];
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/** A web address or a path of the site. Never `javascript:` and its kin. */
|
||||
public const ADDRESS = '#^(/(?!/)|https?://)[^\s<>"\']*$#i';
|
||||
|
||||
/**
|
||||
* What is stored: only the known keys, in the type of the field, the default where nothing is given.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $fields normalized
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function clean(array $fields, array $input): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
$value = array_key_exists($key, $input) ? $input[$key] : $field['default'];
|
||||
|
||||
$out[$key] = match ($field['type']) {
|
||||
'toggle' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
|
||||
'number' => $value === null || $value === '' ? null : $value + 0,
|
||||
default => $value === null ? '' : (is_scalar($value) ? trim((string) $value) : ''),
|
||||
};
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored values over the defaults, for the screens and for the public site.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $fields normalized
|
||||
* @param array<array-key, mixed> $stored
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function values(array $fields, array $stored): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
$out[$key] = array_key_exists($key, $stored) ? $stored[$key] : $field['default'];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function empty(string $type): mixed
|
||||
{
|
||||
return match ($type) {
|
||||
'toggle' => false,
|
||||
'number' => null,
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user