Merge pull request 'Route names and tables that can move, and manager:import' (#32) from feature/configurable-names into release/v0.5.0

This commit is contained in:
deploy-bot committed 2026-12-04 04:09:12 +00:00
commit 56de8ee76a
45 files changed
+491 -73

No files matched your search

+7
View File
@@ -4,6 +4,13 @@ Every release has a section here, named after its version (for example `v0.1.0 -
heading). The release pull request to `production` is stopped by PR CI when its section is missing, and the text of heading). The release pull request to `production` is stopped by PR CI when its section is missing, and the text of
the section is the text of the release in Gitea. the section is the text of the release in Gitea.
## v0.5.0 - 2026-12-04
- Names that can move: `route_name` for the route-name prefix, `tables` for a table of its own per short name (on top of `table_prefix`),
`IriksIT\Manager\Support\Names` to ask for either. The defaults are the names of every earlier version.
- `manager:import posts|pages|reviews` copies the rows of a table of the site into the package (read-only on the source, repeatable,
`--dry-run`, column mapping).
## v0.4.0 - 2026-12-04 ## v0.4.0 - 2026-12-04
- Screens in the package: a small Vue app on the JSON routes, built and served by the package (a site needs no Node). Login, logout and - Screens in the package: a small Vue app on the JSON routes, built and served by the package (a site needs no Node). Login, logout and
+8
View File
@@ -53,6 +53,14 @@ Switch a part in `config/manager.php` (`modules`) or with `MANAGER_PAGES`, `MANA
its migrations are not loaded at all. A module that needs another one (`requires()`) fails at boot when its migrations are not loaded at all. A module that needs another one (`requires()`) fails at boot when
that one is off. that one is off.
## A site with data and names of its own
The package never maps its queries onto other tables: every screen assumes its own columns. What it does give you is room to coexist and a way to move data in.
- `route_name` (default `manager`): the prefix of the route names. A site that already has `manager.*` routes sets, for example, `'route_name' => 'cms'`; the menu and the screens follow. Use `IriksIT\Manager\Support\Names::route('posts.index')` in code of your own.
- `table_prefix` (default `manager_`) and `tables` (`['media' => 'site_files']`): the names of the tables. Set them before the first `migrate`; the package does not rename a table that exists.
- `php artisan manager:import posts --table=articles --map=title=headline --map=body=content [--dry-run] [--connection=...] [--limit=...]` copies the rows of a table of the site into `posts`, `pages` or `reviews`. The source is only read, and running it again updates the rows it made (found by slug, or by author and text for reviews). `--map` is `package_column=source_column`. Put the settings in `manager.import.<target>` (`table`, `connection`, `map`) to run it without options. Tags may be JSON or a comma separated list; a row without the required text is skipped and reported.
## Your own module ## Your own module
Implement `IriksIT\Manager\Contracts\Module` (or extend `Modules\BaseModule`), keep `routes.php` and a Implement `IriksIT\Manager\Contracts\Module` (or extend `Modules\BaseModule`), keep `routes.php` and a
+2
View File
@@ -32,3 +32,5 @@ Per stuk werk een rij; zie `dev/token-usage.py`.
| 2026-12-04 | Changelog van v0.4.0, wiki en notitie in longterm-memory | - | claude-sonnet-5-5 | 7 | 3.891 | 14 | 5.215 | 1.999.583 | 0,01 | | 2026-12-04 | Changelog van v0.4.0, wiki en notitie in longterm-memory | - | claude-sonnet-5-5 | 7 | 3.891 | 14 | 5.215 | 1.999.583 | 0,01 |
| 2026-12-04 | De wekelijkse workflow werkt ook de npm-pakketten van de schermen bij, met 48 uur wachttijd en een nieuwe bundel | - | claude-sonnet-5-5 | 9 | 9.971 | 22 | 15.191 | 3.032.384 | 0,05 | | 2026-12-04 | De wekelijkse workflow werkt ook de npm-pakketten van de schermen bij, met 48 uur wachttijd en een nieuwe bundel | - | claude-sonnet-5-5 | 9 | 9.971 | 22 | 15.191 | 3.032.384 | 0,05 |
| 2026-12-04 | TypeScript 7 niet voorstellen zolang vue-tsc het niet draait, en de PR van de eerste run rechtgezet | - | claude-sonnet-5-5 | 10 | 4.340 | 26 | 4.489 | 3.503.406 | 0,05 | | 2026-12-04 | TypeScript 7 niet voorstellen zolang vue-tsc het niet draait, en de PR van de eerste run rechtgezet | - | claude-sonnet-5-5 | 10 | 4.340 | 26 | 4.489 | 3.503.406 | 0,05 |
| 2026-12-04 | Namen die kunnen verhuizen (route_name, tables) en manager:import voor bestaande gegevens | - | claude-sonnet-5-5 | 25 | 17.827 | 54 | 72.997 | 2.216.503 | 0,09 |
| 2026-12-04 | Namen die kunnen verhuizen (route_name, tables) en manager:import voor bestaande gegevens | - | claude-fable-5-2 | 1 | 5.062 | 61.001 | 0 | 0 | 0,00 |
+18
View File
@@ -149,4 +149,22 @@ return [
| Prefix for the tables of the package. | Prefix for the tables of the package.
*/ */
'table_prefix' => 'manager_', 'table_prefix' => 'manager_',
/*
| A table with a name of its own, by short name (`posts`, `pages`, `media`, ...): wins over the prefix.
| Set it before the first migrate; the package never renames a table that exists.
*/
'tables' => [],
/*
| Prefix of the route names (`manager.posts.index`). Change it when the site already has `manager.*`
| routes; menu items and screens follow by themselves.
*/
'route_name' => 'manager',
/*
| Where `php artisan manager:import <posts|pages|reviews>` reads from, so it needs no options:
| 'posts' => ['table' => 'articles', 'connection' => null, 'map' => ['title' => 'headline']].
*/
'import' => [],
]; ];
+2 -2
View File
@@ -7,11 +7,11 @@
<title>{{ $title }}</title> <title>{{ $title }}</title>
{{-- The theme: values were checked by IriksIT\Manager\Support\Themes, nothing else goes in here. --}} {{-- The theme: values were checked by IriksIT\Manager\Support\Themes, nothing else goes in here. --}}
<style>{!! $css !!}</style> <style>{!! $css !!}</style>
<link rel="stylesheet" href="{{ route('manager.assets', ['file' => 'manager.css'], false) }}?v={{ $version }}"> <link rel="stylesheet" href="{{ route(\IriksIT\Manager\Support\Names::route('assets'), ['file' => 'manager.css'], false) }}?v={{ $version }}">
</head> </head>
<body> <body>
<div id="manager"></div> <div id="manager"></div>
<script type="application/json" id="manager-boot">{!! json_encode($boot, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) !!}</script> <script type="application/json" id="manager-boot">{!! json_encode($boot, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) !!}</script>
<script type="module" src="{{ route('manager.assets', ['file' => 'manager.js'], false) }}?v={{ $version }}"></script> <script type="module" src="{{ route(\IriksIT\Manager\Support\Names::route('assets'), ['file' => 'manager.js'], false) }}?v={{ $version }}"></script>
</body> </body>
</html> </html>
+2 -1
View File
@@ -5,6 +5,7 @@ namespace IriksIT\Manager\Concerns;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use IriksIT\Manager\Models\Group; use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Support\ModuleRegistry; use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Support\Names;
/** /**
* Put this on the User model of the host app (needs the Users module). * Put this on the User model of the host app (needs the Users module).
@@ -18,7 +19,7 @@ trait HasManagerAccess
/** @return BelongsToMany<Group, $this> */ /** @return BelongsToMany<Group, $this> */
public function managerGroups(): BelongsToMany public function managerGroups(): BelongsToMany
{ {
return $this->belongsToMany(Group::class, config('manager.table_prefix').'group_user', 'user_id', 'group_id'); return $this->belongsToMany(Group::class, Names::table('group_user'), 'user_id', 'group_id');
} }
public function isManagerSuperAdmin(): bool public function isManagerSuperAdmin(): bool
+6 -6
View File
@@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Concerns\HasManagerAccess; use IriksIT\Manager\Concerns\HasManagerAccess;
use IriksIT\Manager\Support\ModuleRegistry; use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Support\Names;
/** /**
* Checks that the manager is wired into the app, and says what to do when it is not. Meant for people and for * Checks that the manager is wired into the app, and says what to do when it is not. Meant for people and for
@@ -86,7 +87,7 @@ class DoctorCommand extends Command
$this->add('super_admin_fillable', 'fail', 'is_super_admin is mass assignable: anyone who can fill the model could make themselves a super admin.', 'Remove is_super_admin from $fillable of the user model.'); $this->add('super_admin_fillable', 'fail', 'is_super_admin is mass assignable: anyone who can fill the model could make themselves a super admin.', 'Remove is_super_admin from $fillable of the user model.');
} }
if ($modules->enabled('users') && Schema::hasTable((new $model)->getTable()) && Schema::hasTable(config('manager.table_prefix').'groups')) { if ($modules->enabled('users') && Schema::hasTable((new $model)->getTable()) && Schema::hasTable(Names::table('groups'))) {
$admins = $model::query()->where('is_super_admin', true)->count(); $admins = $model::query()->where('is_super_admin', true)->count();
$admins > 0 $admins > 0
? $this->add('super_admin', 'ok', "{$admins} super admin(s) exist.") ? $this->add('super_admin', 'ok', "{$admins} super admin(s) exist.")
@@ -96,13 +97,12 @@ class DoctorCommand extends Command
private function checkTables(ModuleRegistry $modules): void private function checkTables(ModuleRegistry $modules): void
{ {
$prefix = config('manager.table_prefix');
$missing = []; $missing = [];
foreach ($modules->active() as $module) { foreach ($modules->active() as $module) {
foreach (method_exists($module, 'tables') ? $module->tables() : [] as $table) { foreach (method_exists($module, 'tables') ? $module->tables() : [] as $table) {
if (! Schema::hasTable($prefix.$table)) { if (! Schema::hasTable(Names::table($table))) {
$missing[] = $prefix.$table; $missing[] = Names::table($table);
} }
} }
} }
@@ -114,13 +114,13 @@ class DoctorCommand extends Command
private function checkRoutes(): void private function checkRoutes(): void
{ {
Route::has('manager.dashboard') Route::has(Names::route('dashboard'))
? $this->add('routes', 'ok', 'The manager routes are registered under /'.trim((string) config('manager.path'), '/').'.') ? $this->add('routes', 'ok', 'The manager routes are registered under /'.trim((string) config('manager.path'), '/').'.')
: $this->add('routes', 'fail', 'The manager routes are not registered.', 'Run `composer dump-autoload` and make sure the package service provider is discovered (not in dont-discover).'); : $this->add('routes', 'fail', 'The manager routes are not registered.', 'Run `composer dump-autoload` and make sure the package service provider is discovered (not in dont-discover).');
if (Route::has('login')) { if (Route::has('login')) {
$this->add('login', 'ok', 'The app has a login route.'); $this->add('login', 'ok', 'The app has a login route.');
} elseif (Route::has('manager.login')) { } elseif (Route::has(Names::route('login'))) {
$this->add('login', 'ok', 'The app has no login of its own: visitors use the login of the manager.'); $this->add('login', 'ok', 'The app has no login of its own: visitors use the login of the manager.');
} else { } else {
$this->add('login', 'warn', 'There is no login: the auth middleware has nowhere to send visitors.', 'Set MANAGER_UI=package (the manager brings a login), or add a login to the app.'); $this->add('login', 'warn', 'There is no login: the auth middleware has nowhere to send visitors.', 'Set MANAGER_UI=package (the manager brings a login), or add a login to the app.');
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace IriksIT\Manager\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use IriksIT\Manager\Support\Importer;
/**
* Copies a site's existing table into a table of the package. The source is only read.
*
* php artisan manager:import posts --table=articles --map=title=headline --map=body=content --dry-run
*
* Mappings can also be set once in config `manager.import.<target>` (`table`, `connection`, `map`).
*/
class ImportCommand extends Command
{
protected $signature = 'manager:import {target : posts, pages or reviews}
{--table= : Table to read (default: config manager.import.<target>.table)}
{--connection= : Database connection of that table (default: the default one)}
{--map=* : package_column=source_column, repeat for each column that is named differently}
{--limit= : Only the first rows}
{--dry-run : Count what would happen and write nothing}';
protected $description = 'Copy the existing posts, pages or reviews of the site into the package tables';
public function handle(Importer $importer): int
{
$target = (string) $this->argument('target');
$config = (array) config('manager.import.'.$target, []);
$table = $this->option('table') ?: ($config['table'] ?? null);
if (! is_string($table) || $table === '') {
$this->error('Which table? Give --table=... or set manager.import.'.$target.'.table.');
return self::FAILURE;
}
$map = (array) ($config['map'] ?? []);
foreach ((array) $this->option('map') as $pair) {
if (! str_contains((string) $pair, '=')) {
$this->error("--map wants package_column=source_column, got {$pair}");
return self::FAILURE;
}
[$to, $from] = explode('=', (string) $pair, 2);
$map[trim($to)] = trim($from);
}
try {
$connection = DB::connection($this->option('connection') ?: ($config['connection'] ?? null));
$result = $importer->run($target, $connection, $table, $map, (bool) $this->option('dry-run'), $this->option('limit') !== null ? (int) $this->option('limit') : null);
} catch (InvalidArgumentException $e) {
$this->error($e->getMessage());
return self::FAILURE;
}
foreach ($result['problems'] as $problem) {
$this->warn($problem);
}
$this->info(($this->option('dry-run') ? 'Dry run: ' : '')."{$result['created']} created, {$result['updated']} updated, {$result['skipped']} skipped.");
return self::SUCCESS;
}
}
+2 -1
View File
@@ -7,6 +7,7 @@ use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use IriksIT\Manager\Support\Names;
/** The manager's own login, for an app that has none. Failed attempts reach the audit log through Laravel's `Failed` event. */ /** The manager's own login, for an app that has none. Failed attempts reach the audit log through Laravel's `Failed` event. */
class LoginController class LoginController
@@ -33,6 +34,6 @@ class LoginController
$request->session()->invalidate(); $request->session()->invalidate();
$request->session()->regenerateToken(); $request->session()->regenerateToken();
return response()->json(['redirect' => Route::has('manager.login') ? route('manager.login', [], false) : '/']); return response()->json(['redirect' => Route::has(Names::route('login')) ? route(Names::route('login'), [], false) : '/']);
} }
} }
+2 -1
View File
@@ -5,6 +5,7 @@ namespace IriksIT\Manager\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware; use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Support\Names;
/** `auth`, but a visitor goes to the login of the host app when it has one and to the manager's own login when not. */ /** `auth`, but a visitor goes to the login of the host app when it has one and to the manager's own login when not. */
class Authenticate extends Middleware class Authenticate extends Middleware
@@ -15,6 +16,6 @@ class Authenticate extends Middleware
return null; return null;
} }
return Route::has('login') ? route('login') : (Route::has('manager.login') ? route('manager.login') : null); return Route::has('login') ? route('login') : (Route::has(Names::route('login')) ? route(Names::route('login')) : null);
} }
} }
+2 -1
View File
@@ -4,6 +4,7 @@ namespace IriksIT\Manager\Http\Middleware;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Shell; use IriksIT\Manager\Support\Shell;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@@ -22,7 +23,7 @@ class ServeShell
$name = (string) $request->route()?->getName(); $name = (string) $request->route()?->getName();
if ($name === 'manager.assets' || str_ends_with($name, '.export')) { if ($name === Names::route('assets') || str_ends_with($name, '.export')) {
return $next($request); return $next($request);
} }
+4 -3
View File
@@ -9,6 +9,7 @@ use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use IriksIT\Manager\Support\ModuleRegistry; use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Support\Names;
class ManagerServiceProvider extends ServiceProvider class ManagerServiceProvider extends ServiceProvider
{ {
@@ -54,7 +55,7 @@ class ManagerServiceProvider extends ServiceProvider
} }
if ($this->app->runningInConsole()) { if ($this->app->runningInConsole()) {
$this->commands([Console\InstallCommand::class, Console\DoctorCommand::class, Console\MakeThemeCommand::class]); $this->commands([Console\InstallCommand::class, Console\DoctorCommand::class, Console\MakeThemeCommand::class, Console\ImportCommand::class]);
} }
$this->registerGates($modules); $this->registerGates($modules);
@@ -82,13 +83,13 @@ class ManagerServiceProvider extends ServiceProvider
// Outside `auth`, but behind the bans of the modules. // Outside `auth`, but behind the bans of the modules.
Route::middleware(['web', ...$modules->middleware('before'), 'manager.shell']) Route::middleware(['web', ...$modules->middleware('before'), 'manager.shell'])
->prefix(config('manager.path')) ->prefix(config('manager.path'))
->name('manager.') ->name(Names::routePrefix())
->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/guest.php')); ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/guest.php'));
} }
Route::middleware([...$modules->middleware('before'), ...config('manager.middleware'), ...($screens ? ['manager.shell'] : []), ...$modules->middleware('after')]) Route::middleware([...$modules->middleware('before'), ...config('manager.middleware'), ...($screens ? ['manager.shell'] : []), ...$modules->middleware('after')])
->prefix(config('manager.path')) ->prefix(config('manager.path'))
->name('manager.') ->name(Names::routePrefix())
->group(function () use ($modules) { ->group(function () use ($modules) {
$this->loadRoutesFrom(__DIR__.'/../routes/manager.php'); $this->loadRoutesFrom(__DIR__.'/../routes/manager.php');
+2 -1
View File
@@ -4,6 +4,7 @@ namespace IriksIT\Manager\Models;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use IriksIT\Manager\Support\ModuleRegistry; use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Support\Names;
/** /**
* A set of permissions with a name ("Writers"). Accounts are put in groups; a group is the * A set of permissions with a name ("Writers"). Accounts are put in groups; a group is the
@@ -20,7 +21,7 @@ class Group extends Model
public function users(): BelongsToMany public function users(): BelongsToMany
{ {
return $this->belongsToMany(config('manager.user_model'), config('manager.table_prefix').'group_user', 'group_id', 'user_id'); return $this->belongsToMany(config('manager.user_model'), Names::table('group_user'), 'group_id', 'user_id');
} }
/** /**
+2 -1
View File
@@ -3,6 +3,7 @@
namespace IriksIT\Manager\Models; namespace IriksIT\Manager\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use IriksIT\Manager\Support\Names;
/** /**
* One file in the media library. The row is the bookkeeping; the file itself is stored on the * One file in the media library. The row is the bookkeeping; the file itself is stored on the
@@ -14,7 +15,7 @@ class Media extends Model
public function getTable(): string public function getTable(): string
{ {
return config('manager.table_prefix').'media'; return Names::table('media');
} }
protected function casts(): array protected function casts(): array
+2 -1
View File
@@ -3,6 +3,7 @@
namespace IriksIT\Manager\Models; namespace IriksIT\Manager\Models;
use Illuminate\Database\Eloquent\Model as Eloquent; use Illuminate\Database\Eloquent\Model as Eloquent;
use IriksIT\Manager\Support\Names;
/** Base of the package models: tables get the configured prefix, e.g. manager_pages. */ /** Base of the package models: tables get the configured prefix, e.g. manager_pages. */
abstract class Model extends Eloquent abstract class Model extends Eloquent
@@ -11,6 +12,6 @@ abstract class Model extends Eloquent
public function getTable(): string public function getTable(): string
{ {
return $this->table ?? config('manager.table_prefix').parent::getTable(); return $this->table ?? Names::table(parent::getTable());
} }
} }
+2 -1
View File
@@ -3,6 +3,7 @@
namespace IriksIT\Manager\Models; namespace IriksIT\Manager\Models;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use IriksIT\Manager\Support\Names;
/** What one account chose for itself in the manager (now: its theme). */ /** What one account chose for itself in the manager (now: its theme). */
class UserSetting extends Model class UserSetting extends Model
@@ -11,6 +12,6 @@ class UserSetting extends Model
public function getTable(): string public function getTable(): string
{ {
return config('manager.table_prefix').'user_settings'; return Names::table('user_settings');
} }
} }
+3 -2
View File
@@ -15,6 +15,7 @@ use IriksIT\Manager\Models\IpBan;
use IriksIT\Manager\Models\IpNote; use IriksIT\Manager\Models\IpNote;
use IriksIT\Manager\Models\Post; use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Support\AuditTrail; use IriksIT\Manager\Support\AuditTrail;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\UserAgent; use IriksIT\Manager\Support\UserAgent;
/** /**
@@ -86,7 +87,7 @@ class AuditController
'type' => str_replace('_', ' ', (string) $entry->subject_type), 'type' => str_replace('_', ' ', (string) $entry->subject_type),
'label' => $entry->subject_label, 'label' => $entry->subject_label,
'url' => $entry->subject_type === 'post' && in_array($entry->subject_id, $posts, true) 'url' => $entry->subject_type === 'post' && in_array($entry->subject_id, $posts, true)
? route('manager.posts.edit', $entry->subject_id, false) ? route(Names::route('posts.edit'), $entry->subject_id, false)
: null, : null,
], ],
'details' => $entry->details ?? [], 'details' => $entry->details ?? [],
@@ -305,7 +306,7 @@ class AuditController
*/ */
private function existingPosts(array $ids): array private function existingPosts(array $ids): array
{ {
if ($ids === [] || ! Route::has('manager.posts.edit')) { if ($ids === [] || ! Route::has(Names::route('posts.edit'))) {
return []; return [];
} }
+2 -1
View File
@@ -12,6 +12,7 @@ use Illuminate\Support\Facades\Event;
use IriksIT\Manager\Models\AuditLog; use IriksIT\Manager\Models\AuditLog;
use IriksIT\Manager\Modules\BaseModule; use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\AuditTrail; use IriksIT\Manager\Support\AuditTrail;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permission; use IriksIT\Manager\Support\Permission;
/** /**
@@ -51,7 +52,7 @@ class AuditModule extends BaseModule
public function navigation(): array public function navigation(): array
{ {
return [['label' => 'Audit log', 'route' => 'manager.audit.index', 'permission' => 'audit.view']]; return [['label' => 'Audit log', 'route' => Names::route('audit.index'), 'permission' => 'audit.view']];
} }
public function commands(): array public function commands(): array
@@ -3,16 +3,16 @@
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration return new class extends Migration
{ {
public function up(): void public function up(): void
{ {
$prefix = config('manager.table_prefix');
// Who did what in the manager, and every attempt to log in. A row stands on its own: the // Who did what in the manager, and every attempt to log in. A row stands on its own: the
// name of the account is copied, so it stays readable after the account is deleted. // name of the account is copied, so it stays readable after the account is deleted.
Schema::create($prefix.'audit_logs', function (Blueprint $table) { Schema::create(Names::table('audit_logs'), function (Blueprint $table) {
$table->id(); $table->id();
$table->string('event', 40)->index(); $table->string('event', 40)->index();
// The route that was called, for an action in the manager. // The route that was called, for an action in the manager.
@@ -32,7 +32,7 @@ return new class extends Migration
}); });
// Addresses that are kept out of the manager, or off the whole site. // Addresses that are kept out of the manager, or off the whole site.
Schema::create($prefix.'ip_bans', function (Blueprint $table) { Schema::create(Names::table('ip_bans'), function (Blueprint $table) {
$table->id(); $table->id();
$table->string('ip', 45)->unique(); $table->string('ip', 45)->unique();
$table->string('reason')->nullable(); $table->string('reason')->nullable();
@@ -49,7 +49,7 @@ return new class extends Migration
}); });
// One row (id 1) with the rules; without it the defaults of the model count. // One row (id 1) with the rules; without it the defaults of the model count.
Schema::create($prefix.'audit_settings', function (Blueprint $table) { Schema::create(Names::table('audit_settings'), function (Blueprint $table) {
$table->id(); $table->id();
$table->boolean('auto_ban')->default(true); $table->boolean('auto_ban')->default(true);
$table->unsignedSmallInteger('max_failures')->default(10); $table->unsignedSmallInteger('max_failures')->default(10);
@@ -59,7 +59,7 @@ return new class extends Migration
$table->timestamps(); $table->timestamps();
}); });
Schema::create($prefix.'ip_notes', function (Blueprint $table) { Schema::create(Names::table('ip_notes'), function (Blueprint $table) {
$table->id(); $table->id();
$table->string('ip', 45)->unique(); $table->string('ip', 45)->unique();
// Addresses that belong together carry the same name here; null: no group. // Addresses that belong together carry the same name here; null: no group.
@@ -73,10 +73,9 @@ return new class extends Migration
public function down(): void public function down(): void
{ {
$prefix = config('manager.table_prefix');
foreach (['ip_notes', 'audit_settings', 'ip_bans', 'audit_logs'] as $table) { foreach (['ip_notes', 'audit_settings', 'ip_bans', 'audit_logs'] as $table) {
Schema::dropIfExists($prefix.$table); Schema::dropIfExists(Names::table($table));
} }
} }
}; };
+2 -1
View File
@@ -6,6 +6,7 @@ use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\RateLimiter;
use IriksIT\Manager\Modules\BaseModule; use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permission; use IriksIT\Manager\Support\Permission;
class MediaModule extends BaseModule class MediaModule extends BaseModule
@@ -43,7 +44,7 @@ class MediaModule extends BaseModule
public function navigation(): array public function navigation(): array
{ {
return [ return [
['label' => 'Media', 'route' => 'manager.media.index', 'permission' => 'media.view'], ['label' => 'Media', 'route' => Names::route('media.index'), 'permission' => 'media.view'],
]; ];
} }
@@ -3,6 +3,7 @@
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration return new class extends Migration
{ {
@@ -11,7 +12,7 @@ return new class extends Migration
$users = (new (config('manager.user_model')))->getTable(); $users = (new (config('manager.user_model')))->getTable();
// The file itself is elsewhere: `disk` says where, `location` is its path there. // The file itself is elsewhere: `disk` says where, `location` is its path there.
Schema::create(config('manager.table_prefix').'media', function (Blueprint $table) use ($users) { Schema::create(Names::table('media'), function (Blueprint $table) use ($users) {
$table->id(); $table->id();
$table->string('disk', 40); $table->string('disk', 40);
$table->string('location'); $table->string('location');
@@ -34,6 +35,6 @@ return new class extends Migration
public function down(): void public function down(): void
{ {
Schema::dropIfExists(config('manager.table_prefix').'media'); Schema::dropIfExists(Names::table('media'));
} }
}; };
+2 -1
View File
@@ -2,6 +2,7 @@
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Media\MediaFileController; use IriksIT\Manager\Modules\Media\MediaFileController;
use IriksIT\Manager\Support\Names;
// Files of the media library, for visitors. No session and no cookies: this is a file, not a // Files of the media library, for visitors. No session and no cookies: this is a file, not a
// page, and the browser may cache it for good. The address ends in /view on purpose: web servers // page, and the browser may cache it for good. The address ends in /view on purpose: web servers
@@ -9,4 +10,4 @@ use IriksIT\Manager\Modules\Media\MediaFileController;
Route::get('/media-files/{media}/{filename}/view', MediaFileController::class) Route::get('/media-files/{media}/{filename}/view', MediaFileController::class)
->whereNumber('media') ->whereNumber('media')
->middleware('throttle:media-files') ->middleware('throttle:media-files')
->name('manager.media.file'); ->name(Names::route('media.file'));
+2 -1
View File
@@ -5,6 +5,7 @@ namespace IriksIT\Manager\Modules\Pages;
use IriksIT\Manager\Models\Page; use IriksIT\Manager\Models\Page;
use IriksIT\Manager\Modules\BaseModule; use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\MediaUsage; use IriksIT\Manager\Support\MediaUsage;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permission; use IriksIT\Manager\Support\Permission;
class PagesModule extends BaseModule class PagesModule extends BaseModule
@@ -39,7 +40,7 @@ class PagesModule extends BaseModule
public function navigation(): array public function navigation(): array
{ {
return [ return [
['label' => 'Pages', 'route' => 'manager.pages.index', 'permission' => 'pages.edit'], ['label' => 'Pages', 'route' => Names::route('pages.index'), 'permission' => 'pages.edit'],
]; ];
} }
@@ -3,12 +3,13 @@
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration return new class extends Migration
{ {
public function up(): void public function up(): void
{ {
Schema::create(config('manager.table_prefix').'pages', function (Blueprint $table) { Schema::create(Names::table('pages'), function (Blueprint $table) {
$table->id(); $table->id();
$table->string('slug')->unique(); $table->string('slug')->unique();
$table->string('title'); $table->string('title');
@@ -20,6 +21,6 @@ return new class extends Migration
public function down(): void public function down(): void
{ {
Schema::dropIfExists(config('manager.table_prefix').'pages'); Schema::dropIfExists(Names::table('pages'));
} }
}; };
+2 -1
View File
@@ -10,6 +10,7 @@ use Illuminate\Validation\Rule;
use IriksIT\Manager\Models\Post; use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Support\AuditTrail; use IriksIT\Manager\Support\AuditTrail;
use IriksIT\Manager\Support\Markdown; use IriksIT\Manager\Support\Markdown;
use IriksIT\Manager\Support\Names;
/** /**
* The posts. A post that is live or scheduled is only changed or deleted by who may publish: a * The posts. A post that is live or scheduled is only changed or deleted by who may publish: a
@@ -137,7 +138,7 @@ class PostController
{ {
$request->validate([ $request->validate([
'title' => ['required', 'string', 'max:255'], 'title' => ['required', 'string', 'max:255'],
'slug' => ['nullable', 'string', 'max:255', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', Rule::unique(config('manager.table_prefix').'posts', 'slug')->ignore($post?->id)], 'slug' => ['nullable', 'string', 'max:255', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', Rule::unique(Names::table('posts'), 'slug')->ignore($post?->id)],
'excerpt' => ['nullable', 'string', 'max:500'], 'excerpt' => ['nullable', 'string', 'max:500'],
'body' => ['required', 'string'], 'body' => ['required', 'string'],
'cover_image' => ['nullable', 'string', 'max:2048'], 'cover_image' => ['nullable', 'string', 'max:2048'],
+2 -1
View File
@@ -5,6 +5,7 @@ namespace IriksIT\Manager\Modules\Posts;
use Closure; use Closure;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use IriksIT\Manager\Models\Post; use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Support\Names;
/** /**
* The categories and tags of the posts, for managing them in one place. A category is the * The categories and tags of the posts, for managing them in one place. A category is the
@@ -49,7 +50,7 @@ class PostLabels
private function table(): string private function table(): string
{ {
return config('manager.table_prefix').'post_labels'; return Names::table('post_labels');
} }
/** /**
+3 -2
View File
@@ -5,6 +5,7 @@ namespace IriksIT\Manager\Modules\Posts;
use IriksIT\Manager\Models\Post; use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Modules\BaseModule; use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\MediaUsage; use IriksIT\Manager\Support\MediaUsage;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permission; use IriksIT\Manager\Support\Permission;
class PostsModule extends BaseModule class PostsModule extends BaseModule
@@ -43,8 +44,8 @@ class PostsModule extends BaseModule
public function navigation(): array public function navigation(): array
{ {
return [ return [
['label' => 'Posts', 'route' => 'manager.posts.index', 'permission' => 'posts.view'], ['label' => 'Posts', 'route' => Names::route('posts.index'), 'permission' => 'posts.view'],
['label' => 'Categories and tags', 'route' => 'manager.labels.index', 'permission' => 'posts.labels'], ['label' => 'Categories and tags', 'route' => Names::route('labels.index'), 'permission' => 'posts.labels'],
]; ];
} }
@@ -3,14 +3,14 @@
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration return new class extends Migration
{ {
public function up(): void public function up(): void
{ {
$prefix = config('manager.table_prefix');
Schema::create($prefix.'posts', function (Blueprint $table) { Schema::create(Names::table('posts'), function (Blueprint $table) {
$table->id(); $table->id();
$table->string('title'); $table->string('title');
$table->string('slug')->unique(); $table->string('slug')->unique();
@@ -27,7 +27,7 @@ return new class extends Migration
// Categories and tags that were made by hand, so one can exist before a post uses it. // Categories and tags that were made by hand, so one can exist before a post uses it.
// The ones a post uses are in the post itself; this only remembers names to offer. // The ones a post uses are in the post itself; this only remembers names to offer.
Schema::create($prefix.'post_labels', function (Blueprint $table) { Schema::create(Names::table('post_labels'), function (Blueprint $table) {
$table->id(); $table->id();
$table->string('type', 10); $table->string('type', 10);
$table->string('name', 60); $table->string('name', 60);
@@ -39,9 +39,8 @@ return new class extends Migration
public function down(): void public function down(): void
{ {
$prefix = config('manager.table_prefix');
Schema::dropIfExists($prefix.'post_labels'); Schema::dropIfExists(Names::table('post_labels'));
Schema::dropIfExists($prefix.'posts'); Schema::dropIfExists(Names::table('posts'));
} }
}; };
+2 -1
View File
@@ -3,6 +3,7 @@
namespace IriksIT\Manager\Modules\Reviews; namespace IriksIT\Manager\Modules\Reviews;
use IriksIT\Manager\Modules\BaseModule; use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permission; use IriksIT\Manager\Support\Permission;
class ReviewsModule extends BaseModule class ReviewsModule extends BaseModule
@@ -37,7 +38,7 @@ class ReviewsModule extends BaseModule
public function navigation(): array public function navigation(): array
{ {
return [ return [
['label' => 'Reviews', 'route' => 'manager.reviews.index', 'permission' => 'reviews.manage'], ['label' => 'Reviews', 'route' => Names::route('reviews.index'), 'permission' => 'reviews.manage'],
]; ];
} }
@@ -3,12 +3,13 @@
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration return new class extends Migration
{ {
public function up(): void public function up(): void
{ {
Schema::create(config('manager.table_prefix').'reviews', function (Blueprint $table) { Schema::create(Names::table('reviews'), function (Blueprint $table) {
$table->id(); $table->id();
$table->string('author'); $table->string('author');
$table->string('place')->nullable(); $table->string('place')->nullable();
@@ -21,6 +22,6 @@ return new class extends Migration
public function down(): void public function down(): void
{ {
Schema::dropIfExists(config('manager.table_prefix').'reviews'); Schema::dropIfExists(Names::table('reviews'));
} }
}; };
+2 -1
View File
@@ -4,6 +4,7 @@ namespace IriksIT\Manager\Modules\Statistics;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\UserAgent; use IriksIT\Manager\Support\UserAgent;
/** /**
@@ -30,7 +31,7 @@ final class BotRecorder
/** Counts one page that was served to a program. Does nothing for a person. */ /** Counts one page that was served to a program. Does nothing for a person. */
public function hit(string $userAgent, string $path): void public function hit(string $userAgent, string $path): void
{ {
$table = config('manager.table_prefix').'bot_hits'; $table = Names::table('bot_hits');
$bot = (new UserAgent($userAgent))->bot(); $bot = (new UserAgent($userAgent))->bot();
if ($bot === null) { if ($bot === null) {
+2 -1
View File
@@ -7,6 +7,7 @@ use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use IriksIT\Manager\Facades\Manager; use IriksIT\Manager\Facades\Manager;
use IriksIT\Manager\Models\Post; use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Support\Names;
/** /**
* The numbers of the visitor statistics, for the manager. The only code that * The numbers of the visitor statistics, for the manager. The only code that
@@ -735,7 +736,7 @@ final class Statistics
/** A count or sum as the database gives it (int, numeric string or null). */ /** A count or sum as the database gives it (int, numeric string or null). */
private function table(string $name): string private function table(string $name): string
{ {
return config('manager.table_prefix').$name; return Names::table($name);
} }
private static function number(mixed $value): int private static function number(mixed $value): int
+2 -1
View File
@@ -8,6 +8,7 @@ use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\RateLimiter;
use IriksIT\Manager\Modules\BaseModule; use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permission; use IriksIT\Manager\Support\Permission;
/** /**
@@ -45,7 +46,7 @@ class StatisticsModule extends BaseModule
public function navigation(): array public function navigation(): array
{ {
return [['label' => 'Statistics', 'route' => 'manager.statistics.index', 'permission' => 'statistics.view']]; return [['label' => 'Statistics', 'route' => Names::route('statistics.index'), 'permission' => 'statistics.view']];
} }
public function commands(): array public function commands(): array
@@ -3,6 +3,7 @@
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
/** /**
* The site's own visitor statistics. No cookie and no IP address: a visitor is a code made of the * The site's own visitor statistics. No cookie and no IP address: a visitor is a code made of the
@@ -18,16 +19,15 @@ return new class extends Migration
{ {
public function up(): void public function up(): void
{ {
$prefix = config('manager.table_prefix');
// The random key of a day. Yesterday's row is deleted: see VisitorSalt. // The random key of a day. Yesterday's row is deleted: see VisitorSalt.
Schema::create($prefix.'visitor_salts', function (Blueprint $table) { Schema::create(Names::table('visitor_salts'), function (Blueprint $table) {
$table->date('day')->primary(); $table->date('day')->primary();
$table->string('salt', 64); $table->string('salt', 64);
}); });
// One visit: the pages someone looks at with less than half an hour between them. // One visit: the pages someone looks at with less than half an hour between them.
Schema::create($prefix.'visits', function (Blueprint $table) { Schema::create(Names::table('visits'), function (Blueprint $table) {
$table->id(); $table->id();
$table->string('visitor_hash', 64); $table->string('visitor_hash', 64);
$table->dateTime('started_at'); $table->dateTime('started_at');
@@ -54,11 +54,11 @@ return new class extends Migration
$table->index(['visitor_hash', 'last_seen_at']); $table->index(['visitor_hash', 'last_seen_at']);
}); });
Schema::create($prefix.'page_views', function (Blueprint $table) use ($prefix) { Schema::create(Names::table('page_views'), function (Blueprint $table) {
$table->id(); $table->id();
// What the browser sends back when the visitor leaves the page, to report the time spent. // What the browser sends back when the visitor leaves the page, to report the time spent.
$table->string('token', 40)->unique(); $table->string('token', 40)->unique();
$table->foreignId('visit_id')->constrained($prefix.'visits')->cascadeOnDelete(); $table->foreignId('visit_id')->constrained(Names::table('visits'))->cascadeOnDelete();
$table->string('path'); $table->string('path');
// The post behind the page, when the posts module is on. No foreign key: posts may be off. // The post behind the page, when the posts module is on. No foreign key: posts may be off.
$table->unsignedBigInteger('post_id')->nullable(); $table->unsignedBigInteger('post_id')->nullable();
@@ -73,7 +73,7 @@ return new class extends Migration
// How often each program (search engine, AI crawler, link preview, ...) fetched each page, per // How often each program (search engine, AI crawler, link preview, ...) fetched each page, per
// day. A counter, not a log: no address, no browser line. // day. A counter, not a log: no address, no browser line.
Schema::create($prefix.'bot_hits', function (Blueprint $table) { Schema::create(Names::table('bot_hits'), function (Blueprint $table) {
$table->id(); $table->id();
$table->date('day'); $table->date('day');
$table->string('bot', 60); $table->string('bot', 60);
@@ -88,10 +88,9 @@ return new class extends Migration
public function down(): void public function down(): void
{ {
$prefix = config('manager.table_prefix');
foreach (['bot_hits', 'page_views', 'visits', 'visitor_salts'] as $table) { foreach (['bot_hits', 'page_views', 'visits', 'visitor_salts'] as $table) {
Schema::dropIfExists($prefix.$table); Schema::dropIfExists(Names::table($table));
} }
} }
}; };
+3 -2
View File
@@ -2,9 +2,10 @@
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Statistics\PulseController; use IriksIT\Manager\Modules\Statistics\PulseController;
use IriksIT\Manager\Support\Names;
// Visitors of the public site report a page view here. No session, no cookies. // Visitors of the public site report a page view here. No session, no cookies.
Route::prefix(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/'))->middleware('throttle:manager-pulse')->group(function () { Route::prefix(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/'))->middleware('throttle:manager-pulse')->group(function () {
Route::post('/view', [PulseController::class, 'view'])->name('manager.pulse.view'); Route::post('/view', [PulseController::class, 'view'])->name(Names::route('pulse.view'));
Route::post('/leave', [PulseController::class, 'leave'])->name('manager.pulse.leave'); Route::post('/leave', [PulseController::class, 'leave'])->name(Names::route('pulse.leave'));
}); });
+2 -1
View File
@@ -8,6 +8,7 @@ use Illuminate\Validation\Rule;
use IriksIT\Manager\Models\Group; use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Support\AuditTrail; use IriksIT\Manager\Support\AuditTrail;
use IriksIT\Manager\Support\ModuleRegistry; use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Support\Names;
/** The groups and what each allows. Only for a super admin (the `groups.manage` gate). */ /** The groups and what each allows. Only for a super admin (the `groups.manage` gate). */
class GroupController class GroupController
@@ -59,7 +60,7 @@ class GroupController
/** @return array{name: string, description: string|null, permissions: list<string>} */ /** @return array{name: string, description: string|null, permissions: list<string>} */
private function validated(Request $request, ?Group $group = null): array private function validated(Request $request, ?Group $group = null): array
{ {
$table = config('manager.table_prefix').'groups'; $table = Names::table('groups');
$request->validate([ $request->validate([
'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)], 'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)],
+3 -2
View File
@@ -3,6 +3,7 @@
namespace IriksIT\Manager\Modules\Users; namespace IriksIT\Manager\Modules\Users;
use IriksIT\Manager\Modules\BaseModule; use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permission; use IriksIT\Manager\Support\Permission;
class UsersModule extends BaseModule class UsersModule extends BaseModule
@@ -37,8 +38,8 @@ class UsersModule extends BaseModule
public function navigation(): array public function navigation(): array
{ {
return [ return [
['label' => 'Accounts', 'route' => 'manager.accounts.index', 'permission' => 'accounts.manage'], ['label' => 'Accounts', 'route' => Names::route('accounts.index'), 'permission' => 'accounts.manage'],
['label' => 'Groups', 'route' => 'manager.groups.index', 'permission' => 'groups.manage'], ['label' => 'Groups', 'route' => Names::route('groups.index'), 'permission' => 'groups.manage'],
]; ];
} }
@@ -3,12 +3,12 @@
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration return new class extends Migration
{ {
public function up(): void public function up(): void
{ {
$prefix = config('manager.table_prefix');
$users = (new (config('manager.user_model')))->getTable(); $users = (new (config('manager.user_model')))->getTable();
// New accounts are never super admins; an existing one is not promoted here. // New accounts are never super admins; an existing one is not promoted here.
@@ -17,7 +17,7 @@ return new class extends Migration
Schema::table($users, fn (Blueprint $table) => $table->boolean('is_super_admin')->default(false)); Schema::table($users, fn (Blueprint $table) => $table->boolean('is_super_admin')->default(false));
} }
Schema::create($prefix.'groups', function (Blueprint $table) { Schema::create(Names::table('groups'), function (Blueprint $table) {
$table->id(); $table->id();
$table->string('name')->unique(); $table->string('name')->unique();
$table->string('description', 500)->nullable(); $table->string('description', 500)->nullable();
@@ -25,8 +25,8 @@ return new class extends Migration
$table->timestamps(); $table->timestamps();
}); });
Schema::create($prefix.'group_user', function (Blueprint $table) use ($prefix, $users) { Schema::create(Names::table('group_user'), function (Blueprint $table) use ($users) {
$table->foreignId('group_id')->constrained($prefix.'groups')->cascadeOnDelete(); $table->foreignId('group_id')->constrained(Names::table('groups'))->cascadeOnDelete();
$table->foreignId('user_id')->constrained($users)->cascadeOnDelete(); $table->foreignId('user_id')->constrained($users)->cascadeOnDelete();
$table->primary(['group_id', 'user_id']); $table->primary(['group_id', 'user_id']);
}); });
@@ -34,11 +34,10 @@ return new class extends Migration
public function down(): void public function down(): void
{ {
$prefix = config('manager.table_prefix');
$users = (new (config('manager.user_model')))->getTable(); $users = (new (config('manager.user_model')))->getTable();
Schema::dropIfExists($prefix.'group_user'); Schema::dropIfExists(Names::table('group_user'));
Schema::dropIfExists($prefix.'groups'); Schema::dropIfExists(Names::table('groups'));
Schema::table($users, fn (Blueprint $table) => $table->dropColumn('is_super_admin')); Schema::table($users, fn (Blueprint $table) => $table->dropColumn('is_super_admin'));
} }
}; };
+125
View File
@@ -0,0 +1,125 @@
<?php
namespace IriksIT\Manager\Support;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use InvalidArgumentException;
use IriksIT\Manager\Models\Page;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Models\Review;
/**
* Copies the rows of a site's own table into a table of the package, so a site that already has posts,
* pages or reviews does not start empty. It only reads the source and never writes to it; running it again
* updates the rows it made before (they are found by the `key` columns), so it is safe to repeat.
*/
final class Importer
{
/**
* What can be imported: the model, the columns the package knows, which of those must have a value, and
* the columns that make a row "the same row" when the import runs again.
*
* @var array<string, array{model: class-string<Eloquent>, columns: list<string>, required: list<string>, key: list<string>}>
*/
public const TARGETS = [
'posts' => [
'model' => Post::class,
'columns' => ['title', 'slug', 'excerpt', 'body', 'cover_image', 'category', 'tags', 'is_featured', 'published_at'],
'required' => ['title', 'body'],
'key' => ['slug'],
],
'pages' => [
'model' => Page::class,
'columns' => ['slug', 'title', 'body', 'is_published'],
'required' => ['slug', 'title'],
'key' => ['slug'],
],
'reviews' => [
'model' => Review::class,
'columns' => ['author', 'place', 'rating', 'body', 'is_visible'],
'required' => ['author', 'body'],
'key' => ['author', 'body'],
],
];
/**
* @param array<string, string> $map package column => column of the source table; same name when left out
* @return array{created: int, updated: int, skipped: int, problems: list<string>}
*/
public function run(string $target, ConnectionInterface $source, string $table, array $map = [], bool $dry = false, ?int $limit = null): array
{
$spec = self::TARGETS[$target] ?? throw new InvalidArgumentException("Unknown target {$target}; use one of: ".implode(', ', array_keys(self::TARGETS)));
foreach (array_keys($map) as $column) {
if (! in_array($column, $spec['columns'], true)) {
throw new InvalidArgumentException("{$target} has no column {$column}; known: ".implode(', ', $spec['columns']));
}
}
$result = ['created' => 0, 'updated' => 0, 'skipped' => 0, 'problems' => []];
$query = $source->table($table);
$limit !== null && $query->limit($limit);
foreach ($query->get() as $number => $row) {
$row = (array) $row;
$values = [];
foreach ($spec['columns'] as $column) {
$from = $map[$column] ?? $column;
if (array_key_exists($from, $row)) {
$values[$column] = $this->convert($column, $row[$from]);
}
}
if ($target === 'posts' || $target === 'pages') {
$values['slug'] = ($values['slug'] ?? '') !== '' ? Str::slug((string) $values['slug']) : Str::slug((string) ($values['title'] ?? ''));
}
foreach ($spec['required'] as $column) {
if (! isset($values[$column]) || $values[$column] === '') {
$result['skipped']++;
$result['problems'][] = 'row '.($number + 1).": no value for {$column}";
continue 2;
}
}
$key = Arr::only($values, $spec['key']);
$model = $spec['model'];
$existing = $model::query()->where($key)->first();
$existing ? $result['updated']++ : $result['created']++;
if (! $dry) {
$existing ? $existing->update($values) : $model::query()->create($values);
}
}
return $result;
}
private function convert(string $column, mixed $value): mixed
{
return match ($column) {
'tags' => $this->tags($value),
'is_featured', 'is_published', 'is_visible' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
'rating' => $value === null || $value === '' ? null : max(1, min(5, (int) $value)),
'published_at' => $value === null || $value === '' ? null : $value,
default => is_string($value) ? trim($value) : $value,
};
}
/** @return list<string> */
private function tags(mixed $value): array
{
if (is_string($value)) {
$decoded = json_decode($value, true);
$value = is_array($decoded) ? $decoded : array_map('trim', explode(',', $value));
}
return array_values(array_filter(array_map(fn ($tag) => is_string($tag) ? trim($tag) : '', (array) $value), fn ($tag) => $tag !== ''));
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace IriksIT\Manager\Support;
/**
* The names the package gives to its routes and tables, so a site that already uses `manager.*`
* route names or `manager_*` tables can move them out of the way (config `route_name`,
* `table_prefix`, `tables`). The defaults are the names of every earlier version.
*/
final class Names
{
/** The full name of a package route, e.g. `posts.index` becomes `manager.posts.index`. */
public static function route(string $name): string
{
return self::routePrefix().$name;
}
/** The prefix of every route name, with its closing dot: `manager.` unless the site changed it. */
public static function routePrefix(): string
{
$prefix = trim((string) config('manager.route_name', 'manager'), '.');
return $prefix === '' ? '' : $prefix.'.';
}
/** The table for a package table such as `posts`: a name set in `tables`, else prefix + name. */
public static function table(string $name): string
{
$custom = config('manager.tables.'.$name);
return is_string($custom) && $custom !== '' ? $custom : config('manager.table_prefix').$name;
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ class Shell
'permissions' => $allowed, 'permissions' => $allowed,
'navigation' => $navigation, 'navigation' => $navigation,
'theme' => $key, 'theme' => $key,
'can_login' => Route::has('manager.login'), 'can_login' => Route::has(Names::route('login')),
], ],
]; ];
} }
+74
View File
@@ -0,0 +1,74 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Models\Review;
use IriksIT\Manager\Tests\ReviewsOnTestCase;
uses(ReviewsOnTestCase::class);
beforeEach(function () {
Schema::create('articles', function ($table) {
$table->id();
$table->string('headline')->nullable();
$table->string('url_name')->nullable();
$table->text('content')->nullable();
$table->string('labels')->nullable();
$table->string('published')->nullable();
});
DB::table('articles')->insert([
['headline' => 'First news', 'url_name' => null, 'content' => 'Hello', 'labels' => 'a, b', 'published' => '2026-01-02 10:00:00'],
['headline' => 'Draft', 'url_name' => 'my-draft', 'content' => 'Later', 'labels' => '["x"]', 'published' => null],
['headline' => 'No text', 'url_name' => 'no-text', 'content' => '', 'labels' => null, 'published' => null],
]);
$this->map = ['--map' => ['title=headline', 'slug=url_name', 'body=content', 'tags=labels', 'published_at=published']];
});
it('copies rows into the package and repeats without duplicating', function () {
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles'] + $this->map)
->expectsOutputToContain('2 created, 0 updated, 1 skipped')->assertSuccessful();
expect(Post::query()->count())->toBe(2)
->and(Post::query()->where('slug', 'first-news')->first()->tags)->toBe(['a', 'b'])
->and(Post::query()->where('slug', 'my-draft')->first()->tags)->toBe(['x'])
->and(Post::query()->where('slug', 'my-draft')->first()->published_at)->toBeNull();
DB::table('articles')->where('url_name', 'my-draft')->update(['content' => 'Changed']);
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles'] + $this->map)
->expectsOutputToContain('0 created, 2 updated, 1 skipped');
expect(Post::query()->count())->toBe(2)
->and(Post::query()->where('slug', 'my-draft')->value('body'))->toBe('Changed');
});
it('writes nothing on a dry run and never touches the source', function () {
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles', '--dry-run' => true] + $this->map)
->expectsOutputToContain('Dry run: 2 created');
expect(Post::query()->count())->toBe(0)->and(DB::table('articles')->count())->toBe(3);
});
it('refuses what it does not know', function () {
$this->artisan('manager:import', ['target' => 'cars', '--table' => 'articles'])->assertFailed();
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles', '--map' => ['colour=x']])->assertFailed();
$this->artisan('manager:import', ['target' => 'posts'])->assertFailed();
});
it('reads its settings from the config and imports reviews', function () {
Schema::create('quotes', function ($table) {
$table->id();
$table->string('who');
$table->text('said');
$table->integer('stars')->nullable();
});
DB::table('quotes')->insert([['who' => 'A', 'said' => 'Fine', 'stars' => 9]]);
config(['manager.import.reviews' => ['table' => 'quotes', 'map' => ['author' => 'who', 'body' => 'said', 'rating' => 'stars']]]);
$this->artisan('manager:import', ['target' => 'reviews'])->assertSuccessful();
expect(Review::query()->first()->rating)->toBe(5);
});
+17
View File
@@ -0,0 +1,17 @@
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
it('keeps the names of every earlier version by default', function () {
expect(Names::route('posts.index'))->toBe('manager.posts.index')
->and(Names::table('posts'))->toBe('manager_posts')
->and(Route::has('manager.dashboard'))->toBeTrue()
->and(Route::has('manager.media.file'))->toBeTrue()
->and(Schema::hasTable('manager_posts'))->toBeTrue()
->and(Schema::hasTable('manager_media'))->toBeTrue();
});
+23
View File
@@ -0,0 +1,23 @@
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Tests\RenamedTestCase;
uses(RenamedTestCase::class);
it('moves routes, tables and the menu out of the way of the site', function () {
expect(Route::has('pkg-manager.dashboard'))->toBeTrue()
->and(Route::has('pkg-manager.posts.index'))->toBeTrue()
->and(Route::has('manager.dashboard'))->toBeFalse()
->and(Schema::hasTable('pkg_posts'))->toBeTrue()
->and(Schema::hasTable('site_files'))->toBeTrue()
->and(Schema::hasTable('manager_posts'))->toBeFalse()
->and(Schema::hasTable('pkg_media'))->toBeFalse();
$routes = collect(app(ModuleRegistry::class)->navigation())->pluck('route');
expect($routes)->not->toBeEmpty()
->and($routes->every(fn ($route) => str_starts_with($route, 'pkg-manager.')))->toBeTrue();
});
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace IriksIT\Manager\Tests;
/** A site that already has `manager.*` routes and `manager_*` tables of its own. */
abstract class RenamedTestCase extends TestCase
{
protected array $modules = ['reviews' => true];
protected function defineEnvironment($app): void
{
parent::defineEnvironment($app);
$app['config']->set('manager.route_name', 'pkg-manager');
$app['config']->set('manager.table_prefix', 'pkg_');
$app['config']->set('manager.tables', ['media' => 'site_files']);
}
}