Add resources defined in config and a bundle of the site's own screens

This commit is contained in:
Matthijs Iriks committed 2026-12-04 05:26:37 +01:00
1 parent 37a29d9195
commit 3345797141
35 files changed
+905 -19

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
/** The built screens, served by the package itself: the app does not need Node, a build step or a publish. */
class AssetController
{
private const FILES = ['manager.js' => 'application/javascript', 'manager.css' => 'text/css'];
private const FILES = ['manager.js' => 'application/javascript', 'manager.css' => 'text/css', 'vue.js' => 'application/javascript'];
public function __invoke(string $file): BinaryFileResponse
{
+2 -1
View File
@@ -25,7 +25,8 @@ class ManagerServiceProvider extends ServiceProvider
$this->app->singleton(Modules\Posts\PostLabels::class);
$this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry(
$app['config']->get('manager.available', []),
// A config that was published before resources existed does not list their module.
array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class])),
$app['config']->get('manager.modules', []),
));
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace IriksIT\Manager\Models;
/** A record of a resource that has no model of the site: its values are in `data`. */
class Record extends Model
{
protected function casts(): array
{
return ['data' => 'array'];
}
}
@@ -0,0 +1,108 @@
<?php
namespace IriksIT\Manager\Modules\Resources;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use IriksIT\Manager\Support\AuditTrail;
use IriksIT\Manager\Support\Fields;
use IriksIT\Manager\Support\Resources;
class ResourceController
{
public function index(string $resource): JsonResponse
{
$def = $this->resource($resource, 'view');
$page = Resources::query($def)->paginate($def['per_page']);
return response()->json([
'resource' => $this->describe($def),
'rows' => $page->getCollection()->map(fn (Model $model) => Resources::row($def, $model))->values(),
'current_page' => $page->currentPage(),
'last_page' => $page->lastPage(),
]);
}
public function create(string $resource): JsonResponse
{
$def = $this->resource($resource, 'manage');
return response()->json(['resource' => $this->describe($def), 'record' => ['id' => null, 'values' => Fields::values($def['fields'], [])]]);
}
public function edit(string $resource, string $id): JsonResponse
{
$def = $this->resource($resource, 'manage');
return response()->json(['resource' => $this->describe($def), 'record' => Resources::row($def, $this->record($def, $id))]);
}
public function store(Request $request, string $resource): JsonResponse
{
$def = $this->resource($resource, 'manage');
$model = Resources::save($def, null, $this->values($request, $def));
app(AuditTrail::class)->about($model);
return response()->json(['record' => Resources::row($def, $model)], 201);
}
public function update(Request $request, string $resource, string $id): JsonResponse
{
$def = $this->resource($resource, 'manage');
$model = Resources::save($def, $this->record($def, $id), $this->values($request, $def));
app(AuditTrail::class)->about($model);
return response()->json(['record' => Resources::row($def, $model)]);
}
public function destroy(string $resource, string $id): JsonResponse
{
$def = $this->resource($resource, 'manage');
$model = $this->record($def, $id);
app(AuditTrail::class)->about($model);
$model->delete();
return response()->json(['deleted' => true]);
}
/** @return array<string, mixed> */
private function resource(string $key, string $ability): array
{
$def = Resources::find($key);
abort_if($def === null, 404);
Gate::authorize($key.'.'.$ability);
return $def;
}
/** @param array<string, mixed> $def */
private function record(array $def, string $id): Model
{
return Resources::record($def, $id) ?? abort(404);
}
/**
* @param array<string, mixed> $def
* @return array<string, mixed>
*/
private function values(Request $request, array $def): array
{
$data = $request->validate(Fields::rules($def['fields']));
return Fields::clean($def['fields'], $data);
}
/**
* @param array<string, mixed> $def
* @return array<string, mixed>
*/
private function describe(array $def): array
{
return [
'key' => $def['key'], 'label' => $def['label'], 'singular' => $def['singular'], 'columns' => $def['columns'],
'fields' => array_values($def['fields']), 'can_manage' => Gate::allows($def['key'].'.manage'),
];
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace IriksIT\Manager\Modules\Resources;
use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permission;
use IriksIT\Manager\Support\Resources;
/**
* The lists a site defines in config (`manager.resources`): menu item, permissions and screens for each, with
* nothing registered when there are none.
*/
class ResourcesModule extends BaseModule
{
public function key(): string
{
return 'resources';
}
public function label(): string
{
return 'Resources';
}
public function enabledByDefault(): bool
{
return true;
}
public function tables(): array
{
return ['records'];
}
public function permissions(): array
{
$permissions = [];
foreach (Resources::all() as $key => $resource) {
$permissions[] = new Permission($key.'.view', __('See :label', ['label' => $resource['label']]), $resource['label']);
$permissions[] = new Permission($key.'.manage', __('Add, change and delete :label', ['label' => $resource['label']]), $resource['label'], needs: [$key.'.view']);
}
return $permissions;
}
public function navigation(): array
{
return array_values(array_map(
fn (array $resource) => ['id' => 'records.'.$resource['key'], 'label' => $resource['label'], 'route' => Names::route('records.index'), 'params' => ['resource' => $resource['key']], 'permission' => $resource['key'].'.view'],
Resources::all(),
));
}
public function actions(): array
{
return [
'records.store' => ['Added a record'],
'records.update' => ['Changed a record'],
'records.destroy' => ['Removed a record'],
];
}
public function views(): array
{
return ['records.index' => 'Opened a list', 'records.create' => 'Opened the form for a new record', 'records.edit' => 'Opened a record'];
}
}
@@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration
{
public function up(): void
{
Schema::create(Names::table('records'), function (Blueprint $table) {
$table->id();
$table->string('resource', 40)->index();
$table->json('data')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists(Names::table('records'));
}
};
+14
View File
@@ -0,0 +1,14 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Resources\ResourceController;
// Every resource the site defined shares these routes; the controller checks `<resource>.view` and `<resource>.manage`.
Route::prefix('/records/{resource}')->where(['resource' => '[a-z][a-z0-9_]*', 'id' => '[0-9]+'])->group(function () {
Route::get('/', [ResourceController::class, 'index'])->name('records.index');
Route::get('/create', [ResourceController::class, 'create'])->name('records.create');
Route::post('/', [ResourceController::class, 'store'])->name('records.store');
Route::get('/{id}/edit', [ResourceController::class, 'edit'])->name('records.edit');
Route::put('/{id}', [ResourceController::class, 'update'])->name('records.update');
Route::delete('/{id}', [ResourceController::class, 'destroy'])->name('records.destroy');
});
+1 -1
View File
@@ -67,7 +67,7 @@ final class Menu
$items[] = array_filter([
'label' => $item['label'],
'href' => isset($item['route']) ? route($item['route'], [], false) : (string) $item['url'],
'href' => isset($item['route']) ? route($item['route'], $item['params'] ?? [], false) : (string) $item['url'],
'section' => $item['section'] ?? null,
'icon' => $item['icon'] ?? null,
'new_tab' => ($item['new_tab'] ?? false) ?: null,
+1 -1
View File
@@ -151,7 +151,7 @@ final class ModuleRegistry
foreach ($this->active() as $module) {
foreach ($module->navigation() as $item) {
$short = isset($item['route']) ? Str::after($item['route'], Names::routePrefix()) : '';
$short = $item['id'] ?? (isset($item['route']) ? Str::after($item['route'], Names::routePrefix()) : '');
$item = [...$item, ...(array) ($changes[$short] ?? [])];
if (($item['hidden'] ?? false) === true) {
+122
View File
@@ -0,0 +1,122 @@
<?php
namespace IriksIT\Manager\Support;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model as Eloquent;
use IriksIT\Manager\Models\Record;
/**
* The resources of the site (config `manager.resources`): lists of records the screens make a form for,
* without code of the site's own. A resource is its fields (see `Fields`) plus where they are kept: in a
* model of the site (`model`, the field keys are its attributes) or, without one, in the package's own
* table of records.
*
* 'services' => ['label' => 'Services', 'singular' => 'Service', 'model' => App\Models\Service::class,
* 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], 'fields' => [...]]
*/
final class Resources
{
/** Names the permissions of modules that exist already would clash with. */
private const RESERVED = ['posts', 'pages', 'media', 'accounts', 'groups', 'audit', 'statistics', 'reviews', 'labels', 'profile', 'manager', 'records'];
/**
* @return array<string, array{key: string, label: string, singular: string, model: ?string, fields: array<string, array<string, mixed>>, columns: list<string>, order: array{0: string, 1: string}, per_page: int}>
*/
public static function all(): array
{
$out = [];
foreach ((array) config('manager.resources', []) as $key => $definition) {
if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) || in_array($key, self::RESERVED, true) || ! is_array($definition)) {
continue;
}
$fields = Fields::normalize((array) ($definition['fields'] ?? []));
$model = $definition['model'] ?? null;
$columns = array_values(array_filter((array) ($definition['columns'] ?? array_slice(array_keys($fields), 0, 3)), fn ($column) => isset($fields[$column])));
$order = (array) ($definition['order'] ?? []);
$out[$key] = [
'key' => $key,
'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))),
'singular' => (string) ($definition['singular'] ?? $definition['label'] ?? $key),
'model' => is_string($model) && is_subclass_of($model, Eloquent::class) ? $model : null,
'fields' => $fields,
'columns' => $columns,
'order' => [preg_match('/^[a-z_][a-z0-9_]*$/', (string) ($order[0] ?? '')) ? (string) $order[0] : 'id', ($order[1] ?? 'desc') === 'asc' ? 'asc' : 'desc'],
'per_page' => max(5, min(200, (int) ($definition['per_page'] ?? 50))),
];
}
return $out;
}
/** @return ?array<string, mixed> */
public static function find(string $key): ?array
{
return self::all()[$key] ?? null;
}
/**
* @param array<string, mixed> $resource
* @return Builder<Eloquent>
*/
public static function query(array $resource): Builder
{
[$column, $direction] = $resource['order'];
if ($resource['model'] !== null) {
return $resource['model']::query()->orderBy($column, $direction)->orderBy('id', 'desc');
}
// The package's own table keeps the values in one JSON column.
$query = Record::query()->where('resource', $resource['key']);
return $column !== 'id' && isset($resource['fields'][$column]) ? $query->orderBy('data->'.$column, $direction) : $query->orderBy('id', $column === 'id' ? $direction : 'desc');
}
/**
* @param array<string, mixed> $resource
* @return array<string, mixed>
*/
public static function row(array $resource, Eloquent $model): array
{
$stored = $resource['model'] === null ? (array) $model->getAttribute('data') : null;
$values = [];
foreach ($resource['fields'] as $key => $field) {
$values[$key] = $stored !== null ? ($stored[$key] ?? $field['default']) : ($model->getAttribute($key) ?? $field['default']);
}
return ['id' => $model->getKey(), 'values' => $values];
}
/**
* @param array<string, mixed> $resource
* @param array<string, mixed> $values cleaned by `Fields::clean`
*/
public static function save(array $resource, ?Eloquent $model, array $values): Eloquent
{
if ($resource['model'] === null) {
$model ??= new Record(['resource' => $resource['key']]);
$model->data = $values;
} else {
$model ??= new $resource['model'];
// Only the keys the site defined: the definition is the whitelist.
$model->forceFill($values);
}
$model->save();
return $model;
}
/**
* @param array<string, mixed> $resource
*/
public static function record(array $resource, int|string $id): ?Eloquent
{
return self::query($resource)->reorder()->whereKey($id)->first();
}
}
+7
View File
@@ -27,7 +27,13 @@ class Shell
$navigation = $this->menu->for($user, $allowed);
$extensions = array_values(array_filter(
(array) config('manager.extensions', []),
fn ($url) => is_string($url) && preg_match('#^(/(?!/)|https://)[^\s<>"\'\\\\]*$#', $url) === 1,
));
return [
'extensions' => $extensions,
'css' => $this->themes->css($theme),
'title' => $theme['name'] ?? config('manager.name') ?? config('app.name', 'Manager'),
'version' => is_file($dist.'/manager.js') ? substr(md5_file($dist.'/manager.js').md5_file($dist.'/manager.css'), 0, 10) : 'dev',
@@ -43,6 +49,7 @@ class Shell
],
'permissions' => $allowed,
'navigation' => $navigation,
'extensions' => $user === null ? [] : $extensions,
'view' => $this->menu->view($user),
'can_switch' => $this->menu->maySwitch($user),
'theme' => $key,