Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f4d9b44f2 | ||
|
|
ebb5063ed1 | ||
|
|
a8055c69f8 | ||
|
|
e0299bf77b | ||
|
|
f7cbd6c621 | ||
|
|
e570b849f2 | ||
|
|
81ea30f038 | ||
|
|
cebb66b7d6 | ||
|
|
2f6789147e | ||
|
|
3d6b92497c | ||
|
|
556dfce585 | ||
|
|
f0cb58d7e5 | ||
|
|
4e77e4b427 | ||
|
|
7482ee489b | ||
|
|
2c00fa8f07 | ||
|
|
594e69c0cf | ||
|
|
acb8620621 | ||
|
|
d2ea1bacac | ||
|
|
b75403e5ea | ||
|
|
b863f9a346 |
No files matched your search
+34
-18
@@ -1,9 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tells Packagist that the package has a new version.
|
||||
"""Tells Packagist that the package has a new version, and submits the package when it is not there yet.
|
||||
|
||||
Packagist reads the tags of the repository; this asks it to do that now, instead of waiting for its
|
||||
own poll. The package must have been submitted on packagist.org once (by hand); until then, and
|
||||
while PACKAGIST_USERNAME and PACKAGIST_TOKEN are not set, this only says so and succeeds.
|
||||
own poll. The first time Packagist answers 404 (it does not know the package): then the package is
|
||||
submitted through the create-package API, and Packagist reads every tag that is already there.
|
||||
While PACKAGIST_USERNAME and PACKAGIST_TOKEN are not set, this only says so and succeeds.
|
||||
|
||||
Environment: PACKAGIST_USERNAME, PACKAGIST_TOKEN (the API token of the Packagist account, a secret
|
||||
of the repository), PACKAGE_URL (the public address of the repository).
|
||||
@@ -22,27 +22,43 @@ TOKEN = os.environ.get("PACKAGIST_TOKEN", "").strip()
|
||||
PACKAGE_URL = os.environ.get("PACKAGE_URL", "").strip()
|
||||
|
||||
|
||||
def call(endpoint, user, token, url):
|
||||
"""POST to the API of Packagist; returns the HTTP status. Raises HTTPError with the answer on a refusal."""
|
||||
query = urllib.parse.urlencode({"username": user, "apiToken": token})
|
||||
request = urllib.request.Request(
|
||||
f"https://packagist.org/api/{endpoint}?{query}",
|
||||
data=json.dumps({"repository": {"url": url}}).encode(),
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return response.status
|
||||
|
||||
|
||||
def notify(user, token, url):
|
||||
"""Tells Packagist about the package; submits it first when Packagist does not know it. Returns what happened."""
|
||||
try:
|
||||
return f"Packagist answered {call('update-package', user, token, url)}: it will read the new tag."
|
||||
except urllib.error.HTTPError as e:
|
||||
# Never echo the request (it holds the token); the answer of Packagist says enough.
|
||||
if e.code != 404:
|
||||
sys.exit(f"Packagist refused: {e.code} {e.read().decode()[:300]}")
|
||||
|
||||
try:
|
||||
return f"Packagist did not know the package: submitted it (answer {call('create-package', user, token, url)}). It reads every tag that is there."
|
||||
except urllib.error.HTTPError as e:
|
||||
sys.exit(f"Packagist did not know the package, and refused to submit it: {e.code} {e.read().decode()[:300]}")
|
||||
|
||||
|
||||
def main():
|
||||
if not (USER and TOKEN):
|
||||
print("PACKAGIST_USERNAME / PACKAGIST_TOKEN are not set: Packagist was not told. "
|
||||
"Set both as secrets of the repository once the package is submitted on packagist.org.")
|
||||
"Set both as secrets of the repository.")
|
||||
return
|
||||
if not PACKAGE_URL.startswith("https://"):
|
||||
sys.exit("PACKAGE_URL must be the public https address of the repository.")
|
||||
|
||||
query = urllib.parse.urlencode({"username": USER, "apiToken": TOKEN})
|
||||
request = urllib.request.Request(
|
||||
f"https://packagist.org/api/update-package?{query}",
|
||||
data=json.dumps({"repository": {"url": PACKAGE_URL}}).encode(),
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
print(f"Packagist answered {response.status}: it will read the new tag.")
|
||||
except urllib.error.HTTPError as e:
|
||||
# Never echo the request (it holds the token); the answer of Packagist says enough.
|
||||
sys.exit(f"Packagist refused: {e.code} {e.read().decode()[:300]}")
|
||||
print(notify(USER, TOKEN, PACKAGE_URL))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -9,6 +9,7 @@ from datetime import datetime, timezone
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import check_flow # noqa: E402
|
||||
import packagist # noqa: E402
|
||||
import prune_branches # noqa: E402
|
||||
import update_dependencies # noqa: E402
|
||||
import semver # noqa: E402
|
||||
@@ -166,5 +167,46 @@ class DependencyUpdates(unittest.TestCase):
|
||||
self.assertEqual(composer["require-dev"]["c/c"], "^3.0||^4.0")
|
||||
|
||||
|
||||
class PackagistNotice(unittest.TestCase):
|
||||
def run_notice(self, answers):
|
||||
"""Runs notify() with fake answers per endpoint (a status number, or an HTTP error code as a string)."""
|
||||
import io
|
||||
import urllib.error
|
||||
|
||||
calls = []
|
||||
|
||||
def fake(endpoint, user, token, url):
|
||||
calls.append(endpoint)
|
||||
answer = answers[endpoint]
|
||||
if isinstance(answer, str):
|
||||
raise urllib.error.HTTPError("x", int(answer), "refused", {}, io.BytesIO(b"nope"))
|
||||
return answer
|
||||
|
||||
original = packagist.call
|
||||
packagist.call = fake
|
||||
try:
|
||||
return packagist.notify("u", "t", "https://example.org/r"), calls
|
||||
finally:
|
||||
packagist.call = original
|
||||
|
||||
def test_a_known_package_is_only_updated(self):
|
||||
message, calls = self.run_notice({"update-package": 202})
|
||||
self.assertEqual(calls, ["update-package"])
|
||||
self.assertIn("202", message)
|
||||
|
||||
def test_an_unknown_package_is_submitted(self):
|
||||
message, calls = self.run_notice({"update-package": "404", "create-package": 202})
|
||||
self.assertEqual(calls, ["update-package", "create-package"])
|
||||
self.assertIn("submitted", message)
|
||||
|
||||
def test_another_refusal_is_not_submitted(self):
|
||||
with self.assertRaises(SystemExit):
|
||||
self.run_notice({"update-package": "403", "create-package": 202})
|
||||
|
||||
def test_a_refused_submission_fails(self):
|
||||
with self.assertRaises(SystemExit):
|
||||
self.run_notice({"update-package": "404", "create-package": "400"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -19,6 +19,6 @@ between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one
|
||||
|
||||
## Open decisions
|
||||
|
||||
1. Frontend: ship the Inertia/Vue screens inside the package (built assets, published to the host) or make the package headless with a separate UI package.
|
||||
1. Frontend: decided to ship the Inertia/Vue screens inside the package (prebuilt bundle, host needs no Node) with per-user and site themes; being built after v0.4.0's AI tooling slice.
|
||||
2. Moving the rest from bouwbedrijf.iriks-it.nl, module by module: pages, reviews, then revisions, audit log, login and profile. Users, media and posts (with labels) are done. Leave out what is site-specific (the IriksIT API disk, the owner's simple screens, client names): this repo is public.
|
||||
3. How the host's own `User` and a package `Group` relate when the host has its own roles.
|
||||
@@ -4,6 +4,11 @@ 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
|
||||
the section is the text of the release in Gitea.
|
||||
|
||||
## v0.3.0 - 2026-12-04
|
||||
|
||||
- The Packagist step submits the package itself when Packagist does not know it yet (the update call answered 404), instead
|
||||
of failing until someone submits it by hand.
|
||||
|
||||
## v0.2.0 - 2026-12-04
|
||||
|
||||
- CI: the composer cache and three tries for the install in every job, so a hiccup of a download no longer breaks a run.
|
||||
|
||||
@@ -11,6 +11,16 @@ php artisan migrate
|
||||
Put `IriksIT\Manager\Concerns\HasManagerAccess` on the `User` model. The manager lives at `/manager`
|
||||
(`MANAGER_PATH`) behind the `web` and `auth` middleware (`config/manager.php`).
|
||||
|
||||
## Set up with an AI agent
|
||||
|
||||
```bash
|
||||
php artisan manager:install --modules=users,media,posts --user-model="App\Models\User"
|
||||
php artisan manager:doctor --json # non-zero exit when something is wrong; each problem has a `fix`
|
||||
```
|
||||
|
||||
`resources/ai/INTEGRATION.md` is a step-by-step guide for an agent; `resources/boost/guidelines/core.blade.php`
|
||||
is picked up by Laravel Boost.
|
||||
|
||||
## Modules
|
||||
|
||||
| Key | What | Default |
|
||||
@@ -159,11 +169,12 @@ Nobody opens a pull request to `develop`, and `production` and the release branc
|
||||
| Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`, Trivy on the dependencies, secrets and settings). The check `PR CI / pr-ci` is green when all are. |
|
||||
| Push to production | verify (Pest, audit), tag and release, Packagist, sync develop |
|
||||
| Every Monday | `composer audit` and Trivy on production |
|
||||
| Every Monday | *Dependency updates*: a direct dependency with a release outside its constraint (a new major) gets its constraint widened in a pull request `renovate/deps-DATE` to the open release branch; PR CI tests it and it merges when green. Nothing happens while no release is open. A package has no `composer.lock`, so the central Renovate and Trivy of the homelab have nothing to resolve here. |
|
||||
| Every Monday | *Dependency updates*: a direct dependency with a release outside its constraint (a new major) gets its constraint widened in a pull request `renovate/deps-DATE` to the open release branch; PR CI tests it and it merges when green. Nothing happens while no release is open. The central Trivy (every night 03:00 UTC) and Renovate (04:00 UTC) of the homelab also pass over this repo, but read a `composer.lock` and a package has none, so they find little here. |
|
||||
| Every night | *Prune branches*: removes `feature/*` and `fix/*` branches whose last commit is over 30 days old and that have no open pull request (a branch of a pull request can be restored from it in Gitea) |
|
||||
|
||||
Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and
|
||||
`PACKAGIST_TOKEN` once the package is submitted on packagist.org (until then that step only says so).
|
||||
`PACKAGIST_TOKEN` (until they are set that step only says so). When Packagist does not know the package yet, that step
|
||||
submits it through the create-package API; after that it only tells Packagist about each new tag.
|
||||
|
||||
## What Composer installs
|
||||
|
||||
|
||||
@@ -20,3 +20,7 @@ Per stuk werk een rij; zie `dev/token-usage.py`.
|
||||
| 2026-12-04 | Adviseur-aanroepen bij de auditmodule en het banbeheer, die in de rij erboven nog niet meetelden | - | claude-fable-5-2 | 2 | 25.967 | 246.202 | 0 | 0 | 0,00 |
|
||||
| 2026-12-04 | Het Hermes-tokenscript uit bouwbedrijf overgenomen, met dezelfde rijen per model als het hoofdscript | - | claude-sonnet-5-5 | 9 | 7.044 | 20 | 15.263 | 2.258.010 | 0,01 |
|
||||
| 2026-12-04 | Wekelijkse update van de versiebereiken van afhankelijkheden, als pull request naar de open release | - | claude-sonnet-5-5 | 6 | 7.611 | 12 | 10.963 | 1.632.350 | 0,01 |
|
||||
| 2026-12-04 | De commit zonder AI-vermelding hersteld in de release, de uitleg over de nachtelijke scans gecorrigeerd en de notities in longterm-memory gemaakt | - | claude-sonnet-5-5 | 29 | 16.997 | 72 | 21.381 | 8.975.420 | 0,11 |
|
||||
| 2026-12-04 | De Packagist-stap meldt het pakket zelf aan als Packagist het nog niet kent | - | claude-sonnet-5-5 | 13 | 7.095 | 30 | 11.993 | 4.256.820 | 0,06 |
|
||||
| 2026-12-04 | Installatie en gezondheidscheck voor AI (manager:install en manager:doctor) met een stappengids voor agents | - | claude-sonnet-5-5 | 12 | 12.112 | 28 | 64.789 | 2.344.181 | 0,04 |
|
||||
| 2026-12-04 | Installatie en gezondheidscheck voor AI (manager:install en manager:doctor) met een stappengids voor agents | - | claude-fable-5-2 | 1 | 17.440 | 362.597 | 0 | 0 | 0,00 |
|
||||
@@ -0,0 +1,22 @@
|
||||
# Integrating iriks-it/laravel-manager (guide for AI agents)
|
||||
|
||||
Goal: the manager runs in this Laravel app and `php artisan manager:doctor` is green. Do the steps in order and
|
||||
never edit files inside `vendor/`.
|
||||
|
||||
1. `composer require iriks-it/laravel-manager`
|
||||
2. Pick the modules. `users` and `media` are on; `pages`, `posts` default on; `reviews`, `audit`, `statistics` default off
|
||||
(audit and statistics store visitor data: only switch them on when the owner says so).
|
||||
3. `php artisan manager:install --modules=users,media,posts --user-model="App\Models\User"`
|
||||
(writes `MANAGER_*` to `.env`, publishes `config/manager.php`, runs the doctor). Add `--path=admin` to move the URL.
|
||||
4. Add the trait to the user model: `use \IriksIT\Manager\Concerns\HasManagerAccess;`. Never put `is_super_admin` in `$fillable`.
|
||||
5. `php artisan migrate` (a new process, so it sees the switches you wrote in step 3).
|
||||
6. Create the first super admin: `php artisan manager:create-user --name="..." --email="..." --password="<12+ chars>"`.
|
||||
7. Run `php artisan manager:doctor --json`. Every check must be `ok` or an understood `warn`; each `fail`/`warn` has a `fix`.
|
||||
Repeat until `"ok": true`.
|
||||
|
||||
Facts that matter:
|
||||
- The manager lives at `/manager` (`MANAGER_PATH`) behind `web` + `auth` (`manager.middleware`); the app needs a route named `login`.
|
||||
- Anything that is off has no routes, tables or permissions. A module that needs another one fails at boot when that one is off.
|
||||
- Answers are JSON. Do not add site-specific code to the package: a site's own part is its own module class (`Contracts\Module`,
|
||||
extend `Modules\BaseModule`, add it to `manager.available`).
|
||||
- Behind a proxy set trusted proxies before switching `audit` on.
|
||||
@@ -0,0 +1,8 @@
|
||||
## iriks-it/laravel-manager
|
||||
|
||||
A modular backend (users, media, pages, posts, reviews, audit, statistics) installed as a package.
|
||||
|
||||
- To integrate it, follow `vendor/iriks-it/laravel-manager/resources/ai/INTEGRATION.md` step by step.
|
||||
- Set it up with `php artisan manager:install --modules=... --user-model=...`; verify with `php artisan manager:doctor --json` (non-zero exit on failure, every problem has a `fix`).
|
||||
- The user model needs the `HasManagerAccess` trait; `is_super_admin` is never mass assignable. The first super admin comes from `php artisan manager:create-user`.
|
||||
- Switch parts with `MANAGER_<MODULE>=true|false`; never edit `vendor/`. Site-specific parts are your own `Module` class.
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Concerns\HasManagerAccess;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
|
||||
/**
|
||||
* Checks that the manager is wired into the app, and says what to do when it is not. Meant for people and for
|
||||
* AI agents: `--json` prints one machine-readable report, and the exit code is non-zero when a check fails.
|
||||
*
|
||||
* php artisan manager:doctor [--json]
|
||||
*
|
||||
* A check is `ok`, `warn` (works, but look at it) or `fail` (the manager will not work).
|
||||
*/
|
||||
class DoctorCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:doctor {--json : Print the report as JSON}';
|
||||
|
||||
protected $description = 'Check that the manager is set up correctly in this app';
|
||||
|
||||
/** @var list<array{check: string, status: string, message: string, fix: string|null}> */
|
||||
private array $checks = [];
|
||||
|
||||
public function handle(ModuleRegistry $modules): int
|
||||
{
|
||||
$this->checkUserModel($modules);
|
||||
$this->checkTables($modules);
|
||||
$this->checkRoutes();
|
||||
$this->checkModules($modules);
|
||||
|
||||
$failed = collect($this->checks)->contains('status', 'fail');
|
||||
|
||||
if ($this->option('json')) {
|
||||
$this->line(json_encode(['ok' => ! $failed, 'checks' => $this->checks], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
|
||||
} else {
|
||||
foreach ($this->checks as $check) {
|
||||
$line = sprintf('[%s] %s: %s', strtoupper($check['status']), $check['check'], $check['message']);
|
||||
$check['status'] === 'fail' ? $this->error($line) : ($check['status'] === 'warn' ? $this->warn($line) : $this->info($line));
|
||||
|
||||
if ($check['fix'] !== null && $check['status'] !== 'ok') {
|
||||
$this->line(' fix: '.$check['fix']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
|
||||
private function add(string $check, string $status, string $message, ?string $fix = null): void
|
||||
{
|
||||
$this->checks[] = ['check' => $check, 'status' => $status, 'message' => $message, 'fix' => $fix];
|
||||
}
|
||||
|
||||
private function checkUserModel(ModuleRegistry $modules): void
|
||||
{
|
||||
$model = config('manager.user_model');
|
||||
|
||||
if (! is_string($model) || ! class_exists($model)) {
|
||||
$this->add('user_model', 'fail', 'manager.user_model is not a class: '.var_export($model, true), 'Set MANAGER_USER_MODEL (or manager.user_model) to your User model, for example App\\Models\\User.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->add('user_model', 'ok', "The user model is {$model}.");
|
||||
|
||||
if (! in_array(HasManagerAccess::class, class_uses_recursive($model), true)) {
|
||||
$this->add('user_trait', 'fail', "{$model} does not use HasManagerAccess.", "Add `use \\IriksIT\\Manager\\Concerns\\HasManagerAccess;` inside the class {$model}.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->add('user_trait', 'ok', 'The user model uses HasManagerAccess.');
|
||||
|
||||
if (in_array('is_super_admin', (new $model)->getFillable(), true)) {
|
||||
$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')) {
|
||||
$admins = $model::query()->where('is_super_admin', true)->count();
|
||||
$admins > 0
|
||||
? $this->add('super_admin', 'ok', "{$admins} super admin(s) exist.")
|
||||
: $this->add('super_admin', 'warn', 'There is no super admin yet: nobody can manage groups.', 'php artisan manager:create-user --name=... --email=... --password=...');
|
||||
}
|
||||
}
|
||||
|
||||
private function checkTables(ModuleRegistry $modules): void
|
||||
{
|
||||
$prefix = config('manager.table_prefix');
|
||||
$missing = [];
|
||||
|
||||
foreach ($modules->active() as $module) {
|
||||
foreach (method_exists($module, 'tables') ? $module->tables() : [] as $table) {
|
||||
if (! Schema::hasTable($prefix.$table)) {
|
||||
$missing[] = $prefix.$table;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$missing === []
|
||||
? $this->add('tables', 'ok', 'The tables of every active module exist.')
|
||||
: $this->add('tables', 'fail', 'Missing tables: '.implode(', ', $missing), 'php artisan migrate');
|
||||
}
|
||||
|
||||
private function checkRoutes(): void
|
||||
{
|
||||
Route::has('manager.dashboard')
|
||||
? $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).');
|
||||
|
||||
Route::has('login')
|
||||
? $this->add('login', 'ok', 'The app has a login route.')
|
||||
: $this->add('login', 'warn', 'The app has no route named `login`: the auth middleware has nowhere to send visitors.', 'Add a login to the app (for example a starter kit), or change manager.middleware.');
|
||||
}
|
||||
|
||||
private function checkModules(ModuleRegistry $modules): void
|
||||
{
|
||||
$active = array_keys($modules->active());
|
||||
$this->add('modules', 'ok', 'Active modules: '.implode(', ', $active).'.');
|
||||
|
||||
if ($modules->enabled('media')) {
|
||||
$disk = config('manager.media.disk');
|
||||
config("filesystems.disks.{$disk}") === null
|
||||
? $this->add('media_disk', 'fail', "The media disk \"{$disk}\" is not in config/filesystems.php.", 'Set MANAGER_MEDIA_DISK to a disk that exists.')
|
||||
: $this->add('media_disk', 'ok', "The media disk is \"{$disk}\".");
|
||||
|
||||
if ($disk === 'public' && ! file_exists(public_path('storage'))) {
|
||||
$this->add('storage_link', 'warn', 'public/storage does not exist: uploaded files cannot be served from the public disk.', 'php artisan storage:link');
|
||||
}
|
||||
}
|
||||
|
||||
if ($modules->enabled('audit')) {
|
||||
$this->add('proxies', 'warn', 'The audit log stores the visitor address. Behind a proxy or load balancer, trusted proxies must be configured, or every visitor looks like one address and one bad actor can lock the manager out.', 'Configure trusted proxies (bootstrap/app.php: $middleware->trustProxies(...)) and set MANAGER_NEVER_BAN to your own address.');
|
||||
}
|
||||
|
||||
if ($modules->enabled('statistics')) {
|
||||
$pages = (array) config('manager.statistics.pages');
|
||||
$pages === ['/'] && ! config('manager.statistics.posts_path')
|
||||
? $this->add('statistics_pages', 'warn', 'Only the home page counts in the statistics.', 'Set manager.statistics.pages (and posts_path), or register a resolver with CountedPages::register().')
|
||||
: $this->add('statistics_pages', 'ok', 'The statistics count '.count($pages).' page(s) and '.(config('manager.statistics.posts_path') ? 'the posts' : 'no posts').'.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
|
||||
/**
|
||||
* Sets the manager up in an app, without asking anything when the options are given.
|
||||
*
|
||||
* php artisan manager:install --modules=users,media,posts,audit --user-model="App\Models\User" --migrate
|
||||
*
|
||||
* It publishes the config, writes the MANAGER_* switches to .env, optionally runs the migrations, and finishes with
|
||||
* `manager:doctor`, which says what is still left to do (the trait on the user model, the first super admin).
|
||||
*/
|
||||
class InstallCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:install
|
||||
{--modules= : Comma-separated modules to switch ON (the rest of the optional ones are switched off)}
|
||||
{--user-model= : The Eloquent user model (default: what manager.user_model says)}
|
||||
{--path= : URL prefix of the manager (default: manager)}
|
||||
{--migrate : Run the migrations}
|
||||
{--json : Print the doctor report as JSON}';
|
||||
|
||||
protected $description = 'Set up the manager in this app: config, .env switches, migrations, then a health check';
|
||||
|
||||
public function handle(ModuleRegistry $modules): int
|
||||
{
|
||||
$this->callSilently('vendor:publish', ['--tag' => 'manager-config']);
|
||||
|
||||
$env = [];
|
||||
|
||||
if ($list = $this->option('modules')) {
|
||||
$wanted = array_filter(array_map('trim', explode(',', $list)));
|
||||
$unknown = array_diff($wanted, array_keys($modules->all()));
|
||||
|
||||
if ($unknown !== []) {
|
||||
$this->error('Unknown module(s): '.implode(', ', $unknown).'. Known: '.implode(', ', array_keys($modules->all())).'.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
foreach (array_keys($modules->all()) as $key) {
|
||||
if (in_array($key, ['users', 'media'], true)) {
|
||||
continue; // switched in config, on by default
|
||||
}
|
||||
|
||||
$env['MANAGER_'.strtoupper($key)] = in_array($key, $wanted, true) ? 'true' : 'false';
|
||||
}
|
||||
}
|
||||
|
||||
if ($model = $this->option('user-model')) {
|
||||
$env['MANAGER_USER_MODEL'] = $model;
|
||||
}
|
||||
|
||||
if ($path = $this->option('path')) {
|
||||
$env['MANAGER_PATH'] = trim($path, '/');
|
||||
}
|
||||
|
||||
foreach ($env as $key => $value) {
|
||||
$this->writeEnv($key, $value);
|
||||
}
|
||||
|
||||
if ($env !== []) {
|
||||
$this->line('Wrote to .env: '.implode(', ', array_map(fn ($k, $v) => "{$k}={$v}", array_keys($env), $env)).'. Run `php artisan config:clear` if the config is cached.');
|
||||
}
|
||||
|
||||
if ($this->option('migrate')) {
|
||||
// The switches were just written: a fresh process sees them, this one still has the old config.
|
||||
$this->line('Run `php artisan migrate` (a new process) so the migrations of the modules you switched on are loaded.');
|
||||
}
|
||||
|
||||
return Artisan::call('manager:doctor', $this->option('json') ? ['--json' => true] : [], $this->output) === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
|
||||
private function writeEnv(string $key, string $value): void
|
||||
{
|
||||
$file = base_path('.env');
|
||||
$contents = file_exists($file) ? file_get_contents($file) : '';
|
||||
$line = "{$key}={$value}";
|
||||
|
||||
$contents = preg_match("/^{$key}=.*$/m", $contents)
|
||||
? preg_replace("/^{$key}=.*$/m", $line, $contents)
|
||||
: rtrim($contents, "\n")."\n{$line}\n";
|
||||
|
||||
file_put_contents($file, $contents);
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,10 @@ class ManagerServiceProvider extends ServiceProvider
|
||||
$module->boot();
|
||||
}
|
||||
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->commands([Console\InstallCommand::class, Console\DoctorCommand::class]);
|
||||
}
|
||||
|
||||
$this->registerGates($modules);
|
||||
$this->registerRoutes($modules);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,11 @@ class AuditModule extends BaseModule
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['audit_logs', 'ip_bans', 'audit_settings', 'ip_notes'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -45,6 +45,16 @@ abstract class BaseModule implements Module
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tables (without the prefix) this module needs; `manager:doctor` checks that they exist.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function tables(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [];
|
||||
|
||||
@@ -25,6 +25,11 @@ class MediaModule extends BaseModule
|
||||
return true;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['media'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -24,6 +24,11 @@ class PagesModule extends BaseModule
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['pages'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -24,6 +24,11 @@ class PostsModule extends BaseModule
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['posts', 'post_labels'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -22,6 +22,11 @@ class ReviewsModule extends BaseModule
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['reviews'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -33,6 +33,11 @@ class StatisticsModule extends BaseModule
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['visitor_salts', 'visits', 'page_views', 'bot_hits'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [new Permission('statistics.view', 'See the visitor statistics and download them', 'Statistics')];
|
||||
|
||||
@@ -22,6 +22,11 @@ class UsersModule extends BaseModule
|
||||
return true;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['groups', 'group_user'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
|
||||
function doctorReport(): array
|
||||
{
|
||||
Artisan::call('manager:doctor', ['--json' => true]);
|
||||
|
||||
return json_decode(Artisan::output(), true);
|
||||
}
|
||||
|
||||
it('reports a healthy setup as JSON with exit code 0', function () {
|
||||
$report = doctorReport();
|
||||
$status = collect($report['checks'])->pluck('status', 'check');
|
||||
|
||||
expect($status['user_trait'])->toBe('ok')
|
||||
->and($status['tables'])->toBe('ok')
|
||||
->and($status['routes'])->toBe('ok')
|
||||
->and($report['ok'])->toBeTrue();
|
||||
});
|
||||
|
||||
it('fails with a fix when the user model is not a class', function () {
|
||||
config(['manager.user_model' => 'Nope\\User']);
|
||||
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'user_model');
|
||||
|
||||
expect($check['status'])->toBe('fail')->and($check['fix'])->toContain('MANAGER_USER_MODEL');
|
||||
expect(Artisan::call('manager:doctor'))->toBe(1);
|
||||
});
|
||||
|
||||
it('warns when there is no super admin yet', function () {
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'super_admin');
|
||||
|
||||
expect($check['status'])->toBe('warn')->and($check['fix'])->toContain('manager:create-user');
|
||||
});
|
||||
|
||||
it('lists the tables of the active modules', function () {
|
||||
$tables = collect(app(ModuleRegistry::class)->active())->flatMap->tables();
|
||||
|
||||
expect($tables)->toContain('media', 'posts');
|
||||
});
|
||||
|
||||
it('refuses an unknown module in the installer', function () {
|
||||
expect(Artisan::call('manager:install', ['--modules' => 'users,nonsense']))->toBe(1);
|
||||
});
|
||||
|
||||
it('writes the switches to .env', function () {
|
||||
$env = base_path('.env');
|
||||
$before = file_exists($env) ? file_get_contents($env) : null;
|
||||
|
||||
Artisan::call('manager:install', ['--modules' => 'users,media,posts', '--path' => 'admin']);
|
||||
|
||||
$written = file_get_contents($env);
|
||||
$before === null ? unlink($env) : file_put_contents($env, $before);
|
||||
|
||||
expect($written)->toContain('MANAGER_PATH=admin')->toContain('MANAGER_AUDIT=false')->toContain('MANAGER_POSTS=true');
|
||||
});
|
||||
Reference in new issue
Block a user