diff --git a/.ci/coverage/admin b/.ci/coverage/admin index 620c7091..e46029e7 100644 --- a/.ci/coverage/admin +++ b/.ci/coverage/admin @@ -1 +1 @@ -99.88% of lines, 7 not covered +100.00% of lines, 0 not covered diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c22d859..e35a2296 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,11 @@ All notable changes are listed here. The format follows [Keep a Changelog](https - The demo article's page is drawn by the theme; the app's own article controller, its view and Laravel's welcome page are gone. ### Fixed +- `atrium:install`, `atrium:module:install` and `atrium:module:remove` printed DONE next to a step that failed (publishing, migrating, linking, dropping tables); they print FAIL now. +- Saving the SEO tab of a record twice failed with a unique-constraint error in an application that maps the model to a morph alias (`Relation::morphMap()`); it updates the one SEO record now. +- The API list answered 500 to `?search[]=x` and `?sort[]=name` (a list instead of text); both are ignored now, like any other value the list cannot use. +- An SEO template naming a related record (`{parent}`) printed all of that record's columns as JSON into the page title or description; it gives the record's name now, and a list (`{files}`) leaves its placeholder. +- A very wide, very low image (a banner strip 4000 px wide and 1 px high) made `WebpCopy` stop with an error while scaling it down: its height rounded to zero. It keeps one pixel. - The Bitrix migrator, found by tests of every branch: `atrium:bitrix:parity` now reports a widget of the wrong type (`TYPE_MISMATCH`; it never did) and no longer stops on a model with array fields or one that throws; `--iblock=2` and `--hlblock=1` on `generate:migrations`, `generate:models`, `migrate:data`, `verify` and `migrate` no longer end in a TypeError; a command run twice in one process (a queue worker, a test) no longer keeps the counts, connection and cache of the first run; `verify` says how many records it compared instead of the sample size and reports a section lost in the new database; `generate:migrations` finds a migration of the same table written by an earlier run under another number; a property or field with unreadable settings no longer stops the analysis; a column named after a Cyrillic property in capitals (`ЦЕНА`) is `tsena`, not `ts_e_n_a`; a multiple directory property is no longer in `$fillable` under its relation name; the `parent()` relation of a generated reference model returns `BelongsTo` instead of a class that does not exist; a file whose name starts with `total` is no longer left out of a plain FTP listing; the summary of `migrate` names the folders the files were really written to. Removed with no caller: `PropertyAnalyzer`, `IBlockElement`, `BitrixConnection::getIBlockTypes()`, `getIBlockEnumValues()`, `getElementSections()`, `getFiles()`, `getElementSeo()` and `getSectionSeo()` (the last two asked for columns Bitrix does not have), `IBlockAnalyzer::analyzeByCode()`, `getLinkedIBlockIds()`, `hasComplexRelations()`, `HighloadBlockAnalyzer::getLinkedHlblockIds()`, `findDirectoryHlblock()`, `hasComplexRelations()`, `FieldTypeMapper::getColumnClassName()` `BitrixListLayout::empty()`, `PropertyTypeMapper::shouldIndex()`, `NamingConvention::toMigrationFileName()` and `toMigrationClassName()`, `SectionMigrationGenerator::getFilename()` and the write/filename helpers of `MigrationGenerator`. - Saving a record in the panel or the API wrote the record, its relations, its SEO and what `afterAdminSave()` writes one by one, so a failure halfway left half of it saved; deleting was the same. A save, a delete and `reorderFiles()` run in one transaction now, tried again up to three times after a deadlock, and `atrium.record.saved` / `atrium.record.deleted` are heard only after the commit, so their listeners never mail about or queue a record that was rolled back. - `atrium:install` left an untracked Sanctum migration in every fresh clone: the skeleton carries it now, and on clones installed earlier it does nothing. diff --git a/packages/admin/src/Api/ApiDocumentation.php b/packages/admin/src/Api/ApiDocumentation.php index 20c475b9..3d5e72e3 100644 --- a/packages/admin/src/Api/ApiDocumentation.php +++ b/packages/admin/src/Api/ApiDocumentation.php @@ -48,32 +48,52 @@ public function modules(array $only = []): array continue; } - $fields = array_filter( - AdminController::fieldsOf($model), - static fn (Field $field): bool => $field->shouldShowOnCreate() || $field->shouldShowOnEdit() - ); - - $instance = new $model; - $translatable = Hook::apply( - 'atrium.module.translatable', - method_exists($instance, 'getTranslatableAttributes') ? $instance->getTranslatableAttributes() : [], - $model, - ); - - $modules[$key] = [ - 'label' => $this->resources->label($key), - 'fields' => array_values(array_map( - fn (Field $field): array => in_array($field->getName(), $translatable, true) - ? $this->translatable($this->describe($field)) - : $this->describe($field), - $fields - )), - ]; + $modules[$key] = $this->describeModule($key, $model); } return $modules; } + /** + * One module of the API by its key; the key must be one of the API's. + * + * @return array{label:string,fields:array>} + */ + public function module(string $key): array + { + return $this->describeModule($key, $this->resources->all()[$key]); + } + + /** + * @param class-string $model + * @return array{label:string,fields:array>} + */ + private function describeModule(string $key, string $model): array + { + $instance = new $model; + $translatable = Hook::apply( + 'atrium.module.translatable', + method_exists($instance, 'getTranslatableAttributes') ? $instance->getTranslatableAttributes() : [], + $model, + ); + + $fields = []; + + foreach (AdminController::fieldsOf($model) as $field) { + if (! $field->shouldShowOnCreate() && ! $field->shouldShowOnEdit()) { + continue; + } + + $doc = $this->describe($field); + $fields[] = in_array($field->getName(), $translatable, true) ? $this->translatable($doc) : $doc; + } + + return [ + 'label' => $this->resources->label($key), + 'fields' => $fields, + ]; + } + /** * A field as an API client sees it: what JSON to send and what it means. * @@ -119,7 +139,7 @@ private function describe(Field $field): array 'repeatable' => $this->set($doc, ['type' => 'array', 'items' => $this->repeatableItem($props['itemType'] ?? 'text')], $this->repeatableNote($props['itemType'] ?? 'text')), 'select' => $this->optionsSchema($doc, $props['options'] ?? [], false), 'multiSelect' => $this->optionsSchema($doc, $props['options'] ?? [], true), - 'treeSelect' => $this->relationSchema($doc, $this->flattenTree($props['options'] ?? []), (bool) ($props['multiple'] ?? false), $props['modelClass'] ?? null), + 'treeSelect' => $this->relationSchema($doc, $this->flattenTree($props['options'] ?? []), $props['multiple'], $props['modelClass'] ?? null), 'belongsTo' => $this->relationSchema($doc, $props['options'] ?? [], false, $props['modelClass'] ?? null), 'belongsToMany' => $this->relationSchema($doc, $props['options'] ?? [], true, $props['model'] ?? null), default => $doc, @@ -149,10 +169,9 @@ private function translatable(array $doc): array $properties[$code] = $doc['schema']; } - $doc['schema'] = ['oneOf' => [$doc['schema'], ['type' => 'object', 'properties' => $properties, 'additionalProperties' => false]]]; - $doc['note'] = trim(($doc['note'] ?? '').' Translatable: a plain value sets the default language ('.$languages->default().'), an object {"'.implode('": …, "', $languages->codes()).'": …} sets several. Read back as that object.'); + $schema = ['oneOf' => [$doc['schema'], ['type' => 'object', 'properties' => $properties, 'additionalProperties' => false]]]; - return $doc; + return $this->set($doc, $schema, 'Translatable: a plain value sets the default language ('.$languages->default().'), an object {"'.implode('": …, "', $languages->codes()).'": …} sets several. Read back as that object.'); } /** @@ -245,14 +264,14 @@ private function relationSchema(array $doc, array $options, bool $multiple, ?str * A section tree as a flat list with the full path in the label: * "Europe / Day trips", otherwise sections with the same name are indistinguishable. * - * @return array + * @return array */ private function flattenTree(array $nodes, string $prefix = ''): array { $flat = []; foreach ($nodes as $node) { - $label = $prefix === '' ? (string) $node['label'] : $prefix.' / '.$node['label']; + $label = $prefix === '' ? $node['label'] : $prefix.' / '.$node['label']; $flat[] = ['value' => $node['value'], 'label' => $label]; if (! empty($node['children'])) { @@ -520,7 +539,7 @@ private function siteName(): string private function typeName(array $schema): string { - if (isset($schema['oneOf'][0])) { + if (isset($schema['oneOf'])) { return $this->typeName($schema['oneOf'][0]).' per language'; } diff --git a/packages/admin/src/AtriumServiceProvider.php b/packages/admin/src/AtriumServiceProvider.php index 822afb1a..5da5a538 100644 --- a/packages/admin/src/AtriumServiceProvider.php +++ b/packages/admin/src/AtriumServiceProvider.php @@ -247,7 +247,7 @@ private function registerRoutes(): void if (is_file($custom)) { $this->app['router'] ->prefix(config('atrium.prefix', 'admin')) - ->middleware([...config('atrium.middleware', ['web']), 'atrium.inertia', 'admin.auth', 'admin.can']) + ->middleware([...config()->array('atrium.middleware'), 'atrium.inertia', 'admin.auth', 'admin.can']) ->group($custom); } } diff --git a/packages/admin/src/Auth/Permissions.php b/packages/admin/src/Auth/Permissions.php index 936a9a0a..c0684bd8 100644 --- a/packages/admin/src/Auth/Permissions.php +++ b/packages/admin/src/Auth/Permissions.php @@ -96,7 +96,7 @@ public function sections(): array } foreach ($module->declaredPermissions as $name => $permission) { - [$section, $action] = explode('.', $name, 2); + [$section, $action] = explode('.', $name); $sections[$section] ??= ['key' => $section, 'label' => $section === $key ? $module->label() : Str::headline($section), 'actions' => []]; if (! in_array($action, $sections[$section]['actions'], true)) { @@ -104,13 +104,12 @@ public function sections(): array } if ($permission['label'] !== '') { - $sections[$section]['labels'][$action] = (string) __($permission['label']); + $line = __($permission['label']); + $sections[$section]['labels'][$action] = is_string($line) ? $line : $permission['label']; } } } - $sections = array_values($sections); - usort($sections, static fn (array $a, array $b): int => strnatcasecmp($a['label'], $b['label'])); $sections[] = ['key' => 'api-tokens', 'label' => __('atrium::menu.api_tokens'), 'actions' => ['use']]; diff --git a/packages/admin/src/Captcha/ImageCaptcha.php b/packages/admin/src/Captcha/ImageCaptcha.php index ff4e8cec..289a2e2c 100644 --- a/packages/admin/src/Captcha/ImageCaptcha.php +++ b/packages/admin/src/Captcha/ImageCaptcha.php @@ -33,14 +33,26 @@ final class ImageCaptcha implements CaptchaDriver private const HEIGHT = 50; - public function __construct(private readonly Encrypter $encrypter, private readonly Cache $cache) {} + /** The largest of the built-in fonts of GD: 9 by 15 pixels a sign. */ + private const FONT = 5; + + /** + * @param bool|null $gd Whether the picture can be drawn; null asks PHP whether GD is there. + * @param (\Closure(int,int):int)|null $random Where the numbers of the sum and of the drawing come from; null is random_int(). + */ + public function __construct( + private readonly Encrypter $encrypter, + private readonly Cache $cache, + private readonly ?bool $gd = null, + private readonly ?\Closure $random = null, + ) {} public function widget(): HtmlString { // A question is used up on the first answer: a kept page would give // every visitor the same one. app(RecordCache::class)->dontKeepPage(); - [$a, $b] = [random_int(1, 9), random_int(1, 9)]; + [$a, $b] = [$this->random(1, 9), $this->random(1, 9)]; $token = $this->encrypter->encrypt([ 'q' => "$a + $b", 'a' => $a + $b, @@ -49,7 +61,7 @@ public function widget(): HtmlString ]); $id = 'atrium-captcha-'.Str::random(6); - $question = extension_loaded('gd') + $question = $this->draws() ? ''.e(__('atrium::captcha.image')).'' : ''.e("$a + $b = ?").''; @@ -87,7 +99,12 @@ public function image(mixed $token): ?string { $question = $this->question($token); - return $question === null || ! extension_loaded('gd') ? null : $this->draw($question['q'].' = ?'); + return $question === null || ! $this->draws() ? null : $this->draw($question['q'].' = ?'); + } + + private function draws(): bool + { + return $this->gd ?? extension_loaded('gd'); } /** @@ -115,11 +132,11 @@ private function question(mixed $token): ?array private function draw(string $text): string { $image = imagecreatetruecolor(self::WIDTH, self::HEIGHT); - imagefill($image, 0, 0, $this->color($image, 225, 250)); + imagefilter($image, IMG_FILTER_COLORIZE, ...$this->rgb(225, 250)); for ($i = 0; $i < 6; $i++) { - imagesetthickness($image, random_int(1, 2)); - imageline($image, random_int(0, self::WIDTH), random_int(0, self::HEIGHT), random_int(0, self::WIDTH), random_int(0, self::HEIGHT), $this->color($image, 120, 190)); + imagesetthickness($image, $this->random(1, 2)); + imageline($image, $this->random(0, self::WIDTH), $this->random(0, self::HEIGHT), $this->random(0, self::WIDTH), $this->random(0, self::HEIGHT), $this->color($image, 120, 190)); } // Each sign drawn small with the built-in font, then enlarged, tilted @@ -134,20 +151,19 @@ private function draw(string $text): string } $glyph = imagecreatetruecolor(9, 15); + imagefilter($glyph, IMG_FILTER_NEGATE); $background = imagecolorallocate($glyph, 255, 255, 255); - imagefill($glyph, 0, 0, $background); - imagecolortransparent($glyph, $background); - imagestring($glyph, 5, 0, 0, $char, $this->color($glyph, 20, 90)); + imagestring($glyph, self::FONT, 0, 0, $char, $this->color($glyph, 20, 90)); - $glyph = imagerotate($glyph, random_int(-20, 20), $background); + $glyph = imagerotate($glyph, $this->random(-20, 20), $background); imagecolortransparent($glyph, $background); - $size = random_int(24, 30); - imagecopyresized($image, $glyph, $x, random_int(2, self::HEIGHT - $size - 2), 0, 0, (int) ($size * .6), $size, imagesx($glyph), imagesy($glyph)); - $x += (int) ($size * .6) + random_int(1, 4); + $size = $this->random(24, 30); + imagecopyresized($image, $glyph, $x, $this->random(2, self::HEIGHT - $size - 2), 0, 0, (int) ($size * .6), $size, imagesx($glyph), imagesy($glyph)); + $x += (int) ($size * .6) + $this->random(1, 4); } for ($i = 0; $i < 250; $i++) { - imagesetpixel($image, random_int(0, self::WIDTH - 1), random_int(0, self::HEIGHT - 1), $this->color($image, 60, 200)); + imagesetpixel($image, $this->random(0, self::WIDTH - 1), $this->random(0, self::HEIGHT - 1), $this->color($image, 60, 200)); } ob_start(); @@ -158,7 +174,20 @@ private function draw(string $text): string private function color(\GdImage $image, int $from, int $to): int { - return (int) imagecolorallocate($image, random_int($from, $to), random_int($from, $to), random_int($from, $to)); + return (int) imagecolorallocate($image, ...$this->rgb($from, $to)); + } + + /** + * @return array{int,int,int} + */ + private function rgb(int $from, int $to): array + { + return [$this->random($from, $to), $this->random($from, $to), $this->random($from, $to)]; + } + + private function random(int $min, int $max): int + { + return ($this->random ?? random_int(...))($min, $max); } private function ttl(): int diff --git a/packages/admin/src/Console/Commands/IndexMediaCommand.php b/packages/admin/src/Console/Commands/IndexMediaCommand.php index 358d0054..ac3bcf9d 100644 --- a/packages/admin/src/Console/Commands/IndexMediaCommand.php +++ b/packages/admin/src/Console/Commands/IndexMediaCommand.php @@ -37,7 +37,7 @@ class IndexMediaCommand extends Command public function handle(): int { - $dryRun = (bool) $this->option('dry-run'); + $dryRun = $this->option('dry-run'); $relative = trim((string) ($this->option('path') ?? ''), '/'); if ($relative === '') { @@ -61,7 +61,7 @@ public function handle(): int $added = 0; foreach ($files as $file) { - $url = $prefix.'/'.ltrim($file['relative'], '/'); + $url = $prefix.'/'.$file['relative']; if (isset($known[$url])) { continue; @@ -101,14 +101,10 @@ public function handle(): int */ private function storageFiles(): array { - $disk = (string) config('atrium.uploads.disk', 'public'); - $directory = (string) config('atrium.uploads.directory', 'uploads'); + $disk = config()->string('atrium.uploads.disk', 'public'); + $directory = config()->string('atrium.uploads.directory', 'uploads'); $storage = Storage::disk($disk); - if (! $storage->exists($directory)) { - return [[], '/storage']; - } - $files = []; foreach ($storage->allFiles($directory) as $path) { @@ -156,7 +152,7 @@ private function publicFiles(string $relative): array private function collection(): ?MediaCollection { - $name = (string) ($this->option('collection') ?? ''); + $name = $this->option('collection') ?? ''; return $name === '' ? null : MediaCollection::firstOrCreate(['name' => $name]); } diff --git a/packages/admin/src/Console/Commands/InstallCommand.php b/packages/admin/src/Console/Commands/InstallCommand.php index dbc04033..7b09a76f 100644 --- a/packages/admin/src/Console/Commands/InstallCommand.php +++ b/packages/admin/src/Console/Commands/InstallCommand.php @@ -9,6 +9,7 @@ namespace Atrium\Admin\Console\Commands; +use Atrium\Admin\Console\Concerns\ReportsSteps; use Atrium\Admin\Models\AdminUser; use Atrium\Admin\Modules\Modules; use Illuminate\Console\Command; @@ -18,6 +19,8 @@ */ final class InstallCommand extends Command { + use ReportsSteps; + protected $signature = 'atrium:install {--name= : Name of the first administrator} {--email= : Email of the first administrator} @@ -29,12 +32,12 @@ final class InstallCommand extends Command public function handle(): int { - $this->components->task('Publishing config', fn () => $this->callSilently('vendor:publish', ['--tag' => 'atrium-config']) === 0); - $this->components->task('Publishing assets', fn () => $this->callSilently('vendor:publish', ['--tag' => 'atrium-assets', '--force' => true]) === 0); + $this->step('Publishing config', fn (): bool => $this->callSilently('vendor:publish', ['--tag' => 'atrium-config']) === 0); + $this->step('Publishing assets', fn (): bool => $this->callSilently('vendor:publish', ['--tag' => 'atrium-assets', '--force' => true]) === 0); // API tokens need Sanctum's table; publishing is a no-op when it is already there. if (! glob(database_path('migrations/*_create_personal_access_tokens_table.php'))) { - $this->components->task('Publishing Sanctum migration', fn () => $this->callSilently('vendor:publish', ['--tag' => 'sanctum-migrations']) === 0); + $this->step('Publishing Sanctum migration', fn (): bool => $this->callSilently('vendor:publish', ['--tag' => 'sanctum-migrations']) === 0); } if ($this->option('demo')) { @@ -42,17 +45,16 @@ public function handle(): int } if (! $this->option('no-migrate')) { - $this->components->task('Running migrations', fn () => $this->callSilently('migrate', ['--force' => true]) === 0); + $this->step('Running migrations', fn (): bool => $this->callSilently('migrate', ['--force' => true]) === 0); if (! AdminUser::query()->exists()) { - $this->newLine(); $this->components->info('Create the first administrator.'); - $status = $this->call('atrium:user', array_filter([ + $status = $this->call('atrium:user', [ '--name' => $this->option('name'), '--email' => $this->option('email'), '--password' => $this->option('password'), - ])); + ]); if ($status !== self::SUCCESS) { return $status; @@ -71,12 +73,11 @@ public function handle(): int // Files uploaded in the admin go to storage/app/public and are served // through this link, demo or not. if (! is_link(public_path('storage')) && ! file_exists(public_path('storage'))) { - $this->components->task('Linking public/storage', fn () => $this->callSilently('storage:link') === 0); + $this->step('Linking public/storage', fn (): bool => $this->callSilently('storage:link') === 0); } $this->removeStockRobotsTxt(); - $this->newLine(); $this->components->info('Atrium is ready: '.url(config('atrium.prefix', 'admin'))); return self::SUCCESS; @@ -92,13 +93,11 @@ private function installModules(): void if ($modules->all() === []) { $this->components->warn('No module packages to fill: `composer require alveby/atrium-catalog alveby/atrium-brands alveby/atrium-stores alveby/atrium-news` and run this command again.'); - - return; } foreach ($modules->all() as $module) { if (! $modules->isInstalled($module->name)) { - $this->components->task("Installing {$module->name}", fn (): bool => $modules->install($module)); + $this->step("Installing {$module->name}", fn (): bool => $modules->install($module)); } } } @@ -114,7 +113,7 @@ private function seedDemo(): void foreach ($modules->dependencyOrder($modules->installed()) as $module) { if ($module->demo !== null) { - $this->components->task("Filling {$module->name}", function () use ($modules, $module, &$seeded): bool { + $this->step("Filling {$module->name}", function () use ($modules, $module, &$seeded): bool { $seeded = $modules->seedDemo($module) || $seeded; return true; @@ -143,7 +142,7 @@ private function removeStockRobotsTxt(): void $stock = preg_replace('/\s+/', ' ', trim((string) file_get_contents($file))) === 'User-agent: * Disallow:'; if ($stock) { - $this->components->task('Removing public/robots.txt (robots.txt is set in the admin now)', fn () => unlink($file)); + $this->step('Removing public/robots.txt (robots.txt is set in the admin now)', fn (): bool => unlink($file)); return; } diff --git a/packages/admin/src/Console/Commands/MakeModuleCommand.php b/packages/admin/src/Console/Commands/MakeModuleCommand.php index a9b20b2c..317aab0c 100644 --- a/packages/admin/src/Console/Commands/MakeModuleCommand.php +++ b/packages/admin/src/Console/Commands/MakeModuleCommand.php @@ -35,7 +35,10 @@ public function handle(Filesystem $files): int $namespace = trim($this->laravel->getNamespace(), '\\').'\\Models'; $fqcn = $namespace.'\\'.$class; $table = Str::snake(Str::pluralStudly($class)); - $label = (string) ($this->option('label') ?: Str::headline(Str::pluralStudly($class))); + $label = $this->option('label'); + if (! is_string($label) || $label === '') { + $label = Str::headline(Str::pluralStudly($class)); + } $modelPath = app_path("Models/{$class}.php"); @@ -46,7 +49,7 @@ public function handle(Filesystem $files): int } $files->ensureDirectoryExists(dirname($modelPath)); - $files->put($modelPath, $this->render('model', [ + $files->put($modelPath, $this->render($files, 'model', [ 'namespace' => $namespace, 'class' => $class, 'label' => addcslashes($label, "'\\"), @@ -56,7 +59,7 @@ public function handle(Filesystem $files): int if (! $this->option('no-migration')) { $migrationPath = database_path('migrations/'.date('Y_m_d_His')."_create_{$table}_table.php"); - $files->put($migrationPath, $this->render('migration', ['table' => $table])); + $files->put($migrationPath, $this->render($files, 'migration', ['table' => $table])); $this->components->info("Migration [{$migrationPath}] created."); } @@ -72,12 +75,12 @@ public function handle(Filesystem $files): int /** * @param array $replace */ - private function render(string $stub, array $replace): string + private function render(Filesystem $files, string $stub, array $replace): string { $custom = base_path("stubs/atrium/{$stub}.stub"); $path = is_file($custom) ? $custom : __DIR__."/../../../stubs/{$stub}.stub"; - $content = (string) file_get_contents($path); + $content = $files->get($path); foreach ($replace as $key => $value) { $content = str_replace('{{ '.$key.' }}', $value, $content); diff --git a/packages/admin/src/Console/Commands/ModuleCommand.php b/packages/admin/src/Console/Commands/ModuleCommand.php index 7576b888..68245ccb 100644 --- a/packages/admin/src/Console/Commands/ModuleCommand.php +++ b/packages/admin/src/Console/Commands/ModuleCommand.php @@ -9,6 +9,7 @@ namespace Atrium\Admin\Console\Commands; +use Atrium\Admin\Console\Concerns\ReportsSteps; use Atrium\Admin\Contracts\Administrable; use Atrium\Admin\Modules\Module; use Atrium\Admin\Modules\Modules; @@ -19,6 +20,8 @@ */ abstract class ModuleCommand extends Command { + use ReportsSteps; + protected function packageName(): string { return strtolower(trim((string) $this->argument('package'))); diff --git a/packages/admin/src/Console/Commands/ModuleInstallCommand.php b/packages/admin/src/Console/Commands/ModuleInstallCommand.php index f8616b81..3e00914e 100644 --- a/packages/admin/src/Console/Commands/ModuleInstallCommand.php +++ b/packages/admin/src/Console/Commands/ModuleInstallCommand.php @@ -60,7 +60,7 @@ public function handle(Modules $modules): int } if ($module->migrations !== []) { - $this->components->task('Running its migrations', fn (): bool => $this->callSilently('migrate', [ + $this->step('Running its migrations', fn (): bool => $this->callSilently('migrate', [ '--path' => $module->migrations, '--realpath' => true, '--force' => true, @@ -72,7 +72,9 @@ public function handle(Modules $modules): int } if ($this->option('demo') && $module->demo !== null) { - $this->components->task('Filling it with demo content', fn (): bool => $modules->seedDemo($module) || true); + $this->components->task('Filling it with demo content', function () use ($modules, $module): void { + $modules->seedDemo($module); + }); } $this->refreshCaches(); @@ -81,13 +83,13 @@ public function handle(Modules $modules): int foreach ($modules->childrenOf($module) as $child) { if (! $modules->isInstalled($child->name)) { - $this->call('atrium:module:install', ['package' => $child->name, '--demo' => (bool) $this->option('demo')]); + $this->call('atrium:module:install', ['package' => $child->name, '--demo' => $this->option('demo')]); } } $this->components->info($already ? "{$name} was installed already; its tables are up to date." - : "{$name} is installed. In the menu and the role form: ".implode(', ', $this->moduleKeys($module)).'.'); + : "{$name} is installed. In the menu and the role form: ".implode(', ', $this->moduleKeys($module))); return self::SUCCESS; } @@ -100,7 +102,7 @@ private function grantDeclaredPermissions(Module $module): void { $with = array_filter(array_map(static fn (array $permission): ?string => $permission['with'], $module->declaredPermissions)); - if ($with === [] || ! Schema::hasTable('admin_roles')) { + if (! Schema::hasTable('admin_roles')) { return; } diff --git a/packages/admin/src/Console/Commands/ModuleRemoveCommand.php b/packages/admin/src/Console/Commands/ModuleRemoveCommand.php index b6b117a1..ac67cb6a 100644 --- a/packages/admin/src/Console/Commands/ModuleRemoveCommand.php +++ b/packages/admin/src/Console/Commands/ModuleRemoveCommand.php @@ -60,7 +60,7 @@ public function handle(Modules $modules): int } if (! $keep && $module->migrations !== []) { - $this->components->task('Dropping its tables', fn (): bool => $this->callSilently('migrate:reset', [ + $this->step('Dropping its tables', fn (): bool => $this->callSilently('migrate:reset', [ '--path' => $module->migrations, '--realpath' => true, '--force' => true, diff --git a/packages/admin/src/Console/Commands/SlugRegenerateCommand.php b/packages/admin/src/Console/Commands/SlugRegenerateCommand.php index 9c7dc30f..6dbb2d19 100644 --- a/packages/admin/src/Console/Commands/SlugRegenerateCommand.php +++ b/packages/admin/src/Console/Commands/SlugRegenerateCommand.php @@ -147,7 +147,7 @@ protected function findModelsWithSlug(): array $modelsPath = app_path('Models'); if (! File::isDirectory($modelsPath)) { - return $models; + return []; } $files = File::allFiles($modelsPath); @@ -155,7 +155,7 @@ protected function findModelsWithSlug(): array foreach ($files as $file) { $relativePath = str_replace( [$modelsPath.DIRECTORY_SEPARATOR, '.php'], - ['', ''], + '', $file->getPathname() ); diff --git a/packages/admin/src/Console/Concerns/ReportsSteps.php b/packages/admin/src/Console/Concerns/ReportsSteps.php new file mode 100644 index 00000000..f1a4ab71 --- /dev/null +++ b/packages/admin/src/Console/Concerns/ReportsSteps.php @@ -0,0 +1,28 @@ +components->task($title, fn (): int => $step() ? TaskResult::Success->value : TaskResult::Failure->value); + } +} diff --git a/packages/admin/src/Dashboard/Gadgets/SiteSpeedGadget.php b/packages/admin/src/Dashboard/Gadgets/SiteSpeedGadget.php index 6ae519b3..162e9123 100644 --- a/packages/admin/src/Dashboard/Gadgets/SiteSpeedGadget.php +++ b/packages/admin/src/Dashboard/Gadgets/SiteSpeedGadget.php @@ -24,8 +24,8 @@ */ final class SiteSpeedGadget extends Gadget { - /** Top of the ruler, ms. From the gadget: siteIndexPercent = p50 / 2500 * 100. */ - private const SCALE_MS = 2500; + /** Top of the ruler, s. From the gadget: siteIndexPercent = p50 / 2500 * 100, in ms. */ + private const SCALE_SECONDS = 2.5; /** Band thresholds, ms => label key. From intervals[] in the gadget's index.php. */ private const BANDS = [ @@ -70,14 +70,14 @@ public function data(): array 'samples' => $this->stats->samples(), 'windowDays' => $this->stats->windowDays(), 'bands' => array_map(self::bandLabel(...), array_values(self::BANDS)), - 'scaleSeconds' => number_format(self::SCALE_MS / 1000, 1, ',', ' '), + 'scaleSeconds' => number_format(self::SCALE_SECONDS, 1, ',', ' '), ]; } /** Pointer position, %. Bitrix clamped it to 4…98 so it does not slide off the edges. */ private function pointerPercent(int $ms): float { - return round(min(max($ms / self::SCALE_MS * 100, 4), 98), 2); + return min(max($ms * 100 / (self::SCALE_SECONDS * 1000), 4), 98); } private function band(int $ms): string diff --git a/packages/admin/src/Dashboard/PageSpeedStats.php b/packages/admin/src/Dashboard/PageSpeedStats.php index de3689fe..1cc7b721 100644 --- a/packages/admin/src/Dashboard/PageSpeedStats.php +++ b/packages/admin/src/Dashboard/PageSpeedStats.php @@ -106,20 +106,20 @@ private function compute(): array $totals = PageTiming::where('created_at', '>=', $since) ->selectRaw('COUNT(*) AS samples, SUM(duration_ms) AS total_ms') - ->first(); + ->toBase() + ->sole(); - $samples = (int) ($totals->samples ?? 0); + $samples = (int) $totals->samples; if ($samples === 0) { return ['samples' => 0, 'median_ms' => null, 'average_ms' => null, 'rate' => null, 'slowest' => []]; } - $totalMs = (float) ($totals->total_ms ?? 0); + $totalMs = (float) $totals->total_ms; $median = PageTiming::where('created_at', '>=', $since) ->orderBy('duration_ms') ->skip(intdiv($samples, 2)) - ->take(1) ->value('duration_ms'); $slowest = PageTiming::where('created_at', '>=', $since) @@ -130,7 +130,7 @@ private function compute(): array ->toBase() ->get() ->map(fn (object $row): array => [ - 'path' => (string) $row->path, + 'path' => $row->path, 'ms' => (int) round((float) $row->avg_ms), 'hits' => (int) $row->hits, ]) @@ -138,7 +138,7 @@ private function compute(): array return [ 'samples' => $samples, - 'median_ms' => $median === null ? null : (int) $median, + 'median_ms' => $median, 'average_ms' => $totalMs / $samples, 'rate' => $totalMs > 0 ? $samples / ($totalMs / 1000) : null, 'slowest' => $slowest, diff --git a/packages/admin/src/Fields/TreeSelectField.php b/packages/admin/src/Fields/TreeSelectField.php index dea89a70..e7e75013 100644 --- a/packages/admin/src/Fields/TreeSelectField.php +++ b/packages/admin/src/Fields/TreeSelectField.php @@ -262,21 +262,21 @@ protected function notItsOwnAncestorRule(?FieldContext $context): ?\Closure $parentColumn = $this->parentColumn; return function (string $attribute, $value, \Closure $fail) use ($record, $modelClass, $parentColumn): void { - if (! $value) { + if (! $value || ! is_scalar($value)) { return; } - $rows = $modelClass::query()->pluck($parentColumn, 'id'); - $cursor = (int) $value; + $parents = $modelClass::query()->pluck($parentColumn, 'id')->all(); - for ($depth = 0; $cursor && $depth <= $rows->count(); $depth++) { - if ($cursor === (int) $record->getKey()) { - $fail(__('atrium::fields.validation.own_ancestor')); - - return; - } + // The chosen section and every section above it; one already in + // the chain ends the walk, so a cycle in the data cannot hang it. + $chain = []; + for ($id = $value; array_key_exists($id, $parents) && ! in_array($id, $chain); $id = $parents[$id]) { + $chain[] = $id; + } - $cursor = (int) ($rows[$cursor] ?? 0); + if (in_array($record->getKey(), $chain)) { + $fail(__('atrium::fields.validation.own_ancestor')); } }; } diff --git a/packages/admin/src/Hooks/Hooks.php b/packages/admin/src/Hooks/Hooks.php index 40032016..a7b53f2b 100644 --- a/packages/admin/src/Hooks/Hooks.php +++ b/packages/admin/src/Hooks/Hooks.php @@ -30,9 +30,6 @@ final class Hooks /** @var array>> by name, then priority */ private array $filters = []; - /** @var array> the filters of a name in the order they run */ - private array $sorted = []; - public function __construct( private readonly Dispatcher $events, private readonly Container $container, @@ -67,7 +64,6 @@ public function fire(string $name, mixed ...$args): void public function filter(string $name, callable|string $callback, int $priority = 10): void { $this->filters[$name][$priority][] = $callback; - unset($this->sorted[$name]); } /** @@ -79,7 +75,7 @@ public function apply(string $name, mixed $value, mixed ...$args): mixed return $value; } - foreach ($this->sorted[$name] ??= $this->sort($name) as $callback) { + foreach ($this->sort($name) as $callback) { $value = (is_string($callback) && ! is_callable($callback) ? $this->container->make($callback) : $callback)($value, ...array_values($args)); } @@ -102,6 +98,6 @@ private function sort(string $name): array $byPriority = $this->filters[$name]; ksort($byPriority); - return array_merge(...array_values($byPriority)); + return array_merge(...$byPriority); } } diff --git a/packages/admin/src/Http/Controllers/AdminController.php b/packages/admin/src/Http/Controllers/AdminController.php index 3fcd88a0..20aa09e8 100644 --- a/packages/admin/src/Http/Controllers/AdminController.php +++ b/packages/admin/src/Http/Controllers/AdminController.php @@ -162,7 +162,7 @@ public function index(Request $request): Response // A column like `brand.name` shows a related record's attribute. if ($related !== []) { - $query->with(array_values(array_unique(array_map(static fn (string $name): string => Str::beforeLast($name, '.'), $related)))); + $query->with(array_map(static fn (string $name): string => Str::beforeLast($name, '.'), $related)); } // Apply search @@ -172,7 +172,7 @@ public function index(Request $request): Response // the filter matched nothing — search silently returned every row. $searchable = collect($columns) ->map(fn ($col) => $col->toArray()) - ->filter(fn (array $col): bool => (bool) ($col['searchable'] ?? false)) + ->where('searchable', true) ->pluck('name') ->filter(fn ($name): bool => is_string($name) && $name !== '' && ! in_array($name, $related, true)) ->values() @@ -278,7 +278,7 @@ protected function listFilters(Request $request): array */ protected function preselectSection(Request $request, array $data): array { - $sectionId = (int) $request->query(self::SECTION_QUERY, 0); + $sectionId = (int) $request->query(self::SECTION_QUERY); if ($sectionId <= 0 || ! $this->sectionExists($sectionId)) { return $data; @@ -319,10 +319,6 @@ protected function prefillFromActions(Request $request, array $data): array */ private function withFieldDefaults(array $data, array $defaults): array { - if ($defaults === []) { - return $data; - } - $preset = static function (array $field) use ($defaults): array { if (array_key_exists($field['name'] ?? '', $defaults)) { $field['default'] = $defaults[$field['name']]; @@ -555,10 +551,6 @@ protected function validationAttributes(string $context): array */ protected function runValidation(Request $request, array $rules, string $context): void { - if (empty($rules)) { - return; - } - $request->validate($rules, [], $this->validationAttributes($context)); } @@ -592,7 +584,7 @@ protected function submittedData(Request $request, string $context, Model $item) } } - $data = $request->only(array_values(array_unique($keys))); + $data = $request->only($keys); // An untouched checkbox arrives as an empty string: the form seeds every // field as `default ?? ''`, and ConvertEmptyStringsToNull turns the @@ -694,10 +686,7 @@ public function edit(int $id): Response $item = $this->model::findOrFail($id); // Load BelongsToMany relations for proper data transformation - $belongsToManyRelations = $this->getBelongsToManyRelations(); - if (! empty($belongsToManyRelations)) { - $item->load($belongsToManyRelations); - } + $item->load($this->getBelongsToManyRelations()); $data = $this->prepareFormData('edit', $item); diff --git a/packages/admin/src/Http/Controllers/AdminUserController.php b/packages/admin/src/Http/Controllers/AdminUserController.php index 8281d9eb..6e0fe11b 100644 --- a/packages/admin/src/Http/Controllers/AdminUserController.php +++ b/packages/admin/src/Http/Controllers/AdminUserController.php @@ -52,7 +52,7 @@ public function destroy(int $id): RedirectResponse $this->guardTarget($item); - if ($item instanceof AdminUser && $item->isSuperadmin() && $this->isLastSuperadmin($item)) { + if ($item instanceof AdminUser && $this->isLastSuperadmin($item)) { return back()->with('error', __('atrium::permissions.last_superadmin')); } @@ -66,12 +66,12 @@ protected function saveItem(Request $request, string $context, Model&Administrab ? $request->boolean('is_superadmin') : null; - if ($item instanceof AdminUser && $item->exists) { + if ($item instanceof AdminUser) { $this->guardTarget($item); $demoted = $promote === false || ($request->has('is_active') && ! $request->boolean('is_active')); - if ($item->isSuperadmin() && $demoted && $this->isLastSuperadmin($item)) { + if ($demoted && $this->isLastSuperadmin($item)) { throw ValidationException::withMessages(['is_superadmin' => __('atrium::permissions.last_superadmin')]); } } @@ -104,7 +104,7 @@ private function guardTarget(Model $item): void private function isLastSuperadmin(AdminUser $item): bool { - return $this->model::query() + return $item->isSuperadmin() && $this->model::query() ->where('is_superadmin', true) ->where('is_active', true) ->whereKeyNot($item->getKey()) diff --git a/packages/admin/src/Http/Controllers/Api/DocsController.php b/packages/admin/src/Http/Controllers/Api/DocsController.php index a565f3cb..364918a2 100644 --- a/packages/admin/src/Http/Controllers/Api/DocsController.php +++ b/packages/admin/src/Http/Controllers/Api/DocsController.php @@ -43,6 +43,6 @@ public function openApi(Request $request, ApiDocumentation $docs): JsonResponse */ private function only(Request $request): array { - return array_values(array_filter(array_map('trim', explode(',', (string) $request->query('only', ''))))); + return array_filter(array_map('trim', explode(',', (string) $request->query('only', '')))); } } diff --git a/packages/admin/src/Http/Controllers/Api/ResourceController.php b/packages/admin/src/Http/Controllers/Api/ResourceController.php index a6fa999c..14519ecb 100644 --- a/packages/admin/src/Http/Controllers/Api/ResourceController.php +++ b/packages/admin/src/Http/Controllers/Api/ResourceController.php @@ -67,10 +67,13 @@ public function listItems(Request $request, string $resource = ''): JsonResponse } } - if (($search = (string) $request->query('search', '')) !== '') { + $search = $request->query('search'); + + // search[]=x is not a search: it is ignored, not a reason for a 500. + if (is_string($search) && $search !== '') { $searchable = collect(Hook::apply('atrium.module.columns', $this->model::getAdministrationListColumns(), $this->model)) ->map(fn ($column) => $column->toArray()) - ->filter(fn (array $column): bool => (bool) ($column['searchable'] ?? false)) + ->where('searchable', true) ->pluck('name') ->all(); @@ -89,7 +92,8 @@ public function listItems(Request $request, string $resource = ''): JsonResponse }); } - $sort = (string) $request->query('sort', 'id'); + $sort = $request->query('sort'); + $sort = is_string($sort) ? $sort : 'id'; $direction = $request->query('direction') === 'desc' ? 'desc' : 'asc'; if (! Hook::apply('atrium.query.sort', false, $query, $sort, $direction)) { @@ -111,7 +115,7 @@ public function listItems(Request $request, string $resource = ''): JsonResponse ]); } - public function showItem(Request $request, string $resource = '', int $id = 0): JsonResponse + public function showItem(Request $request, string $resource, int $id): JsonResponse { $this->useResource($request, $resource, 'read', Permissions::VIEW); @@ -130,7 +134,7 @@ public function storeItem(Request $request, string $resource = ''): JsonResponse /** * Updates are partial: only the fields sent are validated and written. */ - public function updateItem(Request $request, string $resource = '', int $id = 0): JsonResponse + public function updateItem(Request $request, string $resource, int $id): JsonResponse { $this->useResource($request, $resource, 'write', Permissions::UPDATE); @@ -139,7 +143,7 @@ public function updateItem(Request $request, string $resource = '', int $id = 0) return response()->json(['data' => $this->present($item->fresh($this->eagerRelations()))]); } - public function destroyItem(Request $request, string $resource = '', int $id = 0): JsonResponse + public function destroyItem(Request $request, string $resource, int $id): JsonResponse { $this->useResource($request, $resource, 'write', Permissions::DELETE); diff --git a/packages/admin/src/Http/Controllers/FileManagerController.php b/packages/admin/src/Http/Controllers/FileManagerController.php index b30dc60c..915a2cba 100644 --- a/packages/admin/src/Http/Controllers/FileManagerController.php +++ b/packages/admin/src/Http/Controllers/FileManagerController.php @@ -17,7 +17,6 @@ use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\UploadedFile; -use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; use Symfony\Component\Mime\MimeTypes; @@ -59,7 +58,7 @@ class FileManagerController extends Controller */ public function upload(Request $request): JsonResponse { - $maxKb = (int) config('atrium.uploads.max_size', 10240); + $maxKb = config('atrium.uploads.max_size', 10240); $request->validate([ 'file' => [ @@ -88,7 +87,9 @@ public function upload(Request $request): JsonResponse ], 422); } - if (! $this->isWhatItsNameSays($file, $extension)) { + $mimeType = $this->contentType($file, $extension); + + if ($mimeType === null) { return response()->json([ 'message' => __('atrium::files.errors.content_mismatch', ['type' => $extension]), ], 422); @@ -101,7 +102,6 @@ public function upload(Request $request): JsonResponse $this->makeWebpCopy($disk, $path); - $mimeType = (string) $file->getMimeType(); $item = MediaItem::create([ 'collection_id' => $this->uploadsCollection()->id, 'name' => Str::limit($file->getClientOriginalName(), 250, ''), @@ -129,20 +129,21 @@ public function upload(Request $request): JsonResponse } /** - * Whether the file is what its name says, judged by its content (finfo), - * not by the name the client sent: a script called photo.jpg is refused. + * The type of the file's content (finfo) when the file is what its name + * says, null when it is not: a script called photo.jpg is refused. * Office files finfo knows only by their container — a zip, an OLE store — * count as the formats built on it. An SVG may carry a script, so one with * anything that runs is refused. */ - private function isWhatItsNameSays(UploadedFile $file, string $extension): bool + private function contentType(UploadedFile $file, string $extension): ?string { $types = MimeTypes::getDefault(); $type = $types->guessMimeType($file->getRealPath()) ?? ''; $extensions = [...$types->getExtensions($type), ...self::CONTAINERS[$type] ?? []]; - return in_array($extension, $extensions, true) - && ($type !== 'image/svg+xml' || preg_match(self::ACTIVE_SVG, (string) $file->getContent()) === 0); + return in_array($extension, $extensions, true) && ($type !== 'image/svg+xml' || preg_match(self::ACTIVE_SVG, (string) $file->getContent()) === 0) + ? $type + : null; } /** @@ -153,9 +154,9 @@ private function isWhatItsNameSays(UploadedFile $file, string $extension): bool * made only by the scheduled `images:webp` command, so an image uploaded in * the panel was served heavy until the next run. * - * A failure is swallowed: a missing copy is a pity, refusing to save the - * image because of it is far worse. The reason goes to the log, and the - * scheduled command catches up later anyway. + * WebpCopy::make() reports what it could not do instead of throwing: a + * missing copy is a pity, refusing to save the image because of it would be + * far worse. */ private function makeWebpCopy(string $disk, string $path): void { @@ -165,11 +166,7 @@ private function makeWebpCopy(string $disk, string $path): void return; } - try { - WebpCopy::make(Storage::disk($disk)->path($path)); - } catch (\Throwable $e) { - Log::warning('Could not make a webp copy of '.$path.': '.$e->getMessage()); - } + WebpCopy::make(Storage::disk($disk)->path($path)); } /** @@ -177,8 +174,9 @@ private function makeWebpCopy(string $disk, string $path): void */ public function index(Request $request): JsonResponse { - $type = (string) $request->get('type', 'all'); - $page = max(1, (int) $request->get('page', 1)); + $type = $request->get('type'); + $type = is_string($type) ? $type : 'all'; + $page = max(1, $request->integer('page')); $query = MediaItem::query(); @@ -188,13 +186,13 @@ public function index(Request $request): JsonResponse $query->documents(); } - if ($collection = (int) $request->get('collection', 0)) { + if ($collection = $request->integer('collection')) { $query->where('collection_id', $collection); } $query->search((string) $request->get('search', '')); - $total = (clone $query)->count(); + $total = $query->count(); $files = $query ->orderByDesc('created_at') @@ -220,7 +218,7 @@ public function index(Request $request): JsonResponse 'total' => $total, 'page' => $page, 'per_page' => self::PER_PAGE, - 'last_page' => (int) ceil($total / self::PER_PAGE), + 'last_page' => ceil($total / self::PER_PAGE), ]); } @@ -296,7 +294,7 @@ private function collections(string $type): array ->map(fn (MediaCollection $collection) => [ 'id' => $collection->id, 'name' => $collection->name, - 'count' => (int) $collection->items_count, + 'count' => $collection->items_count, ]) ->values() ->all(); diff --git a/packages/admin/src/Http/Controllers/ModuleController.php b/packages/admin/src/Http/Controllers/ModuleController.php index 588ae200..e70eae46 100644 --- a/packages/admin/src/Http/Controllers/ModuleController.php +++ b/packages/admin/src/Http/Controllers/ModuleController.php @@ -23,6 +23,7 @@ use Atrium\Admin\Support\Sites; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\Artisan; use Inertia\Inertia; use Inertia\Response; @@ -183,11 +184,11 @@ public function update(Request $request, string $module): RedirectResponse foreach ($fields as $field) { $name = $field->getName(); - $rules[$name] = $field->getValidationRules(FieldContext::edit(null, $request->file($name) ?? $request->input($name), $request->has($name))); + $rules[$name] = $field->getValidationRules(FieldContext::edit(null, Arr::get($request->all(), $name), $request->has($name))); $attributes[$name] = $field->getLabel(); } - $request->validate(array_filter($rules), [], array_filter($attributes)); + $request->validate($rules, [], $attributes); $values = []; diff --git a/packages/admin/src/Http/Controllers/SiteController.php b/packages/admin/src/Http/Controllers/SiteController.php index dcda9a35..40c626b5 100644 --- a/packages/admin/src/Http/Controllers/SiteController.php +++ b/packages/admin/src/Http/Controllers/SiteController.php @@ -29,7 +29,7 @@ public function update(Request $request): RedirectResponse abort_unless($user instanceof AdminUser, 403); $id = $request->validate([ - 'site_id' => ['required', Rule::in($user->allowedSites()->pluck('id')->map(fn ($id) => (string) $id)->all())], + 'site_id' => ['required', Rule::in($user->allowedSites()->pluck('id')->all())], ])['site_id']; $request->session()->put(ResolveSite::SESSION_KEY, (int) $id); diff --git a/packages/admin/src/Http/Middleware/EnterSiteFolder.php b/packages/admin/src/Http/Middleware/EnterSiteFolder.php index 8650b6e4..b2921e60 100644 --- a/packages/admin/src/Http/Middleware/EnterSiteFolder.php +++ b/packages/admin/src/Http/Middleware/EnterSiteFolder.php @@ -49,7 +49,7 @@ public function handle(Request $request, Closure $next): Response return $next($request); } - $rest = substr($path, strlen('/'.$site->folder)) ?: '/'; + $rest = substr($path, strlen($site->folder) + 1) ?: '/'; if ($this->isPanel($rest)) { return $next($request); @@ -79,17 +79,17 @@ public function handle(Request $request, Closure $next): Response /** * Symfony keeps the base URL and the path of a request in properties of - * its own and offers no setter. Both are worked out first, then the - * folder moves from one to the other. + * its own and offers no setter. The path is worked out (with the base URL) + * by the caller, the base path here, then the folder moves from one to + * the other. */ private function move(Request $request, string $folder, string $rest): void { - $request->getBaseUrl(); $request->getBasePath(); (function (string $folder, string $rest): void { $this->baseUrl .= $folder; - $this->basePath = rtrim((string) $this->basePath, '/').$folder; + $this->basePath .= $folder; $this->pathInfo = $rest; })->call($request, $folder, $rest); } diff --git a/packages/admin/src/Http/Middleware/HandleAtriumRequests.php b/packages/admin/src/Http/Middleware/HandleAtriumRequests.php index d845656c..2ad996e2 100644 --- a/packages/admin/src/Http/Middleware/HandleAtriumRequests.php +++ b/packages/admin/src/Http/Middleware/HandleAtriumRequests.php @@ -17,6 +17,7 @@ use Atrium\Admin\Support\Themes; use Closure; use Illuminate\Http\Request; +use Illuminate\Support\Facades\File; use Inertia\Inertia; use Inertia\Middleware; use Symfony\Component\HttpFoundation\Response; @@ -53,7 +54,7 @@ public function version(Request $request): ?string { $manifest = public_path('vendor/atrium/manifest.json'); - return is_file($manifest) ? (string) md5_file($manifest) : null; + return is_file($manifest) ? md5(File::get($manifest)) : null; } /** diff --git a/packages/admin/src/Http/Middleware/RecordPageTiming.php b/packages/admin/src/Http/Middleware/RecordPageTiming.php index 35db7846..18032797 100644 --- a/packages/admin/src/Http/Middleware/RecordPageTiming.php +++ b/packages/admin/src/Http/Middleware/RecordPageTiming.php @@ -42,7 +42,7 @@ public function terminate(Request $request, Response $response): void return; } - $rate = (float) config('atrium.dashboard.timings.sample_rate', 1.0); + $rate = config('atrium.dashboard.timings.sample_rate', 1.0); if ($rate < 1.0 && mt_rand() / mt_getrandmax() > $rate) { return; @@ -83,11 +83,8 @@ private function shouldRecord(Request $request, Response $response): bool private function durationMs(Request $request): int { - $start = defined('LARAVEL_START') - ? LARAVEL_START - : (float) $request->server('REQUEST_TIME_FLOAT', microtime(true)); - - $ms = (int) round((microtime(true) - $start) * 1000); + $now = now()->getPreciseTimestamp(6) / 1000000; + $ms = (int) round(($now - $request->server('REQUEST_TIME_FLOAT', $now)) * 1000); // Upper bound, so a single timeout does not stretch the scale to infinity. return max(0, min($ms, 600000)); diff --git a/packages/admin/src/Http/Middleware/SetContentLocale.php b/packages/admin/src/Http/Middleware/SetContentLocale.php index f446dc97..8f5d2a8c 100644 --- a/packages/admin/src/Http/Middleware/SetContentLocale.php +++ b/packages/admin/src/Http/Middleware/SetContentLocale.php @@ -29,12 +29,11 @@ public function __construct(private readonly ContentLanguages $languages) {} public function handle(Request $request, Closure $next): Response { - $route = $request->route(); - $code = $route?->parameter('locale'); + $code = $request->route('locale'); if (is_string($code)) { abort_unless($this->languages->has($code) && $code !== $this->languages->default(), 404); - $route->forgetParameter('locale'); + $request->route()->forgetParameter('locale'); } else { $code = $this->languages->default(); } diff --git a/packages/admin/src/Http/Middleware/SlugRedirectMiddleware.php b/packages/admin/src/Http/Middleware/SlugRedirectMiddleware.php index 874d1753..8652a686 100644 --- a/packages/admin/src/Http/Middleware/SlugRedirectMiddleware.php +++ b/packages/admin/src/Http/Middleware/SlugRedirectMiddleware.php @@ -44,7 +44,7 @@ public function handle(Request $request, Closure $next): Response $redirect = SlugHistory::findRedirectPath($path); if ($redirect && $redirect !== $path) { - return redirect('/'.$redirect, 301); + return redirect($redirect, 301); } // Try just the last segment as slug: it is replaced by the current diff --git a/packages/admin/src/Mcp/ApiGateway.php b/packages/admin/src/Mcp/ApiGateway.php index 189ff74d..6025a515 100644 --- a/packages/admin/src/Mcp/ApiGateway.php +++ b/packages/admin/src/Mcp/ApiGateway.php @@ -39,7 +39,7 @@ public function call(string $method, string $path, array $query = [], ?array $bo $method, $query, server: ['CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json'], - content: $body === null ? null : (string) json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), + content: $body === null ? null : json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ); $sub->headers->set('Authorization', (string) $current->headers->get('Authorization')); @@ -54,7 +54,6 @@ public function call(string $method, string $path, array $query = [], ?array $bo // The MCP response still belongs to the original request. app()->instance('request', $current); Facade::clearResolvedInstance('request'); - url()->setRequest($current); } $status = $response->getStatusCode(); @@ -75,7 +74,7 @@ public function call(string $method, string $path, array $query = [], ?array $bo */ private static function message(int $status, array $data): string { - $message = (string) ($data['message'] ?? 'The request failed.'); + $message = $data['message'] ?? 'The request failed.'; foreach ((array) ($data['errors'] ?? []) as $field => $errors) { $message .= "\n- {$field}: ".implode(' ', (array) $errors); diff --git a/packages/admin/src/Mcp/AtriumServer.php b/packages/admin/src/Mcp/AtriumServer.php index 8e3de287..206a6b6e 100644 --- a/packages/admin/src/Mcp/AtriumServer.php +++ b/packages/admin/src/Mcp/AtriumServer.php @@ -56,6 +56,6 @@ class AtriumServer extends Server */ protected function boot(): void { - $this->tools = array_values(array_unique([...$this->tools, ...(array) config('atrium.mcp.tools', [])])); + $this->tools = array_unique([...$this->tools, ...(array) config('atrium.mcp.tools', [])]); } } diff --git a/packages/admin/src/Mcp/Tools/ApiTool.php b/packages/admin/src/Mcp/Tools/ApiTool.php index d77a42bd..8d96e9bd 100644 --- a/packages/admin/src/Mcp/Tools/ApiTool.php +++ b/packages/admin/src/Mcp/Tools/ApiTool.php @@ -46,7 +46,7 @@ protected function module(Request $request): ?string protected function unknownModule(Request $request): Response { - return Response::error('No module "'.(string) $request->get('module', '').'". See list_modules.'); + return Response::error('No module "'.$request->get('module', '').'". See list_modules.'); } /** diff --git a/packages/admin/src/Mcp/Tools/DescribeModule.php b/packages/admin/src/Mcp/Tools/DescribeModule.php index 40021649..71144263 100644 --- a/packages/admin/src/Mcp/Tools/DescribeModule.php +++ b/packages/admin/src/Mcp/Tools/DescribeModule.php @@ -36,7 +36,7 @@ public function handle(Request $request, ApiDocumentation $docs): Response return Response::error("No module \"{$module}\" for this token. See list_modules."); } - $description = $docs->modules([$module])[$module]; + $description = $docs->module($module); return Response::json([ 'module' => $module, diff --git a/packages/admin/src/Models/AdminUser.php b/packages/admin/src/Models/AdminUser.php index cfec552c..d55708ac 100644 --- a/packages/admin/src/Models/AdminUser.php +++ b/packages/admin/src/Models/AdminUser.php @@ -116,7 +116,7 @@ public static function getAdministrationFields(): array MultiSelectField::make('site_ids') ->label(__('atrium::account.users.fields.sites')) ->hint(__('atrium::account.users.hints.sites')) - ->options(app(Sites::class)->all()->mapWithKeys(fn ($site) => [(string) $site->id => $site->name])->all()), + ->options(app(Sites::class)->all()->mapWithKeys(fn ($site) => [$site->id => $site->name])->all()), ] : []), // Only a superadmin hands out rights: anyone else could give @@ -185,7 +185,7 @@ public static function getCreateValidationRules(): array 'roles' => ['nullable', 'array'], 'roles.*' => ['integer', Rule::exists('admin_roles', 'id')], 'site_ids' => ['nullable', 'array'], - 'site_ids.*' => [Rule::in(app(Sites::class)->all()->pluck('id')->map(fn ($id) => (string) $id)->all())], + 'site_ids.*' => [Rule::in(app(Sites::class)->all()->pluck('id')->all())], ]; } @@ -203,7 +203,7 @@ public static function getUpdateValidationRules(): array 'roles' => ['nullable', 'array'], 'roles.*' => ['integer', Rule::exists('admin_roles', 'id')], 'site_ids' => ['nullable', 'array'], - 'site_ids.*' => [Rule::in(app(Sites::class)->all()->pluck('id')->map(fn ($id) => (string) $id)->all())], + 'site_ids.*' => [Rule::in(app(Sites::class)->all()->pluck('id')->all())], ]; } @@ -265,7 +265,7 @@ public function hasAdminPermission(string $permission): bool public function adminPermissions(): array { return $this->roles - ->flatMap(fn (AdminRole $role): array => (array) $role->permissions) + ->flatMap(fn (AdminRole $role): array => $role->permissions) ->unique() ->values() ->all(); diff --git a/packages/admin/src/Models/Language.php b/packages/admin/src/Models/Language.php index 0c885fe5..50f9109d 100644 --- a/packages/admin/src/Models/Language.php +++ b/packages/admin/src/Models/Language.php @@ -69,7 +69,7 @@ protected static function booted(): void } if ($language->exists && $language->isDirty('code')) { - $language->code = (string) $language->getOriginal('code'); + $language->code = $language->getOriginal('code'); } }); @@ -126,7 +126,7 @@ public static function getAdministrationFields(): array ->label(__('atrium::languages.fields.code')) ->hint(__('atrium::languages.hints.code')) ->required() - ->rules(['string', 'max:12', 'regex:/^'.self::CODE_PATTERN.'$/']) + ->rules(['max:12', 'regex:/^'.self::CODE_PATTERN.'$/']) ->unique('admin_languages', 'code') ->onlyOnCreate(), diff --git a/packages/admin/src/Models/Site.php b/packages/admin/src/Models/Site.php index d721e69a..f4b17eab 100644 --- a/packages/admin/src/Models/Site.php +++ b/packages/admin/src/Models/Site.php @@ -27,6 +27,7 @@ use Atrium\Admin\Traits\HasAdminTabs; use Atrium\Admin\Traits\InteractsWithAdmin; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; /** @@ -112,7 +113,7 @@ protected static function booted(): void } if ($site->exists && $site->isDirty('code')) { - $site->code = (string) $site->getOriginal('code'); + $site->code = $site->getOriginal('code'); } $site->domains = $site->normalizedDomains(); @@ -213,7 +214,7 @@ private static function siteFields(array $languages): array ->label(__('atrium::sites.fields.code')) ->hint(__('atrium::sites.hints.code')) ->required() - ->rules(['string', 'max:32', 'regex:/^'.self::CODE_PATTERN.'$/']) + ->rules(['max:32', 'regex:/^'.self::CODE_PATTERN.'$/']) ->unique('admin_sites', 'code') ->onlyOnCreate(), @@ -272,13 +273,13 @@ private static function codeFields(): array ->label(__('atrium::sites.fields.google_tag_id')) ->hint(__('atrium::sites.hints.google_tag_id')) ->placeholder('G-XXXXXXXXXX') - ->rules(['string', 'max:32', 'regex:'.self::GOOGLE_TAG_PATTERN]), + ->rules(['max:32', 'regex:'.self::GOOGLE_TAG_PATTERN]), TextField::make('yandex_metrika_id') ->label(__('atrium::sites.fields.yandex_metrika_id')) ->hint(__('atrium::sites.hints.yandex_metrika_id')) ->placeholder('12345678') - ->rules(['string', 'max:20', 'regex:/^\\s*\\d+\\s*$/']), + ->rules(['max:20', 'regex:/^\\s*\\d+\\s*$/']), CheckboxField::make('yandex_webvisor') ->label(__('atrium::sites.fields.yandex_webvisor')) @@ -292,17 +293,17 @@ private static function codeFields(): array TextField::make('google_verification') ->label(__('atrium::sites.fields.google_verification')) ->hint(__('atrium::sites.hints.verification', ['name' => 'google-site-verification'])) - ->rules(['string', 'max:1000']), + ->rules(['max:1000']), TextField::make('yandex_verification') ->label(__('atrium::sites.fields.yandex_verification')) ->hint(__('atrium::sites.hints.verification', ['name' => 'yandex-verification'])) - ->rules(['string', 'max:1000']), + ->rules(['max:1000']), TextField::make('bing_verification') ->label(__('atrium::sites.fields.bing_verification')) ->hint(__('atrium::sites.hints.verification', ['name' => 'msvalidate.01'])) - ->rules(['string', 'max:1000']), + ->rules(['max:1000']), TextareaField::make('head_code') ->label(__('atrium::sites.fields.head_code')) @@ -390,7 +391,7 @@ public function url(string $path = ''): string $root = $request->getScheme().'://'.$domain.($standard || $port === null ? '' : ':'.$port); } - $path = trim(implode('/', [(string) $this->folder, trim($path, '/')]), '/'); + $path = trim(implode('/', [$this->folder, trim($path, '/')]), '/'); return $path === '' ? $root : $root.'/'.$path; } @@ -452,10 +453,13 @@ public function holdsPath(string $path): bool */ public static function normalizeFolder(mixed $folder): ?string { - $folder = trim((string) $folder); - $folder = (string) preg_replace('#^[a-z][a-z0-9+.-]*://[^/]*#i', '', $folder); - $folder = (string) preg_replace('#[?\#].*$#', '', $folder); - $folder = trim((string) preg_replace('#/+#', '/', $folder), '/'); + $folder = Str::of((string) $folder) + ->trim() + ->replaceMatches('#^[a-z][a-z0-9+.-]*://[^/]*#i', '') + ->replaceMatches('#[?\#].*$#', '') + ->replaceMatches('#/+#', '/') + ->trim('/') + ->value(); return $folder === '' ? null : $folder; } @@ -471,10 +475,14 @@ private function normalizedDomains(): array $domains = []; foreach ((array) $this->domains as $domain) { - $domain = strtolower(trim((string) $domain)); - $domain = (string) preg_replace('#^[a-z][a-z0-9+.-]*://#', '', $domain); - $domain = (string) preg_replace('#[/?\#].*$#', '', $domain); - $domain = rtrim((string) preg_replace('#:\d+$#', '', $domain), '.'); + $domain = Str::of((string) $domain) + ->trim() + ->lower() + ->replaceMatches('#^[a-z][a-z0-9+.-]*://#', '') + ->replaceMatches('#[/?\#].*$#', '') + ->replaceMatches('#:\d+$#', '') + ->rtrim('.') + ->value(); if ($domain !== '' && ! in_array($domain, $domains, true)) { $domains[] = $domain; @@ -524,11 +532,11 @@ private function guardFolder(): void } $first = strtolower(explode('/', $this->folder)[0]); - $reserved = array_filter([ + $reserved = [ strtolower(explode('/', trim((string) config('atrium.prefix', 'admin'), '/'))[0]), strtolower(explode('/', trim((string) config('atrium.api.prefix', 'api/v1'), '/'))[0]), strtolower(explode('/', trim((string) config('atrium.mcp.path', 'mcp'), '/'))[0]), - ]); + ]; if (in_array($first, $reserved, true)) { throw ValidationException::withMessages(['folder' => __('atrium::sites.errors.folder_reserved', ['folder' => $first])]); @@ -547,7 +555,7 @@ private function guardFolder(): void */ private function guardDomains(): void { - foreach ((array) $this->domains as $domain) { + foreach ($this->domains as $domain) { if (! preg_match(self::DOMAIN_PATTERN, $domain)) { throw ValidationException::withMessages(['domains' => __('atrium::sites.errors.domain_invalid', ['domain' => $domain])]); } @@ -560,13 +568,13 @@ private function guardDomains(): void continue; } - $clash = array_intersect((array) $this->domains, (array) $other->domains); + $clash = array_intersect($this->domains, (array) $other->domains); if ($clash !== [] && $this->folder === null) { throw ValidationException::withMessages(['domains' => __('atrium::sites.errors.domain_taken', ['domain' => reset($clash), 'site' => $other->name])]); } - if ($this->folder !== null && ($clash !== [] || ((array) $this->domains === [] && (array) $other->domains === []))) { + if ($this->folder !== null && ($clash !== [] || ($this->domains === [] && (array) $other->domains === []))) { $address = ($clash === [] ? '' : reset($clash)).'/'.$this->folder.'/'; throw ValidationException::withMessages(['folder' => __('atrium::sites.errors.folder_taken', ['address' => $address, 'site' => $other->name])]); diff --git a/packages/admin/src/Modules/Modules.php b/packages/admin/src/Modules/Modules.php index 5c41e4e5..cdb3605f 100644 --- a/packages/admin/src/Modules/Modules.php +++ b/packages/admin/src/Modules/Modules.php @@ -344,7 +344,7 @@ public function dependencyOrder(array $modules): array return; } - foreach ([...array_filter([$this->parentOf($module)?->name]), ...$module->suggests] as $name) { + foreach ([$this->parentOf($module)?->name, ...$module->suggests] as $name) { if (isset($modules[$name])) { $visit($modules[$name], [...$path, $module->name]); } diff --git a/packages/admin/src/Modules/Settings.php b/packages/admin/src/Modules/Settings.php index ec2b4f99..9fbfb4f9 100644 --- a/packages/admin/src/Modules/Settings.php +++ b/packages/admin/src/Modules/Settings.php @@ -37,9 +37,6 @@ final class Settings /** @var array */ private array $declarations = []; - /** @var array> */ - private array $defaults = []; - public function __construct( private readonly Modules $modules, private readonly Sites $sites, @@ -50,9 +47,9 @@ public function __construct( */ public function get(string $key, mixed $default = null, Site|int|null $site = null): mixed { - [$module, $name] = array_pad(explode('.', $key, 2), 2, ''); + $parts = explode('.', $key, 2); - return $this->all($module, $site)[$name] ?? $default; + return $this->all($parts[0], $site)[$parts[1] ?? ''] ?? $default; } /** @@ -70,7 +67,7 @@ public function all(string $module, Site|int|null $site = null): array $stored = array_filter($this->stored($module, $this->siteId($declaration, $site)), static fn (mixed $value): bool => $value !== null && $value !== ''); - return array_replace($this->defaults[$module] ??= $declaration->defaults(), $stored); + return array_replace($declaration->defaults(), $stored); } /** @@ -172,7 +169,7 @@ public function siteId(ModuleSettings $declaration, Site|int|null $site = null): */ public function flush(): void { - $this->stored = $this->declarations = $this->defaults = []; + $this->stored = $this->declarations = []; if (app()->resolved(RecordCache::class)) { app(RecordCache::class)->flushClass(self::class); diff --git a/packages/admin/src/Services/SlugService.php b/packages/admin/src/Services/SlugService.php index e7297a38..c80cf4d8 100644 --- a/packages/admin/src/Services/SlugService.php +++ b/packages/admin/src/Services/SlugService.php @@ -64,7 +64,7 @@ public function generateUnique(string $text, string $modelClass, ?int $excludeId */ public function ensureUnique(string $slug, string $modelClass, ?int $excludeId = null, int $counter = 0): string { - $testSlug = $counter > 0 ? "{$slug}-{$counter}" : $slug; + $testSlug = $counter !== 0 ? "{$slug}-{$counter}" : $slug; $query = $modelClass::where('code', $testSlug); @@ -165,10 +165,7 @@ public function syncSlug(Model $model): void } $model->slugModel()->updateOrCreate( - [ - 'sluggable_type' => get_class($model), - 'sluggable_id' => $model->getKey(), - ], + [], [ 'slug' => $model->getAttribute('code'), 'full_path' => $model->getFullPath(), diff --git a/packages/admin/src/Support/ConfigWriter.php b/packages/admin/src/Support/ConfigWriter.php index 6a6eec69..0a1fd312 100644 --- a/packages/admin/src/Support/ConfigWriter.php +++ b/packages/admin/src/Support/ConfigWriter.php @@ -9,6 +9,9 @@ namespace Atrium\Admin\Support; +use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Str; + /** * Small, conservative edits of the published config/atrium.php. * @@ -28,7 +31,7 @@ public static function addResource(string $class, ?string $path = null): bool return false; } - $config = (string) file_get_contents($path); + $config = (new Filesystem)->get($path); $entry = '\\'.ltrim($class, '\\').'::class'; if (str_contains($config, $entry)) { @@ -90,7 +93,7 @@ private static function addToList(string $key, string $after, string $comment, s return false; } - $config = (string) file_get_contents($path); + $config = (new Filesystem)->get($path); $entry = var_export(strtolower($name), true); $list = "/'{$key}'\\s*=>\\s*\\[\\n(.*?)^[ \\t]*\\],/sm"; @@ -104,13 +107,14 @@ private static function addToList(string $key, string $after, string $comment, s } preg_match($list, $config, $match, PREG_OFFSET_CAPTURE); + [$inner, $innerAt] = $match[1]; - if (preg_match('/^[ \\t]*'.preg_quote($entry, '/').',/m', $match[1][0])) { + if (preg_match('/^[ \\t]*'.preg_quote($entry, '/').',/m', $inner)) { return true; } // Appended: the list is the menu's order. - $at = $match[1][1] + strlen($match[1][0]); + $at = $innerAt + strlen($inner); self::write($path, substr($config, 0, $at)." {$entry},\n".substr($config, $at)); return true; @@ -124,14 +128,14 @@ private static function removeFromList(string $key, string $name, ?string $path) return false; } - $config = (string) file_get_contents($path); + $config = (new Filesystem)->get($path); if (! preg_match("/'{$key}'\s*=>\s*\[\n.*?\],/s", $config, $match, PREG_OFFSET_CAPTURE)) { return true; } $line = '/^[ \t]*'.preg_quote(var_export(strtolower($name), true), '/').',[ \t]*\n/m'; - $list = (string) preg_replace($line, '', $match[0][0]); + $list = Str::replaceMatches($line, '', $match[0][0]); self::write($path, substr_replace($config, $list, $match[0][1], strlen($match[0][0]))); diff --git a/packages/admin/src/Support/ContentLanguages.php b/packages/admin/src/Support/ContentLanguages.php index 1e13b29c..ae6abbf7 100644 --- a/packages/admin/src/Support/ContentLanguages.php +++ b/packages/admin/src/Support/ContentLanguages.php @@ -48,7 +48,7 @@ public function codes(): array public function default(): string { - return (string) $this->all()->first()?->code; + return (string) $this->all()->firstOrFail()->code; } public function has(string $code): bool @@ -137,10 +137,8 @@ private function load(): Collection } // The site's own default language, else the panel-wide one. - $default = $languages->firstWhere('code', $site->default_language) - ?? $languages->firstWhere('is_default', true) - ?? $languages->first(); + $default = $languages->firstWhere('code', $site->default_language) ?? $languages->first(); - return $languages->sortBy(fn (Language $language): int => $language->is($default) ? 0 : 1)->values(); + return $languages->reject(fn (Language $language): bool => $language->is($default))->prepend($default)->values(); } } diff --git a/packages/admin/src/Support/Locales.php b/packages/admin/src/Support/Locales.php index 535509fd..01826881 100644 --- a/packages/admin/src/Support/Locales.php +++ b/packages/admin/src/Support/Locales.php @@ -74,10 +74,7 @@ public function dictionary(string $locale): array $dictionary = []; foreach (array_diff($this->groups(), ['validation']) as $group) { - $fallback = (array) trans("atrium::{$group}", [], self::FALLBACK); - $own = (array) trans("atrium::{$group}", [], $locale); - - $dictionary[$group] = array_replace_recursive($fallback, $own); + $dictionary[$group] = array_replace_recursive($this->lines($group, self::FALLBACK), $this->lines($group, $locale)); } /** @var array */ @@ -117,13 +114,25 @@ public function groups(): array return array_map(static fn (string $file): string => basename($file, '.php'), $files); } + /** + * One lang file in one language; none when that language has no such file. + * + * @return array + */ + private function lines(string $group, string $locale): array + { + $lines = trans("atrium::{$group}", [], $locale); + + return is_array($lines) ? $lines : []; + } + private function browserAsked(Request $request, string $locale): bool { - $wanted = strtolower(str_replace('_', '-', $locale)); + $wanted = str_replace('_', '-', $locale); $language = strtok($wanted, '-'); foreach ($request->getLanguages() as $asked) { - $asked = strtolower(str_replace('_', '-', $asked)); + $asked = str_replace('_', '-', $asked); if ($asked === $wanted || $asked === $language || strtok($asked, '-') === $language) { return true; diff --git a/packages/admin/src/Support/Menu.php b/packages/admin/src/Support/Menu.php index 45c90f73..4554a18d 100644 --- a/packages/admin/src/Support/Menu.php +++ b/packages/admin/src/Support/Menu.php @@ -126,7 +126,7 @@ private function translate(array $items): array /** * @param array> $menu - * @return array + * @return array */ private function listedRoutes(array $menu): array { @@ -134,12 +134,12 @@ private function listedRoutes(array $menu): array foreach ($menu as $item) { if (isset($item['route'])) { - $routes[] = (string) $item['route']; + $routes[] = $item['route']; } foreach ($item['children'] ?? [] as $child) { if (isset($child['route'])) { - $routes[] = (string) $child['route']; + $routes[] = $child['route']; } } } diff --git a/packages/admin/src/Support/PublicUrl.php b/packages/admin/src/Support/PublicUrl.php index 05471acc..9544b4d3 100644 --- a/packages/admin/src/Support/PublicUrl.php +++ b/packages/admin/src/Support/PublicUrl.php @@ -35,7 +35,7 @@ final class PublicUrl */ private const MAX_DEPTH = 20; - /** @var array> */ + /** @var array>> tree class => parent column => paths */ private static array $pathCache = []; /** @@ -104,16 +104,14 @@ public static function ruleFor(string $modelClass): ?array */ public static function sectionPaths(string $treeClass, string $parentColumn = 'parent_id'): array { - $cacheKey = $treeClass.'|'.$parentColumn; - - if (isset(self::$pathCache[$cacheKey])) { - return self::$pathCache[$cacheKey]; + if (isset(self::$pathCache[$treeClass][$parentColumn])) { + return self::$pathCache[$treeClass][$parentColumn]; } // Kept in the record cache until a section of the tree changes. - return self::$pathCache[$cacheKey] = app(RecordCache::class)->remember( + return self::$pathCache[$treeClass][$parentColumn] = app(RecordCache::class)->remember( [$treeClass, self::class], - 'section-paths:'.$cacheKey, + 'section-paths:'.$treeClass.'|'.$parentColumn, static fn (): array => self::buildSectionPaths($treeClass, $parentColumn), perSite: false, ); diff --git a/packages/admin/src/Support/Sitemap.php b/packages/admin/src/Support/Sitemap.php index aee13218..aa548021 100644 --- a/packages/admin/src/Support/Sitemap.php +++ b/packages/admin/src/Support/Sitemap.php @@ -54,7 +54,7 @@ public function parts(): int public function index(): string { if ($this->parts() <= 1) { - return $this->part(1); + return $this->urlset($this->entries()); } $xml = $this->writer(); @@ -74,8 +74,14 @@ public function index(): string public function part(int $part): string { - $entries = array_slice($this->entries(), ($part - 1) * $this->perFile(), $this->perFile()); + return $this->urlset(array_slice($this->entries(), ($part - 1) * $this->perFile(), $this->perFile())); + } + /** + * @param array}> $entries + */ + private function urlset(array $entries): string + { $xml = $this->writer(); $xml->startElement('urlset'); $xml->writeAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); @@ -196,9 +202,9 @@ private function entriesOf(Model $record, Closure $urlIn): array if (count($urls) > 1) { $alternates = $urls; - $default = $this->languages->all()->first(); + $default = $this->languages->all()->firstOrFail(); - if ($default !== null && isset($urls[$default->hreflang()])) { + if (isset($urls[$default->hreflang()])) { $alternates['x-default'] = $urls[$default->hreflang()]; } } diff --git a/packages/admin/src/Support/Sites.php b/packages/admin/src/Support/Sites.php index d9ae72a8..248d47d8 100644 --- a/packages/admin/src/Support/Sites.php +++ b/packages/admin/src/Support/Sites.php @@ -49,7 +49,7 @@ public function all(): Collection public function default(): Site { - return $this->all()->firstWhere('is_default', true) ?? $this->all()->first(); + return $this->all()->firstOrFail(); } public function find(mixed $id): ?Site @@ -99,7 +99,7 @@ public function folderSites(string $host): Collection ->filter(fn (Site $site): bool => $site->active && $site->folder !== null && ($site->hasDomain($host) || (array) $site->domains === [])) ->sortBy([ fn (Site $a, Site $b): int => strlen((string) $b->folder) <=> strlen((string) $a->folder), - fn (Site $a, Site $b): int => (int) $b->hasDomain($host) <=> (int) $a->hasDomain($host), + fn (Site $a, Site $b): int => $b->hasDomain($host) <=> $a->hasDomain($host), ]) ->unique('folder') ->values(); @@ -114,8 +114,10 @@ public static function rootUrl(Request $request): string $root = $request->root(); $folder = $request->attributes->get(EnterSiteFolder::FOLDER); - return is_string($folder) && str_ends_with($root, '/'.$folder) - ? substr($root, 0, -strlen('/'.$folder)) + $suffix = '/'.$folder; + + return is_string($folder) && str_ends_with($root, $suffix) + ? substr($root, 0, -strlen($suffix)) : $root; } diff --git a/packages/admin/src/Support/Themes.php b/packages/admin/src/Support/Themes.php index a45e2eab..d1445705 100644 --- a/packages/admin/src/Support/Themes.php +++ b/packages/admin/src/Support/Themes.php @@ -35,9 +35,10 @@ public function choices(): array return [self::SYSTEM, ...self::THEMES]; } - public function isChoice(?string $choice): bool + /** @phpstan-assert-if-true string $choice */ + public function isChoice(mixed $choice): bool { - return $choice !== null && in_array($choice, $this->choices(), true); + return in_array($choice, $this->choices(), true); } /** The configured default, or graphite when the config names no theme. */ @@ -45,13 +46,15 @@ public function default(): string { $configured = config('atrium.admin.theme'); - return is_string($configured) && $this->isChoice($configured) ? $configured : self::FALLBACK; + return $this->isChoice($configured) ? $configured : self::FALLBACK; } /** The admin's own choice, otherwise the default. May be "system". */ public function choiceFor(?AdminUser $user): string { - return $this->isChoice($user?->theme) ? (string) $user->theme : $this->default(); + $theme = $user?->theme; + + return $this->isChoice($theme) ? $theme : $this->default(); } /** diff --git a/packages/admin/src/Support/WebpCopy.php b/packages/admin/src/Support/WebpCopy.php index 68a9b494..e4493ef5 100644 --- a/packages/admin/src/Support/WebpCopy.php +++ b/packages/admin/src/Support/WebpCopy.php @@ -10,6 +10,7 @@ namespace Atrium\Admin\Support; use GdImage; +use SplFileInfo; /** * A lighter copy of an image: `photo.jpg` gets a `photo.jpg.webp` next to it. @@ -59,7 +60,7 @@ public static function convertible(string $path): bool * * @return array{status: string, before?: int, after?: int} */ - public static function make(string $source, int $quality = 82, int $maxWidth = 1920, bool $force = false): array + public static function make(string $source, int $quality = 82, int $maxWidth = 1920, bool $force = false, int $maxPixels = self::MAX_PIXELS): array { if (! self::supported() || ! is_file($source) || ! self::convertible($source)) { return ['status' => 'failed']; @@ -71,7 +72,7 @@ public static function make(string $source, int $quality = 82, int $maxWidth = 1 return ['status' => 'skipped']; } - $image = self::load($source); + $image = self::load($source, $maxPixels); if ($image === null) { return ['status' => 'failed']; @@ -79,14 +80,13 @@ public static function make(string $source, int $quality = 82, int $maxWidth = 1 $image = self::resize($image, $maxWidth); $ok = @imagewebp($image, $target, $quality); - imagedestroy($image); if (! $ok) { return ['status' => 'failed']; } - $before = (int) filesize($source); - $after = (int) filesize($target); + $before = (new SplFileInfo($source))->getSize(); + $after = (new SplFileInfo($target))->getSize(); // A copy heavier than the source is pointless — the server would serve // the original. Happens with palette PNGs: webp loses on badges and logos. @@ -99,7 +99,7 @@ public static function make(string $source, int $quality = 82, int $maxWidth = 1 return ['status' => 'made', 'before' => $before, 'after' => $after]; } - private static function load(string $path): ?GdImage + private static function load(string $path, int $maxPixels): ?GdImage { $info = @getimagesize($path); @@ -109,16 +109,13 @@ private static function load(string $path): ?GdImage [$width, $height] = $info; - if ($width * $height > self::MAX_PIXELS) { + if ($width * $height > $maxPixels) { return null; } // Some files named .jpg are actually webp already (left so by an old - // CMS module). Nothing to compress a second time. - if ($info[2] === IMAGETYPE_WEBP) { - return null; - } - + // CMS module). Nothing to compress a second time: only the two types + // below are opened. $image = match ($info[2]) { IMAGETYPE_JPEG => @imagecreatefromjpeg($path), IMAGETYPE_PNG => @imagecreatefrompng($path), @@ -129,11 +126,9 @@ private static function load(string $path): ?GdImage return null; } - // Otherwise palette PNGs lose colours when scaled, and without these two - // lines transparency is filled with black. + // Otherwise palette PNGs lose colours when scaled, and webp cannot be + // written from a palette image at all. imagepalettetotruecolor($image); - imagealphablending($image, false); - imagesavealpha($image, true); return $image; } @@ -141,18 +136,21 @@ private static function load(string $path): ?GdImage private static function resize(GdImage $image, int $maxWidth): GdImage { $width = imagesx($image); + $scaled = $maxWidth > 0 ? min($maxWidth, $width) : $width; - if ($maxWidth <= 0 || $width <= $maxWidth) { - return $image; - } + return $scaled === $width ? $image : self::scaled($image, $scaled); + } - $height = (int) round(imagesy($image) * $maxWidth / $width); - $resized = imagecreatetruecolor($maxWidth, $height); + private static function scaled(GdImage $image, int $width): GdImage + { + $sourceWidth = imagesx($image); + $sourceHeight = imagesy($image); + $height = max(1, (int) round($sourceHeight * $width / $sourceWidth)); + $resized = imagecreatetruecolor($width, $height); + // Without this the copy of transparent areas is blended onto black. imagealphablending($resized, false); - imagesavealpha($resized, true); - imagecopyresampled($resized, $image, 0, 0, 0, 0, $maxWidth, $height, $width, imagesy($image)); - imagedestroy($image); + imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $sourceWidth, $sourceHeight); return $resized; } diff --git a/packages/admin/src/Traits/HasAdminFiles.php b/packages/admin/src/Traits/HasAdminFiles.php index 8c411f1d..71a710c8 100644 --- a/packages/admin/src/Traits/HasAdminFiles.php +++ b/packages/admin/src/Traits/HasAdminFiles.php @@ -32,9 +32,8 @@ public function files(): MorphMany public static function bootHasAdminFiles(): void { static::deleting(function ($model) { - // Delete associated files from storage + // A file row removes its file from the disk as it goes (File::booted()). foreach ($model->files as $file) { - Storage::disk($file->disk)->delete($file->path); $file->delete(); } }); @@ -92,10 +91,7 @@ public function detachFile(string $field, int $fileId): void { $file = $this->files()->where('field', $field)->where('id', $fileId)->first(); - if ($file) { - Storage::disk($file->disk)->delete($file->path); - $file->delete(); - } + $file?->delete(); } /** @@ -121,16 +117,12 @@ public function syncFiles(string $field, array $paths, array $metadata = []): vo // Delete existing files $existingFiles = $this->getFilesByField($field); foreach ($existingFiles as $file) { - Storage::disk($file->disk)->delete($file->path); $file->delete(); } // Attach new files - foreach ($paths as $index => $path) { - $this->attachFile($field, $path, [ - 'sort' => $index + 1, - ...$metadata, - ]); + foreach ($paths as $path) { + $this->attachFile($field, $path, $metadata); } } diff --git a/packages/admin/src/Traits/HasAdminSeo.php b/packages/admin/src/Traits/HasAdminSeo.php index 563970a6..8f253a2c 100644 --- a/packages/admin/src/Traits/HasAdminSeo.php +++ b/packages/admin/src/Traits/HasAdminSeo.php @@ -15,7 +15,9 @@ use Atrium\Admin\Fields\TextField; use Atrium\Admin\Models\SeoMeta; use Atrium\Admin\Support\MediaUrl; +use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphOne; +use Illuminate\Support\Carbon; use Illuminate\Support\Str; trait HasAdminSeo @@ -117,7 +119,7 @@ private static function excerpt(string $html, int $limit = 300): string // the limit: a fragment cut mid-phrase reads as a bug, a whole sentence // reads as a description. Half the limit, so that a single five-word // sentence is not served as the description. - if (preg_match('/^(.*[.!?])\s/us', mb_substr($text, 0, $limit), $m) + if (preg_match('/(.*[.!?])\s/', mb_substr($text, 0, $limit), $m) && mb_strlen($m[1]) >= intdiv($limit, 2)) { return $m[1]; } @@ -141,7 +143,7 @@ protected function getDefaultSeoDescription(): string // and is shown on the page itself. Without this branch sections went to // search results with no description at all, and Google made up the // snippet itself. - if (isset($this->description) && $this->description) { + if (! empty($this->description)) { return self::excerpt((string) $this->description); } @@ -183,23 +185,17 @@ public function getOgImage(): ?string */ protected function processSeoTemplate(string $template): string { - // Replace {field} placeholders with model values + // Replace {field} placeholders with model values; a related record + // gives its name, anything that is not text (a list, a file) leaves the + // placeholder as it is. return preg_replace_callback('/\{(\w+)\}/', function ($matches) { - $field = $matches[1]; + $value = $this->getAttribute($matches[1]); - if (isset($this->$field)) { - return strip_tags((string) $this->$field); + if ($value instanceof Model) { + $value = $value->getAttribute('name'); } - // Check relations - if (method_exists($this, $field)) { - $related = $this->$field; - if ($related && isset($related->name)) { - return $related->name; - } - } - - return $matches[0]; + return is_scalar($value) || $value instanceof Carbon ? strip_tags((string) $value) : $matches[0]; }, $template); } @@ -208,10 +204,9 @@ protected function processSeoTemplate(string $template): string */ public function updateSeoMeta(array $data): SeoMeta { - return $this->seoMeta()->updateOrCreate( - ['seoable_type' => static::class, 'seoable_id' => $this->id], - $data - ); + // The relation already pins the type (its morph alias, if the app has + // a morph map) and the id. + return $this->seoMeta()->updateOrCreate([], $data); } /** diff --git a/packages/admin/src/Traits/HasAdminSlug.php b/packages/admin/src/Traits/HasAdminSlug.php index 2d78ed91..84c0799f 100644 --- a/packages/admin/src/Traits/HasAdminSlug.php +++ b/packages/admin/src/Traits/HasAdminSlug.php @@ -125,10 +125,10 @@ public function generateSlug(): string */ protected function ensureUniqueSlug(string $slug, int $counter = 0): string { - $testSlug = $counter > 0 ? "{$slug}-{$counter}" : $slug; + $testSlug = $counter !== 0 ? "{$slug}-{$counter}" : $slug; $exists = static::where('code', $testSlug) - ->where('id', '!=', $this->id ?? 0) + ->where('id', '!=', $this->id) ->exists(); if ($exists) { @@ -188,7 +188,7 @@ protected function createSlugRecord(): void protected function updateSlugRecord(): void { $this->slugModel()->updateOrCreate( - ['sluggable_type' => static::class, 'sluggable_id' => $this->id], + [], [ 'slug' => $this->code, 'full_path' => $this->getFullPath(), diff --git a/packages/admin/src/Traits/HasAdminTabs.php b/packages/admin/src/Traits/HasAdminTabs.php index 5d46a95f..7e6aba71 100644 --- a/packages/admin/src/Traits/HasAdminTabs.php +++ b/packages/admin/src/Traits/HasAdminTabs.php @@ -87,7 +87,7 @@ public static function getFieldsGroupedByTabs(string $context = 'create'): array $sortedTabs = TabRegistry::sortTabs($visibleTabs); return [ - 'tabs' => array_values(array_map(fn ($t) => $t instanceof Tab ? $t->toArray() : $t, $sortedTabs)), + 'tabs' => array_map(fn ($t) => $t instanceof Tab ? $t->toArray() : $t, $sortedTabs), 'fields' => $grouped, ]; } diff --git a/packages/admin/src/Traits/HasSoftRelations.php b/packages/admin/src/Traits/HasSoftRelations.php index aa5af000..9631e92c 100644 --- a/packages/admin/src/Traits/HasSoftRelations.php +++ b/packages/admin/src/Traits/HasSoftRelations.php @@ -43,7 +43,7 @@ trait HasSoftRelations */ protected function softBelongsTo(string $related, ?string $foreignKey = null, ?string $ownerKey = null, ?string $relation = null): BelongsTo { - $relation ??= debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function']; + $relation ??= $this->guessBelongsToRelation(); if (Soft::available($related)) { return $this->belongsTo($related, $foreignKey, $ownerKey, $relation); @@ -61,7 +61,7 @@ protected function softBelongsTo(string $related, ?string $foreignKey = null, ?s */ protected function softBelongsToMany(string $related, string $table, ?string $foreignPivotKey = null, ?string $relatedPivotKey = null, ?string $relation = null): BelongsToMany { - $relation ??= debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function']; + $relation ??= $this->guessBelongsToRelation(); if (Soft::available($related)) { return $this->belongsToMany($related, $table, $foreignPivotKey, $relatedPivotKey, null, null, $relation); @@ -93,7 +93,7 @@ protected function softHasMany(string $related, ?string $foreignKey = null, ?str */ protected function softMorphTo(?string $name = null, ?string $type = null, ?string $id = null): MorphTo { - $name ??= debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function']; + $name ??= $this->guessBelongsToRelation(); [$type, $id] = $this->getMorphs(Str::snake($name), $type, $id); diff --git a/packages/admin/tests/Concerns/PinsExtensionSurface.php b/packages/admin/tests/Concerns/PinsExtensionSurface.php new file mode 100644 index 00000000..8adb4c87 --- /dev/null +++ b/packages/admin/tests/Concerns/PinsExtensionSurface.php @@ -0,0 +1,37 @@ + [$class, $method, $visibility]) { + $reflection = new ReflectionMethod($class, $method); + $is = $reflection->isPublic() ? 'public' : ($reflection->isProtected() ? 'protected' : 'private'); + + if ($is !== $visibility) { + $wrong[] = "{$name} is {$is}, not {$visibility}"; + } + } + + $this->assertSame([], $wrong); + } +} diff --git a/packages/admin/tests/Feature/AdminControllerExactnessTest.php b/packages/admin/tests/Feature/AdminControllerExactnessTest.php new file mode 100644 index 00000000..656f9707 --- /dev/null +++ b/packages/admin/tests/Feature/AdminControllerExactnessTest.php @@ -0,0 +1,774 @@ +set('app.locale', 'en'); + $app['config']->set('atrium.resources', [ + Post::class, Bulletin::class, Bundle::class, Chapter::class, Dossier::class, Memo::class, Page::class, Topic::class, + ]); + } + + private function panel(): static + { + return $this->actingAs($this->admin ??= $this->admin(), 'admin'); + } + + /** + * The controller of a fixture with its protected methods open. + * + * @param class-string $model + */ + private function controller(string $model): object + { + return new class($model) extends AdminController + { + public function __construct(string $model) + { + $this->model = $model; + } + + public function call(string $method, mixed ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } + + /** + * @param array $data + */ + public function pull(string $method, array &$data): mixed + { + return $this->{$method}($data); + } + }; + } + + /** + * @return list the tables the SQL of $callback read, one entry per query + */ + private function queriesTo(string $table, callable $callback): array + { + DB::flushQueryLog(); + DB::enableQueryLog(); + $callback(); + DB::disableQueryLog(); + + return array_values(array_filter( + array_column(DB::getQueryLog(), 'query'), + static fn (string $sql): bool => preg_match('/from ["`]'.$table.'["`]/i', $sql) === 1, + )); + } + + public function test_a_column_of_a_related_record_is_loaded_for_the_whole_page_at_once(): void + { + $first = Page::query()->create(['name' => ['en' => 'First']]); + $second = Page::query()->create(['name' => ['en' => 'Second']]); + Topic::query()->create(['name' => 'A', 'page_id' => $first->id]); + Topic::query()->create(['name' => 'B', 'page_id' => $second->id]); + + $reads = $this->queriesTo('pages', fn () => $this->panel()->get('/admin/topics')->assertOk()); + + $this->assertCount(1, $reads); + } + + public function test_a_list_without_related_columns_reads_no_other_table(): void + { + Post::query()->create(['name' => 'Apple']); + + $reads = $this->queriesTo('pages', fn () => $this->panel()->get('/admin/posts')->assertOk()); + + $this->assertSame([], $reads); + } + + public function test_search_looks_only_in_the_columns_that_say_they_are_searchable(): void + { + Post::query()->create(['name' => 'Apple', 'sort' => 7]); + Post::query()->create(['name' => 'Pear', 'sort' => 8]); + $asked = []; + Hook::filter('atrium.module.columns', static fn (array $columns, string $model): array => $model === Post::class + ? [ + ...$columns, + self::column(['name' => 'sort']), + self::column(['name' => null, 'searchable' => true]), + self::column(['name' => '', 'searchable' => true]), + self::column(['name' => 'sort', 'searchable' => false]), + ] + : $columns); + Hook::filter('atrium.query.search', static function (bool $handled, $query, string $column) use (&$asked): bool { + $asked[] = $column; + + return false; + }); + + $names = array_column( + $this->panel()->get('/admin/posts?search=Apple')->assertOk()->viewData('page')['props']['items']['data'], + 'name', + ); + + $this->assertSame(['Apple'], $names); + $this->assertSame(['name'], $asked); + } + + /** + * @param array $array + */ + private static function column(array $array): object + { + return new class($array) + { + /** @param array $array */ + public function __construct(private readonly array $array) {} + + /** @return array */ + public function toArray(): array + { + return $this->array; + } + }; + } + + public function test_a_search_that_matches_a_number_column_only_finds_nothing_when_it_is_not_searchable(): void + { + Post::query()->create(['name' => 'Apple', 'sort' => 777]); + + $names = array_column( + $this->panel()->get('/admin/posts?search=777')->assertOk()->viewData('page')['props']['items']['data'], + 'name', + ); + + $this->assertSame([], $names); + } + + public function test_the_create_form_preselects_the_section_it_was_opened_from(): void + { + $section = Post::query()->create(['name' => 'Section']); + + $this->panel()->get("/admin/chapters/create?section_id={$section->id}")->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('fields.2.name', 'section_id') + ->where('fields.2.default', $section->id) + ->where('fieldsByTab.params.2.default', $section->id)); + } + + public function test_the_create_form_ignores_a_section_that_is_not_there(): void + { + Post::query()->create(['name' => 'Section']); + + foreach (['', '?section_id=0', '?section_id=-1', '?section_id=999', '?section_id=abc'] as $query) { + $reads = $this->queriesTo('posts', function () use ($query): void { + $this->panel()->get('/admin/chapters/create'.$query)->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page->where('fields.2.default', null)); + }); + + // Nothing can be asked about section 0 or a negative one. + if (in_array($query, ['', '?section_id=0', '?section_id=-1', '?section_id=abc'], true)) { + $this->assertSame([], $reads, $query); + } + } + } + + public function test_a_module_without_sections_never_preselects_one(): void + { + Hook::filter('atrium.module.fields', static fn (array $fields, string $model): array => $model === Post::class + ? [...$fields, NumberField::make('section_id')->label('Section')] + : $fields); + + $this->panel()->get('/admin/posts/create?section_id=1')->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page->where('fields.3.name', 'section_id')->where('fields.3.default', null)); + } + + public function test_a_controller_whose_form_has_no_plain_field_list_still_gets_its_defaults(): void + { + $controller = new class(Bulletin::class) extends AdminController + { + public function __construct(string $model) + { + $this->model = $model; + } + + protected function prepareFormData(string $context, $item = null): array + { + return ['fieldsByTab' => ['params' => [['name' => 'name'], ['name' => 'sort']]]]; + } + }; + + $request = Request::create('/admin/bulletins/create?name=Apple', 'GET'); + $request->headers->set('X-Inertia', 'true'); + $props = $controller->create($request)->toResponse($request)->getData(true)['props']; + + $this->assertSame([['name' => 'name', 'default' => 'Apple'], ['name' => 'sort']], $props['fieldsByTab']['params']); + $this->assertArrayNotHasKey('fields', $props); + } + + public function test_a_module_that_cannot_be_created_here_still_saves_edits_and_the_reverse(): void + { + $dossier = Dossier::query()->create(['name' => 'Old']); + $memo = Memo::query()->create(['name' => 'Old']); + + $this->panel()->post('/admin/dossiers', ['name' => 'New'])->assertForbidden(); + $this->panel()->put("/admin/dossiers/{$dossier->id}", ['name' => 'Changed'])->assertRedirect('/admin/dossiers'); + $this->panel()->post('/admin/memos', ['name' => 'New'])->assertRedirect('/admin/memos'); + $this->panel()->put("/admin/memos/{$memo->id}", ['name' => 'Changed'])->assertForbidden(); + + $this->assertSame('Changed', $dossier->fresh()->name); + $this->assertSame('Old', $memo->fresh()->name); + $this->assertSame(['Changed', 'Old', 'New'], Post::query()->orderBy('id')->pluck('name')->all()); + } + + public function test_an_empty_password_on_edit_keeps_the_stored_one(): void + { + $other = AdminUser::query()->create(['name' => 'Other', 'email' => 'other@example.com', 'password' => 'secret-password', 'is_active' => true]); + $hash = $other->password; + + $this->panel()->put("/admin/users/{$other->id}", ['name' => 'Renamed', 'email' => 'other@example.com', 'password' => '']) + ->assertSessionHasNoErrors(); + + $other->refresh(); + $this->assertSame('Renamed', $other->name); + $this->assertSame($hash, $other->password); + } + + public function test_a_save_reads_the_fields_of_the_module_once(): void + { + $calls = 0; + Hook::filter('atrium.module.fields', static function (array $fields) use (&$calls): array { + $calls++; + + return $fields; + }); + + $this->panel()->post('/admin/posts', ['name' => 'Apple'])->assertSessionHasNoErrors(); + + $this->assertSame(1, $calls); + } + + public function test_the_fields_of_a_form_are_a_list(): void + { + $controller = $this->controller(Chapter::class); + + $create = $controller->call('contextFields', 'create'); + + $this->assertTrue(array_is_list($create)); + $this->assertCount(4, $create); + } + + public function test_the_fields_shown_only_on_one_side_are_kept_for_that_side(): void + { + Hook::filter('atrium.module.fields', static fn (array $fields, string $model): array => $model === Post::class + ? [NumberField::make('only_create')->onlyOnCreate(), ...$fields, NumberField::make('only_edit')->onlyOnEdit()] + : $fields); + $controller = $this->controller(Post::class); + + $this->assertSame(['only_create', 'name', 'active', 'sort'], array_map(static fn ($field) => $field->getName(), $controller->call('contextFields', 'create'))); + $this->assertSame(['name', 'active', 'sort', 'only_edit'], array_map(static fn ($field) => $field->getName(), $controller->call('contextFields', 'edit'))); + } + + public function test_unique_rules_are_rewritten_to_skip_the_record_being_edited(): void + { + $topic = Topic::query()->create(['name' => 'Mine']); + $controller = $this->controller(Topic::class); + $unique = static fn (string $column): string => (string) Rule::unique('topics', $column)->ignore($topic->getKey(), 'id'); + + $rules = $controller->call('ignoreCurrentRecord', [ + 'name' => 'required|unique:topics', + 'code' => ['nullable', 'unique:topics,NULL'], + 'alias' => 'unique:topics,null', + 'slug' => 'unique:topics,note', + 'scoped' => ['unique:topics,slug,0', 'unique:topics'], + 'plain' => 'required|max:5', + 'listed' => ['required', 'max:5'], + ], $topic); + + $stringify = static fn (array $list): array => array_map(static fn ($rule): string => (string) $rule, $list); + + $this->assertSame(['required', $unique('name')], $stringify($rules['name'])); + $this->assertSame(['nullable', $unique('code')], $stringify($rules['code'])); + $this->assertSame([$unique('alias')], $stringify($rules['alias'])); + $this->assertSame([$unique('note')], $stringify($rules['slug'])); + $this->assertSame(['unique:topics,slug,0', $unique('scoped')], $stringify($rules['scoped'])); + $this->assertSame('required|max:5', $rules['plain']); + $this->assertSame(['required', 'max:5'], $rules['listed']); + } + + public function test_the_rules_of_a_record_that_is_not_there_yet_are_left_as_written(): void + { + $controller = $this->controller(Topic::class); + $rules = ['name' => 'required|unique:topics', 'code' => ['unique:topics,slug']]; + + $this->assertSame($rules, $controller->call('ignoreCurrentRecord', $rules, null)); + $this->assertSame($rules, $controller->call('ignoreCurrentRecord', $rules, new Topic)); + } + + public function test_a_unique_rule_looks_only_at_the_current_site_for_the_module_s_own_table(): void + { + $controller = $this->controller(Note::class); + + $own = (string) $controller->call('uniqueRule', 'notes', 'code', null); + $foreign = (string) $controller->call('uniqueRule', 'pages', 'code', null); + + $this->assertStringContainsString('site_id', $own); + $this->assertStringNotContainsString('site_id', $foreign); + $this->assertStringNotContainsString('site_id', (string) $this->controller(Topic::class)->call('uniqueRule', 'topics', 'code', null)); + } + + public function test_every_language_of_a_translated_field_gets_its_rules(): void + { + Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200]); + $controller = $this->controller(Page::class); + $field = TextField::make('name')->rules(['unique:pages', 'unique:pages,slug', 'unique:pages,NULL', 'unique:pages,null', 'regex:/^a,b$/']); + $uniques = static fn (array $list): array => array_values(array_map( + static fn ($rule): string => (string) $rule, + array_filter($list, static fn ($rule): bool => is_object($rule) || str_starts_with($rule, 'unique:')), + )); + + $rules = $controller->call('translatableRules', $field, Request::create('/'), 'create', null); + + $this->assertSame(['name', 'name.en', 'name.de'], array_keys($rules)); + $this->assertSame(['nullable', 'array'], $rules['name']); + foreach (['en', 'de'] as $code) { + $this->assertSame( + ["unique:pages,name->{$code},NULL,id", "unique:pages,slug->{$code},NULL,id", "unique:pages,name->{$code},NULL,id", "unique:pages,name->{$code},NULL,id"], + $uniques($rules["name.{$code}"]), + ); + $this->assertContains('regex:/^a,b$/', $rules["name.{$code}"]); + } + } + + public function test_a_unique_language_rule_ignores_the_record_being_edited(): void + { + $page = Page::query()->create(['name' => ['en' => 'Home']]); + $field = TextField::make('name')->rules(['unique:pages']); + + $rules = $this->controller(Page::class)->call('translatableRules', $field, Request::create('/'), 'edit', $page); + + $this->assertSame( + (string) Rule::unique('pages', 'name->en')->ignore($page->getKey(), 'id'), + (string) array_values(array_filter($rules['name.en'], 'is_object'))[0], + ); + } + + public function test_a_language_other_than_the_default_may_stay_empty_whatever_the_rules_say(): void + { + Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200]); + $controller = $this->controller(Page::class); + $ask = static fn (TextField $field): array => $controller->call('translatableRules', $field, Request::create('/'), 'create', null); + + $required = $ask(TextField::make('name')->required()->rules(['max:5'])); + $declared = $ask(TextField::make('name')->required()->rules(['nullable', 'max:5'])); + $optional = $ask(TextField::make('name')->rules(['max:5'])); + + $this->assertContains('required', $required['name.en']); + $this->assertNotContains('required', $required['name.de']); + $this->assertSame('nullable', $required['name.de'][0]); + $this->assertSame(1, array_count_values($required['name.de'])['nullable']); + + $this->assertContains('required', $declared['name.en']); + $this->assertNotContains('required', $declared['name.de']); + $this->assertSame(1, array_count_values($declared['name.de'])['nullable']); + $this->assertTrue(array_is_list($declared['name.de'])); + + $this->assertNotContains('required', $optional['name.en']); + $this->assertSame(1, array_count_values($optional['name.de'])['nullable']); + $this->assertTrue(array_is_list($optional['name.de'])); + } + + public function test_a_many_to_many_field_is_pulled_out_of_the_data_whatever_comes_before_it(): void + { + $controller = $this->controller(Bundle::class); + $data = ['name' => 'Box', 'extras' => [9], 'topics' => ['5', '', null, 0, 6], 'other' => 1]; + + $relations = $controller->pull('extractRelationValues', $data); + + $this->assertSame(['topics' => ['5', 0, 6]], $relations); + $this->assertSame(['name' => 'Box', 'other' => 1], $data); + } + + public function test_every_many_to_many_field_with_a_relation_is_pulled_out(): void + { + $controller = $this->controller(Bundle::class); + $data = ['name' => 'Box', 'posts' => 3, 'topics' => [4, 5]]; + + $relations = $controller->pull('extractRelationValues', $data); + + $this->assertSame(['posts' => [3], 'topics' => [4, 5]], $relations); + $this->assertSame(['name' => 'Box'], $data); + } + + public function test_the_relations_of_a_module_are_the_many_to_many_fields_that_have_a_method(): void + { + $this->assertSame(['posts', 'topics'], $this->controller(Bundle::class)->call('getBelongsToManyRelations')); + $this->assertSame([], $this->controller(Post::class)->call('getBelongsToManyRelations')); + } + + public function test_the_edit_form_holds_the_ids_of_a_many_to_many_field(): void + { + $first = Post::query()->create(['name' => 'One']); + $second = Post::query()->create(['name' => 'Two']); + $bundle = Bundle::query()->create(['name' => 'Box']); + $bundle->posts()->sync([$first->id, $second->id]); + + $this->panel()->get("/admin/bundles/{$bundle->id}/edit")->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('item.posts', [$first->id, $second->id]) + ->where('item.topics', []) + ->missing('item.extras')); + } + + public function test_the_ids_of_a_many_to_many_field_are_saved_with_the_record(): void + { + $post = Post::query()->create(['name' => 'One']); + + $this->panel()->post('/admin/bundles', ['name' => 'Box', 'posts' => [$post->id], 'extras' => [$post->id]])->assertSessionHasNoErrors(); + + $bundle = Bundle::query()->sole(); + $this->assertSame([$post->id], $bundle->posts()->pluck('posts.id')->all()); + $this->assertSame([], $bundle->topics()->pluck('topics.id')->all()); + } + + public function test_the_form_is_titled_for_the_record_or_for_a_new_one(): void + { + $post = Post::query()->create(['name' => 'Apple']); + $chapter = Chapter::query()->create(['name' => 'Intro']); + $posts = $this->controller(Post::class); + $chapters = $this->controller(Chapter::class); + + $edit = $posts->call('prepareFormData', 'edit', $post); + $create = $posts->call('prepareFormData', 'create'); + + $this->assertSame('Edit: Apple', $edit['title']); + $this->assertSame('Apple', $edit['itemTitle']); + $this->assertSame('Create Posts', $create['title']); + $this->assertNull($create['itemTitle']); + $this->assertNull($create['item']); + $this->assertFalse($edit['useTabs']); + $this->assertFalse($create['useTabs']); + $this->assertArrayNotHasKey('tabs', $edit); + $this->assertSame('Posts', $edit['adminLabel']); + + $tabbed = $chapters->call('prepareFormData', 'edit', $chapter); + $this->assertTrue($tabbed['useTabs']); + $this->assertSame('Edit: Intro', $tabbed['title']); + $this->assertSame('Intro', $tabbed['itemTitle']); + $this->assertSame('Create Chapters', $chapters->call('prepareFormData', 'create')['title']); + $this->assertNull($chapters->call('prepareFormData', 'create')['itemTitle']); + $this->assertArrayHasKey('tabs', $tabbed); + $this->assertSame(['params'], array_keys($tabbed['fieldsByTab'])); + $this->assertCount(4, $tabbed['fields']); + } + + public function test_the_fields_of_a_module_that_chooses_them_itself_are_the_ones_it_chooses(): void + { + $this->assertSame( + ['name', 'cover'], + array_map(static fn ($field): string => $field->getName(), AdminController::fieldsOf(Brochure::class)), + ); + $this->assertSame( + ['name', 'active', 'sort'], + array_map(static fn ($field): string => $field->getName(), AdminController::fieldsOf(Post::class)), + ); + } + + public function test_a_file_sent_with_a_value_of_the_same_name_is_checked_as_a_file(): void + { + Hook::filter('atrium.module.fields', static fn (array $fields, string $model): array => $model === Post::class + ? [...$fields, ImageField::make('photo')->label('Photo')] + : $fields); + $controller = $this->controller(Post::class); + $request = Request::create('/', 'POST', ['photo' => 'stored/path.jpg'], [], ['photo' => UploadedFile::fake()->image('a.jpg')]); + + $rules = $controller->call('resolveRules', $request, 'create', null)['photo']; + + $this->assertContains('image', $rules); + $this->assertNotContains('string', $rules); + + $stored = $controller->call('resolveRules', Request::create('/', 'POST', ['photo' => 'stored/path.jpg']), 'create', null)['photo']; + $this->assertContains('string', $stored); + $this->assertNotContains('image', $stored); + } + + public function test_the_rules_of_the_fields_after_a_translated_one_are_derived_too(): void + { + $rules = $this->controller(Page::class)->call('resolveRules', Request::create('/', 'POST'), 'create', null); + + $this->assertSame(['name', 'name.en', 'code', 'code.en', 'sort'], array_keys($rules)); + } + + public function test_a_label_in_english_is_lowercased_with_its_accents_and_in_another_language_kept(): void + { + Hook::filter('atrium.module.fields', static fn (array $fields, string $model): array => $model === Post::class + ? [...$fields, TextField::make('title')->label('ÜBER Äpfel')] + : $fields); + $controller = $this->controller(Post::class); + + $this->assertSame('über äpfel', $controller->call('validationAttributes', 'create')['title']); + + $this->app->setLocale('de'); + $this->assertSame('ÜBER Äpfel', $controller->call('validationAttributes', 'create')['title']); + } + + public function test_a_field_without_a_label_gets_no_name_and_does_not_hide_the_fields_after_it(): void + { + Hook::filter('atrium.module.fields', static fn (array $fields, string $model): array => $model === Post::class + ? [...$fields, TextField::make('blank'), TextField::make('title')->label('Heading')] + : $fields); + + $attributes = $this->controller(Post::class)->call('validationAttributes', 'create'); + + $this->assertArrayNotHasKey('blank', $attributes); + $this->assertSame('heading', $attributes['title']); + } + + public function test_the_form_uses_tabs_only_for_a_model_that_has_both_the_tab_grouping_and_the_switch(): void + { + $switchOnly = new class extends Model + { + public static function getAdminLabel(): string + { + return 'Switch'; + } + + public static function usesTabs(): bool + { + return true; + } + + public static function getAdministrationFields(): array + { + return [TextField::make('name')]; + } + }; + $groupingOnly = new class extends Model + { + public static function getAdminLabel(): string + { + return 'Grouping'; + } + + public static function getFieldsGroupedByTabs(string $context): array + { + throw new LogicException('Grouping alone does not turn tabs on.'); + } + + public static function getAdministrationFields(): array + { + return [TextField::make('name')]; + } + }; + + foreach ([$switchOnly, $groupingOnly] as $model) { + $form = $this->controller($model::class)->call('prepareFormData', 'create'); + + $this->assertFalse($form['useTabs']); + $this->assertArrayNotHasKey('fieldsByTab', $form); + } + + $this->assertTrue($this->controller(Chapter::class)->call('prepareFormData', 'create')['useTabs'] ?? false); + } + + public function test_translations_in_a_language_that_is_not_active_are_dropped_from_every_translated_field(): void + { + $controller = $this->controller(Page::class); + $request = Request::create('/', 'POST', ['code' => ['en' => 'home', 'fr' => 'accueil'], 'sort' => 3]); + + $data = $controller->call('submittedData', $request, 'create', new Page); + + $this->assertSame(['code' => ['en' => 'home'], 'sort' => 3], $data); + + $none = $controller->call('submittedData', Request::create('/', 'POST', ['name' => ['fr' => 'x'], 'code' => ['en' => 'home']]), 'create', new Page); + $this->assertSame(['code' => ['en' => 'home']], $none); + } + + public function test_the_fields_of_every_tab_are_serialized(): void + { + $result = $this->controller(Post::class)->call('serializeFieldsByTab', [ + 'params' => [TextField::make('a')->label('A')], + 'seo' => [TextField::make('b')->label('B'), TextField::make('c')->label('C')], + ], 'create'); + + $this->assertSame(['params', 'seo'], array_keys($result)); + $this->assertSame(['a'], array_column($result['params'], 'name')); + $this->assertSame(['b', 'c'], array_column($result['seo'], 'name')); + } + + public function test_the_seo_values_of_a_form_are_pulled_out_whichever_of_them_come_first(): void + { + $controller = $this->controller(Article::class); + $data = ['name' => 'Hello', 'seo_description' => 'About', 'seo_title' => 'Title']; + + $seo = $controller->pull('extractSeoValues', $data); + + $this->assertSame(['title' => 'Title', 'description' => 'About'], $seo); + $this->assertSame(['name' => 'Hello'], $data); + + $partial = ['name' => 'Hello', 'seo_description' => 'About']; + $this->assertSame(['description' => 'About'], $controller->pull('extractSeoValues', $partial)); + $this->assertSame(['name' => 'Hello'], $partial); + + $none = ['name' => 'Hello']; + $this->assertSame([], $controller->pull('extractSeoValues', $none)); + $this->assertSame([], $this->controller(Post::class)->pull('extractSeoValues', $data)); + } + + public function test_seo_is_saved_only_by_a_record_that_can_read_and_write_it(): void + { + $controller = $this->controller(Article::class); + $writes = []; + $both = new class($writes) extends Model + { + public function __construct(private array &$writes = []) + { + parent::__construct(); + } + + public function seoMeta(): object + { + return new class + { + public function exists(): bool + { + return true; + } + }; + } + + public function updateSeoMeta(array $data): void + { + $this->writes[] = $data; + } + }; + $readOnly = new class extends Model + { + public function seoMeta(): object + { + throw new LogicException('Nothing to write with.'); + } + }; + $writeOnly = new class extends Model + { + public function updateSeoMeta(array $data): void + { + throw new LogicException('Nothing to read from.'); + } + }; + + $controller->call('persistSeoValues', $both, ['title' => 'T']); + $controller->call('persistSeoValues', $both, []); + $controller->call('persistSeoValues', $readOnly, ['title' => 'T']); + $controller->call('persistSeoValues', $writeOnly, ['title' => 'T']); + + $this->assertSame([['title' => 'T']], $writes); + } + + public function test_a_related_column_shows_the_default_language_only_of_a_record_that_translates_it(): void + { + $both = new class extends Model + { + public function isTranslatableAttribute(string $key): bool + { + return $key === 'name'; + } + + public function getTranslation(string $key, string $language): string + { + return "T-{$key}-{$language}"; + } + }; + $other = new class extends Model + { + public function isTranslatableAttribute(string $key): bool + { + return false; + } + + public function getTranslation(string $key, string $language): string + { + return "T-{$key}-{$language}"; + } + }; + $asks = new class extends Model + { + public function isTranslatableAttribute(string $key): bool + { + return true; + } + }; + $reads = new class extends Model + { + public function getTranslation(string $key, string $language): string + { + return "T-{$key}-{$language}"; + } + }; + $plain = new class extends Model {}; + $controller = $this->controller(Topic::class); + + $shown = static function (Model $related) use ($controller): mixed { + $related->setRawAttributes(['name' => 'Raw']); + $topic = new Topic; + $topic->setRelation('page', $related); + + return $controller->call('listRow', $topic, ['page.name'])['page.name']; + }; + + $this->assertSame('T-name-en', $shown($both)); + $this->assertSame('Raw', $shown($other)); + $this->assertSame('Raw', $shown($asks)); + $this->assertSame('Raw', $shown($reads)); + $this->assertSame('Raw', $shown($plain)); + } + + public function test_the_actions_of_a_record_reach_the_page_as_plain_arrays(): void + { + $actions = $this->controller(Chapter::class)->call('resourceProps')['actions']; + + $this->assertCount(2, $actions); + $this->assertContainsOnlyArray($actions); + $this->assertSame('Subchapter', $actions[0]['label']); + } +} diff --git a/packages/admin/tests/Feature/AdminTraitsTest.php b/packages/admin/tests/Feature/AdminTraitsTest.php index 9335e846..4e66b2a7 100644 --- a/packages/admin/tests/Feature/AdminTraitsTest.php +++ b/packages/admin/tests/Feature/AdminTraitsTest.php @@ -11,6 +11,7 @@ use Atrium\Admin\Fields\Field; use Atrium\Admin\Fields\TextField; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Handbook; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; @@ -20,6 +21,8 @@ final class AdminTraitsTest extends TestCase { + use PinsExtensionSurface; + /** * @param array> $grouped * @return array> diff --git a/packages/admin/tests/Feature/AdminUserExactnessTest.php b/packages/admin/tests/Feature/AdminUserExactnessTest.php new file mode 100644 index 00000000..d9ebd7e7 --- /dev/null +++ b/packages/admin/tests/Feature/AdminUserExactnessTest.php @@ -0,0 +1,175 @@ +create(['name' => 'Ann', 'email' => 'ann@example.com', 'password' => 'long-enough-1', ...$attributes]); + } + + /** + * @return array + */ + private function fields(): array + { + $fields = []; + + foreach (AdminUser::getAdministrationFields() as $field) { + $fields[$field->getName()] = $field; + } + + return $fields; + } + + private function errors(array $rules, array $data): array + { + return array_keys(Validator::make($data, $rules)->errors()->toArray()); + } + + public function test_a_verification_date_comes_back_as_a_date(): void + { + $user = $this->user(['email_verified_at' => '2026-03-04 05:06:07']); + $user->forceFill(['email_verified_at' => '2026-03-04 05:06:07'])->save(); + + $this->assertInstanceOf(CarbonInterface::class, $user->fresh()->email_verified_at); + $this->assertSame('2026-03-04 05:06:07', $user->fresh()->email_verified_at->format('Y-m-d H:i:s')); + } + + public function test_the_fields_of_one_site_install(): void + { + $fields = $this->fields(); + + $this->assertSame(['name', 'email', 'password', 'password_confirmation', 'is_active'], array_keys($fields)); + $this->assertTrue($fields['name']->isRequired()); + $this->assertSame(255, $fields['name']->getMaxLength()); + $this->assertContains('min:8', $fields['password']->getValidationRules()); + $this->assertNotContains('min:7', $fields['password']->getValidationRules()); + $this->assertNotContains('min:9', $fields['password']->getValidationRules()); + $this->assertTrue($fields['is_active']->getDefault()); + } + + public function test_the_site_limit_lists_the_sites_by_id(): void + { + $second = Site::query()->create(['code' => 'de', 'name' => 'Deutschland', 'domains' => ['example.de']]); + $main = Site::query()->where('code', 'main')->sole(); + + $fields = $this->fields(); + + $this->assertSame(['name', 'email', 'password', 'password_confirmation', 'is_active', 'site_ids'], array_keys($fields)); + $options = $fields['site_ids']->toArray()['options']; + $this->assertEquals([ + ['value' => (string) $main->id, 'label' => $main->name], + ['value' => (string) $second->id, 'label' => 'Deutschland'], + ], $options); + } + + public function test_only_a_superadmin_sees_the_rights_fields(): void + { + $this->assertArrayNotHasKey('roles', $this->fields()); + + $admin = $this->user(); + $admin->forceFill(['is_superadmin' => true])->save(); + $this->actingAs($admin, 'admin'); + $fields = $this->fields(); + + $this->assertSame(['name', 'email', 'password', 'password_confirmation', 'is_active', 'is_superadmin', 'roles'], array_keys($fields)); + } + + public function test_the_create_rules_are_these(): void + { + $this->assertEquals([ + 'name' => ['required', 'string', 'max:255'], + 'email' => ['required', 'string', 'email', 'max:255', 'unique:admin_users'], + 'password' => ['required', 'string', 'min:8', 'confirmed'], + 'is_active' => ['nullable', 'boolean'], + 'is_superadmin' => ['nullable', 'boolean'], + 'roles' => ['nullable', 'array'], + 'roles.*' => ['integer', Rule::exists('admin_roles', 'id')], + 'site_ids' => ['nullable', 'array'], + 'site_ids.*' => [Rule::in([1])], + ], AdminUser::getCreateValidationRules()); + } + + public function test_the_update_rules_are_these(): void + { + $this->assertEquals([ + 'name' => ['required', 'string', 'max:255'], + 'email' => ['required', 'string', 'email', 'max:255'], + 'password' => ['nullable', 'string', 'min:8', 'confirmed'], + 'is_active' => ['nullable', 'boolean'], + 'is_superadmin' => ['nullable', 'boolean'], + 'roles' => ['nullable', 'array'], + 'roles.*' => ['integer', Rule::exists('admin_roles', 'id')], + 'site_ids' => ['nullable', 'array'], + 'site_ids.*' => [Rule::in([1])], + ], AdminUser::getUpdateValidationRules()); + } + + public function test_the_rules_accept_the_ticked_sites_as_the_form_sends_them(): void + { + foreach ([AdminUser::getCreateValidationRules(), AdminUser::getUpdateValidationRules()] as $rules) { + $good = ['name' => 'Ann', 'email' => 'new@example.com', 'password' => 'long-enough-1', 'password_confirmation' => 'long-enough-1']; + + $this->assertSame([], $this->errors($rules, $good + ['site_ids' => ['1']])); + $this->assertSame(['site_ids.0'], $this->errors($rules, $good + ['site_ids' => ['2']])); + $this->assertSame(['roles.0'], $this->errors($rules, $good + ['roles' => ['x']])); + $this->assertSame(['roles.0'], $this->errors($rules, $good + ['roles' => [99]])); + } + } + + public function test_a_blank_form_names_what_is_missing(): void + { + $this->assertSame(['name', 'email', 'password'], $this->errors(AdminUser::getCreateValidationRules(), [])); + $this->assertSame(['name', 'email'], $this->errors(AdminUser::getUpdateValidationRules(), [])); + $this->assertSame(['is_active', 'is_superadmin'], $this->errors(AdminUser::getUpdateValidationRules(), ['name' => 'a', 'email' => 'a@b.test', 'is_active' => 'x', 'is_superadmin' => 'x'])); + } + + public function test_the_sites_ticked_on_an_account_may_be_stored_as_numbers(): void + { + $second = Site::query()->create(['code' => 'de', 'name' => 'Deutschland', 'domains' => ['example.de']]); + $main = Site::query()->where('code', 'main')->sole(); + + $user = $this->user(); + $this->assertSame([$main->id, $second->id], $user->allowedSites()->pluck('id')->all(), 'No ticks: every site.'); + + $user->forceFill(['site_ids' => [$second->id]])->save(); + $this->assertSame([$second->id], $user->fresh()->allowedSites()->pluck('id')->all()); + + $user->forceFill(['site_ids' => [(string) $main->id]])->save(); + $this->assertSame([$main->id], $user->fresh()->allowedSites()->pluck('id')->all()); + } + + public function test_the_permissions_of_all_the_roles_add_up_and_a_role_without_any_adds_nothing(): void + { + $user = $this->user(); + $user->roles()->attach([ + AdminRole::query()->create(['name' => 'A', 'permissions' => ['x.read', 'x.write']])->id, + AdminRole::query()->create(['name' => 'B', 'permissions' => ['x.read', 'y.read']])->id, + AdminRole::query()->create(['name' => 'C', 'permissions' => []])->id, + ]); + + $this->assertSame(['x.read', 'x.write', 'y.read'], $user->fresh()->adminPermissions()); + } +} diff --git a/packages/admin/tests/Feature/ApiDocumentationExactTest.php b/packages/admin/tests/Feature/ApiDocumentationExactTest.php new file mode 100644 index 00000000..db54d4c9 --- /dev/null +++ b/packages/admin/tests/Feature/ApiDocumentationExactTest.php @@ -0,0 +1,178 @@ +set('app.url', 'http://shop.test'); + $app['config']->set('atrium.resources', [Bare::class, ApiEdges::class]); + } + + private function encoded(mixed $value): string + { + return (string) json_encode($value); + } + + public function test_a_module_without_required_fields_has_no_required_list(): void + { + $schemas = app(ApiDocumentation::class)->openApi(['bares'])['components']['schemas']; + + $this->assertSame( + $this->encoded(['type' => 'object', 'properties' => ['name' => ['type' => 'string', 'maxLength' => 65535, 'description' => 'Name']]]), + $this->encoded($schemas['Bares']), + ); + $this->assertSame( + $this->encoded(['type' => 'object', 'properties' => ['name' => ['type' => 'string', 'maxLength' => 65535, 'description' => 'Name']]]), + $this->encoded($schemas['BaresChanges']), + ); + $this->assertSame( + $this->encoded(['allOf' => [ + ['type' => 'object', 'properties' => [ + 'id' => ['type' => 'integer'], + 'admin_url' => ['type' => 'string'], + 'public_url' => ['type' => ['string', 'null']], + ]], + ['$ref' => '#/components/schemas/Bares'], + ]]), + $this->encoded($schemas['BaresRecord']), + ); + } + + public function test_the_paths_of_a_module_in_full(): void + { + $errors = [ + '401' => ['description' => 'No valid token'], + '403' => ['description' => 'The token has no ability for the module'], + '404' => ['description' => 'No such module or record'], + ]; + $json = static fn (array $schema): array => ['content' => ['application/json' => ['schema' => $schema]]]; + $record = $json(['type' => 'object', 'properties' => ['data' => ['$ref' => '#/components/schemas/BaresRecord']]]); + $id = ['name' => 'id', 'in' => 'path', 'required' => true, 'schema' => ['type' => 'integer']]; + + $paths = app(ApiDocumentation::class)->openApi(['bares'])['paths']; + + $this->assertSame(['/bares', '/bares/{id}', '/files'], array_keys($paths)); + + $this->assertSame($this->encoded([ + 'get' => [ + 'operationId' => 'list_bares', + 'summary' => 'Bare: list', + 'tags' => ['Bare'], + 'parameters' => [ + ['name' => 'page', 'in' => 'query', 'schema' => ['type' => 'integer']], + ['name' => 'per_page', 'in' => 'query', 'schema' => ['type' => 'integer', 'maximum' => 100]], + ['name' => 'search', 'in' => 'query', 'schema' => ['type' => 'string']], + ['name' => 'filter', 'in' => 'query', 'style' => 'deepObject', 'explode' => true, 'schema' => ['type' => 'object']], + ['name' => 'sort', 'in' => 'query', 'schema' => ['type' => 'string']], + ['name' => 'direction', 'in' => 'query', 'schema' => ['type' => 'string', 'enum' => ['asc', 'desc']]], + ], + 'responses' => ['200' => ['description' => 'List page'] + $json(['type' => 'object', 'properties' => [ + 'data' => ['type' => 'array', 'items' => ['$ref' => '#/components/schemas/BaresRecord']], + 'meta' => ['type' => 'object'], + ]])] + $errors, + ], + 'post' => [ + 'operationId' => 'create_bares', + 'summary' => 'Bare: create', + 'tags' => ['Bare'], + 'requestBody' => ['required' => true] + $json(['$ref' => '#/components/schemas/Bares']), + 'responses' => ['201' => ['description' => 'Created'] + $record, '422' => ['description' => 'Fields failed validation']] + $errors, + ], + ]), $this->encoded($paths['/bares'])); + + $this->assertSame($this->encoded([ + 'get' => [ + 'operationId' => 'get_bares', + 'summary' => 'Bare: record', + 'tags' => ['Bare'], + 'parameters' => [$id], + 'responses' => ['200' => ['description' => 'Record'] + $record] + $errors, + ], + 'patch' => [ + 'operationId' => 'update_bares', + 'summary' => 'Bare: update the fields sent', + 'tags' => ['Bare'], + 'parameters' => [$id], + 'requestBody' => ['required' => true] + $json(['$ref' => '#/components/schemas/BaresChanges']), + 'responses' => ['200' => ['description' => 'Updated'] + $record, '422' => ['description' => 'Fields failed validation']] + $errors, + ], + 'delete' => [ + 'operationId' => 'delete_bares', + 'summary' => 'Bare: delete', + 'tags' => ['Bare'], + 'parameters' => [$id], + 'responses' => ['204' => ['description' => 'Deleted'], '409' => ['description' => 'The record cannot be deleted']] + $errors, + ], + ]), $this->encoded($paths['/bares/{id}'])); + + $this->assertSame($this->encoded(['post' => [ + 'operationId' => 'upload_file', + 'summary' => 'Upload a file; returns a url for an image field or a gallery', + 'requestBody' => ['required' => true, 'content' => ['multipart/form-data' => ['schema' => [ + 'type' => 'object', + 'properties' => ['file' => ['type' => 'string', 'format' => 'binary']], + 'required' => ['file'], + ]]]], + 'responses' => ['200' => ['description' => 'File uploaded'] + $json(['type' => 'object', 'properties' => [ + 'url' => ['type' => 'string'], + 'path' => ['type' => 'string'], + ]])] + $errors, + ]]), $this->encoded($paths['/files'])); + } + + public function test_a_translatable_field_keeps_its_own_note_and_is_typed_by_its_plain_value(): void + { + Hook::filter('atrium.module.translatable', static fn (array $names): array => [...$names, 'starts', 'limit', 'name']); + + $fields = collect(app(ApiDocumentation::class)->modules(['api_edges'])['api_edges']['fields'])->keyBy('name'); + $translatable = ' Translatable: a plain value sets the default language (en), an object {"en": …} sets several. Read back as that object.'; + + $this->assertSame('Edit only. Date: YYYY-MM-DD.'.$translatable, $fields['starts']['note']); + $this->assertSame('Create only.'.$translatable, $fields['limit']['note']); + $this->assertSame(trim($translatable), $fields['name']['note']); + + $markdown = app(ApiDocumentation::class)->markdown(['api_edges']); + $this->assertStringContainsString('| `limit` | number per language |', $markdown); + $this->assertStringContainsString('| `starts` | date per language |', $markdown); + $this->assertStringContainsString('| `name` | string per language |', $markdown); + } + + public function test_the_note_of_a_field_comes_before_the_text_the_api_adds(): void + { + $fields = collect(app(ApiDocumentation::class)->modules(['api_edges'])['api_edges']['fields'])->keyBy('name'); + $this->assertSame(['name', 'agree', 'tags', 'section_id', 'limit', 'starts'], $fields->keys()->all()); + $this->assertSame([0, 1, 2, 3, 4, 5], array_keys(app(ApiDocumentation::class)->modules(['api_edges'])['api_edges']['fields']), 'A list, though a field before them is left out.'); + $this->assertSame('Create only.', $fields['limit']['note']); + $this->assertSame('Edit only. Date: YYYY-MM-DD.', $fields['starts']['note']); + + $this->assertSame('Create only. Send true/false; the response contains "Y" or null.', $fields['agree']['note']); + $this->assertSame('Edit only. List of values.', $fields['tags']['note']); + $this->assertSame('Create only. Record id.', $fields['section_id']['note']); + $this->assertSame(['type' => 'integer'], $fields['section_id']['schema'], 'A tree without "multiple" is a single choice.'); + + $aisle = ApiAisle::query()->create(['name' => '123', 'sort' => 1]); + $this->assertSame([['value' => $aisle->id, 'label' => '123']], collect(app(ApiDocumentation::class)->modules(['api_edges'])['api_edges']['fields'])->keyBy('name')['section_id']['options']); + } +} diff --git a/packages/admin/tests/Feature/ApiDocumentationTest.php b/packages/admin/tests/Feature/ApiDocumentationTest.php index 37ed6c88..cd52dbb9 100644 --- a/packages/admin/tests/Feature/ApiDocumentationTest.php +++ b/packages/admin/tests/Feature/ApiDocumentationTest.php @@ -12,6 +12,8 @@ use Atrium\Admin\Api\ApiDocumentation; use Atrium\Admin\Api\ApiResources; use Atrium\Admin\Models\Language; +use Atrium\Admin\Resources\ResourceRegistry; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\ApiAisle; use Atrium\Admin\Tests\Fixtures\ApiShowcase; use Atrium\Admin\Tests\Fixtures\Post; @@ -24,6 +26,8 @@ */ final class ApiDocumentationTest extends TestCase { + use PinsExtensionSurface; + protected function defineEnvironment($app): void { parent::defineEnvironment($app); @@ -114,6 +118,26 @@ public function test_only_the_modules_asked_for_are_described(string $only, arra } } + public function test_the_administrators_stay_out_of_the_api_unless_the_app_says_otherwise(): void + { + $make = fn (): ApiResources => new ApiResources($this->app['router'], $this->app->make(ResourceRegistry::class)); + + $this->assertArrayHasKey('users', $make()->modules()); + $this->assertArrayNotHasKey('users', $make()->all()); + + // An app that sets its own api block without "except" keeps the default. + config(['atrium.api' => ['prefix' => 'v1']]); + $this->assertArrayNotHasKey('users', $make()->all()); + + config(['atrium.api.except' => []]); + $this->assertArrayHasKey('users', $make()->all()); + + $resources = $make(); + $before = $resources->all(); + config(['atrium.api.except' => ['posts']]); + $this->assertSame($before, $resources->all(), 'The list is worked out once.'); + } + public function test_modules_are_named_as_in_the_menu(): void { $resources = app(ApiResources::class); diff --git a/packages/admin/tests/Feature/ApiGatewayTest.php b/packages/admin/tests/Feature/ApiGatewayTest.php new file mode 100644 index 00000000..1ccff569 --- /dev/null +++ b/packages/admin/tests/Feature/ApiGatewayTest.php @@ -0,0 +1,206 @@ +app->instance('request', Request::create('https://example.test/mcp', 'POST')); + request()->headers->set('Authorization', 'Bearer abc'); + config()->set('atrium.api.prefix', '/api/v1/'); + + $router = $this->recordingRouter(fn (Request $r) => new HttpResponse('{}', 200)); + (new ApiGateway($router))->call('GET', '/posts/5', ['page' => 2]); + + $sub = $router->seen; + $this->assertSame('https://example.test/api/v1/posts/5?page=2', $sub->fullUrl()); + $this->assertSame('GET', $sub->getMethod()); + $this->assertSame('Bearer abc', $sub->headers->get('Authorization')); + $this->assertSame('application/json', $sub->headers->get('Content-Type')); + $this->assertSame('application/json', $sub->headers->get('Accept')); + } + + public function test_a_prefix_without_slashes_gets_none_doubled(): void + { + config()->set('atrium.api.prefix', 'v2'); + + $router = $this->recordingRouter(fn (Request $r) => new HttpResponse('{}', 200)); + (new ApiGateway($router))->call('GET', 'posts'); + + $this->assertSame('/v2/posts', $router->seen->getPathInfo()); + } + + public function test_a_missing_token_stays_empty(): void + { + $this->app->instance('request', Request::create('/mcp', 'POST')); + + $router = $this->recordingRouter(fn (Request $r) => new HttpResponse('{}', 200)); + (new ApiGateway($router))->call('GET', 'posts'); + + $this->assertSame('', $router->seen->headers->get('Authorization')); + } + + public function test_the_body_goes_as_json_with_unicode_and_slashes_as_they_are(): void + { + $router = $this->recordingRouter(fn (Request $r) => new HttpResponse('{}', 200)); + (new ApiGateway($router))->call('POST', 'posts', [], ['name' => 'Café / bar']); + + $this->assertSame('{"name":"Café / bar"}', $router->seen->getContent()); + } + + public function test_no_body_means_no_content(): void + { + $router = $this->recordingRouter(fn (Request $r) => new HttpResponse('{}', 200)); + (new ApiGateway($router))->call('GET', 'posts'); + + $this->assertSame('', $router->seen->getContent()); + } + + public function test_a_body_that_cannot_be_encoded_is_sent_empty_instead_of_failing(): void + { + $router = $this->recordingRouter(fn (Request $r) => new HttpResponse('{}', 200)); + (new ApiGateway($router))->call('POST', 'posts', [], ['name' => "\xB1"]); + + $this->assertSame('', $router->seen->getContent()); + } + + public function test_the_api_sees_the_sub_request_as_the_current_one_while_it_runs(): void + { + $original = Request::create('/mcp', 'POST'); + $this->app->instance('request', $original); + RequestFacade::path(); // the facade has resolved the original by now + + $inside = []; + $router = $this->recordingRouter(function (Request $sub) use (&$inside) { + $inside = [app('request') === $sub, RequestFacade::path(), url()->getRequest() === $sub]; + + return new HttpResponse('{}', 200); + }); + (new ApiGateway($router))->call('GET', 'posts'); + + $this->assertSame([true, 'api/v1/posts', true], $inside); + $this->assertSame('mcp', RequestFacade::path(), 'What the facade saw during the call is forgotten afterwards.'); + } + + public function test_the_original_request_is_back_afterwards_for_everyone(): void + { + $original = Request::create('/mcp', 'POST'); + $this->app->instance('request', $original); + + $router = $this->recordingRouter(fn (Request $r) => new HttpResponse('{}', 200)); + (new ApiGateway($router))->call('GET', 'posts'); + + $this->assertSame($original, app('request')); + $this->assertSame('mcp', RequestFacade::path()); + $this->assertSame($original, url()->getRequest()); + } + + public function test_the_original_request_is_back_even_when_the_api_throws(): void + { + $original = Request::create('/mcp', 'POST'); + $this->app->instance('request', $original); + $router = $this->recordingRouter(function () { + RequestFacade::path(); + + throw new RuntimeException('boom'); + }); + + try { + (new ApiGateway($router))->call('GET', 'posts'); + $this->fail('The exception must go on.'); + } catch (RuntimeException $e) { + $this->assertSame('boom', $e->getMessage()); + } + + $this->assertSame($original, app('request')); + $this->assertSame('mcp', RequestFacade::path()); + $this->assertSame($original, url()->getRequest()); + } + + public function test_an_answer_comes_back_as_json(): void + { + $result = $this->gateway(new HttpResponse('{"data":{"a":"é/b"}}', 200)); + + $this->assertFalse($result->isError()); + $this->assertSame('{"data":{"a":"é/b"}}', (string) $result->content()); + } + + public function test_204_is_done_and_its_neighbours_are_not(): void + { + $this->assertSame('Done.', (string) $this->gateway(new HttpResponse('', 204))->content()); + $this->assertFalse($this->gateway(new HttpResponse('', 204))->isError()); + $this->assertSame('null', (string) $this->gateway(new HttpResponse('', 203))->content()); + $this->assertSame('null', (string) $this->gateway(new HttpResponse('', 205))->content()); + } + + public function test_a_streamed_answer_has_no_content_and_counts_as_empty(): void + { + $result = $this->gateway(new StreamedResponse(static function (): void {}, 200)); + + $this->assertFalse($result->isError()); + $this->assertSame('null', (string) $result->content()); + } + + public function test_400_and_above_is_an_error_and_399_is_not(): void + { + $this->assertTrue($this->gateway(new HttpResponse('{"message":"Bad"}', 400))->isError()); + $this->assertSame('HTTP 400. Bad', (string) $this->gateway(new HttpResponse('{"message":"Bad"}', 400))->content()); + $this->assertFalse($this->gateway(new HttpResponse('{"a":1}', 399))->isError()); + } + + public function test_an_error_without_a_message_says_the_request_failed(): void + { + $this->assertSame('HTTP 500. The request failed.', (string) $this->gateway(new HttpResponse('', 500))->content()); + $this->assertSame('HTTP 500. The request failed.', (string) $this->gateway(new HttpResponse('[1,2]', 500))->content()); + $this->assertSame('HTTP 500. The request failed.', (string) $this->gateway(new HttpResponse('"text"', 500))->content()); + } + + public function test_every_invalid_field_is_listed_with_all_its_messages(): void + { + $body = json_encode(['message' => 'Invalid.', 'errors' => ['name' => ['Required.', 'Too short.'], 'sort' => ['Not a number.']]]); + + $this->assertSame( + "HTTP 422. Invalid.\n- name: Required. Too short.\n- sort: Not a number.", + (string) $this->gateway(new HttpResponse((string) $body, 422))->content(), + ); + } + + public function test_errors_that_are_not_a_list_are_still_shown(): void + { + $this->assertSame( + "HTTP 422. Invalid.\n- 0: Oops", + (string) $this->gateway(new HttpResponse('{"message":"Invalid.","errors":"Oops"}', 422))->content(), + ); + $this->assertSame( + "HTTP 422. Invalid.\n- name: Required.", + (string) $this->gateway(new HttpResponse('{"message":"Invalid.","errors":{"name":"Required."}}', 422))->content(), + ); + } + + private function gateway(HttpResponse $answer): Response + { + return (new ApiGateway($this->recordingRouter(fn () => $answer)))->call('GET', 'posts'); + } +} diff --git a/packages/admin/tests/Feature/ApiResourceExactnessTest.php b/packages/admin/tests/Feature/ApiResourceExactnessTest.php new file mode 100644 index 00000000..10d54567 --- /dev/null +++ b/packages/admin/tests/Feature/ApiResourceExactnessTest.php @@ -0,0 +1,137 @@ +set('atrium.resources', [Post::class, Page::class, Bundle::class, Topic::class]); + } + + protected function defineDatabaseMigrations(): void + { + parent::defineDatabaseMigrations(); + + $this->loadMigrationsFrom(dirname((string) (new ReflectionClass(Sanctum::class))->getFileName(), 2).'/database/migrations'); + } + + /** + * @param array $abilities + */ + private function api(array $abilities = ['posts:read', 'posts:write']): static + { + $owner = AdminUser::query()->where('email', 'owner@example.com')->first() + ?? AdminUser::query()->create(['name' => 'Owner', 'email' => 'owner@example.com', 'password' => 'secret-password', 'is_active' => true]); + $owner->forceFill(['is_superadmin' => true])->save(); + $this->app['auth']->forgetGuards(); + + return $this->withToken($owner->createToken('agent', $abilities)->plainTextToken); + } + + /** + * @return array + */ + private function names(string $url): array + { + return $this->api()->getJson($url)->assertOk()->json('data.*.name'); + } + + public function test_a_filter_on_a_foreign_column_does_not_stop_the_filters_after_it(): void + { + Post::query()->create(['name' => 'Hello']); + Post::query()->create(['name' => 'Bye']); + + $this->assertSame(['Hello'], $this->names('/api/v1/posts?filter[password]=x&filter[name]=Hello')); + } + + public function test_the_id_and_the_dates_are_fields_to_filter_and_to_sort_by(): void + { + $first = Post::query()->create(['name' => 'First']); + $second = Post::query()->create(['name' => 'Second']); + $first->forceFill(['created_at' => '2026-03-01 00:00:00', 'updated_at' => '2026-03-03 00:00:00'])->saveQuietly(); + $second->forceFill(['created_at' => '2026-03-02 00:00:00', 'updated_at' => '2026-03-01 00:00:00'])->saveQuietly(); + + $this->assertSame(['Second'], $this->names("/api/v1/posts?filter[id]={$second->id}")); + $this->assertSame(['First', 'Second'], $this->names('/api/v1/posts?sort=created_at')); + $this->assertSame(['Second', 'First'], $this->names('/api/v1/posts?sort=created_at&direction=desc')); + $this->assertSame(['Second', 'First'], $this->names('/api/v1/posts?sort=updated_at')); + $this->assertSame(['Second', 'First'], $this->names('/api/v1/posts?sort=id&direction=desc')); + $this->assertSame(['First', 'Second'], $this->names('/api/v1/posts?sort=password'), 'Not a field: by id.'); + } + + public function test_a_translated_field_is_filtered_by_its_text_in_any_language(): void + { + Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200]); + $first = Page::query()->create(['name' => ['en' => 'First', 'de' => 'Erste']]); + $second = Page::query()->create(['name' => ['en' => 'Second', 'de' => 'Zweite']]); + $ids = fn (string $text): array => $this->api(['pages:read'])->getJson('/api/v1/pages?filter[name]='.urlencode($text))->assertOk()->json('data.*.id'); + + $this->assertSame([$first->id], $ids('First')); + $this->assertSame([$first->id], $ids('Erste')); + $this->assertSame([$second->id], $ids('Zweite')); + $this->assertSame([], $ids('Third')); + } + + public function test_a_token_without_the_ability_for_the_call_is_refused_with_403(): void + { + $this->api(['posts:read'])->postJson('/api/v1/posts', ['name' => 'New']) + ->assertStatus(403) + ->assertJsonPath('message', 'The token lacks the posts:write ability.'); + $this->api(['posts:write'])->getJson('/api/v1/posts') + ->assertStatus(403) + ->assertJsonPath('message', 'The token lacks the posts:read ability.'); + $this->api(['pages:read'])->getJson('/api/v1/posts')->assertStatus(403); + + $this->assertSame(0, Post::query()->count()); + } + + public function test_every_relation_of_a_record_comes_back_with_it(): void + { + $bundle = Bundle::query()->create(['name' => 'Starter']); + $post = Post::query()->create(['name' => 'Hello']); + $topic = Topic::query()->create(['name' => 'News']); + $bundle->posts()->attach($post); + $bundle->topics()->attach($topic); + + $this->api(['bundles:read'])->getJson('/api/v1/bundles') + ->assertOk() + ->assertJsonPath('data.0.posts', [$post->id]) + ->assertJsonPath('data.0.topics', [$topic->id]); + $this->api(['bundles:read'])->getJson("/api/v1/bundles/{$bundle->id}") + ->assertJsonPath('data.posts', [$post->id]) + ->assertJsonPath('data.topics', [$topic->id]); + } + + public function test_a_search_or_a_sort_that_is_a_list_does_not_break_the_page(): void + { + Post::query()->create(['name' => 'Hello']); + Post::query()->create(['name' => 'Bye']); + + $this->assertSame(['Hello', 'Bye'], $this->names('/api/v1/posts?search[]=Hello')); + $this->assertSame(['Bye', 'Hello'], $this->names('/api/v1/posts?sort[]=name&direction=desc'), 'By id, newest first.'); + } +} diff --git a/packages/admin/tests/Feature/ApiResourceTest.php b/packages/admin/tests/Feature/ApiResourceTest.php index ba13d74d..4ccf4161 100644 --- a/packages/admin/tests/Feature/ApiResourceTest.php +++ b/packages/admin/tests/Feature/ApiResourceTest.php @@ -16,6 +16,7 @@ use Atrium\Admin\Models\MediaItem; use Atrium\Admin\Models\SeoMeta; use Atrium\Admin\Models\Site; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\ApiArticle; use Atrium\Admin\Tests\Fixtures\Note; use Atrium\Admin\Tests\Fixtures\Page; @@ -36,6 +37,8 @@ */ final class ApiResourceTest extends TestCase { + use PinsExtensionSurface; + protected function defineEnvironment($app): void { parent::defineEnvironment($app); diff --git a/packages/admin/tests/Feature/ApiTokensTest.php b/packages/admin/tests/Feature/ApiTokensTest.php index 88ed1b69..6a4ef16e 100644 --- a/packages/admin/tests/Feature/ApiTokensTest.php +++ b/packages/admin/tests/Feature/ApiTokensTest.php @@ -14,6 +14,7 @@ use Atrium\Admin\Models\AdminUser; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; +use Illuminate\Support\Facades\DB; use Inertia\Testing\AssertableInertia; use Laravel\Sanctum\PersonalAccessToken; use Laravel\Sanctum\Sanctum; @@ -61,6 +62,48 @@ public function test_a_token_is_issued_and_its_key_is_shown_once(): void $this->withToken($plain)->getJson('/api/v1/posts')->assertOk(); } + public function test_the_form_names_the_name_field_in_the_panel_s_words(): void + { + $this->app->make('translator')->addLines(['account.api_tokens.attributes.name' => 'token title'], 'en', 'atrium'); + + $this->actingAs($this->admin(), 'admin') + ->from('/admin/api-tokens') + ->post('/admin/api-tokens', ['abilities' => ['posts:read']]) + ->assertSessionHasErrors(['name' => 'The token title field is required.']); + } + + public function test_an_ability_is_a_string_that_is_on_offer(): void + { + $response = $this->actingAs($this->admin(), 'admin') + ->from('/admin/api-tokens') + ->post('/admin/api-tokens', ['name' => 'Robot', 'abilities' => [5]]); + + $messages = $response->assertSessionHasErrors('abilities.0')->getSession()->get('errors')->get('abilities.0'); + $this->assertCount(2, $messages); + $this->assertStringContainsString('must be a string', $messages[0]); + $this->assertStringContainsString('invalid', $messages[1]); + $this->assertSame(0, PersonalAccessToken::query()->count()); + } + + public function test_the_abilities_of_a_token_are_stored_as_a_list(): void + { + $this->actingAs($this->admin(), 'admin') + ->post('/admin/api-tokens', ['name' => 'Robot', 'abilities' => ['posts:read', 'posts:read', 'posts:write']]); + + $this->assertSame('["posts:read","posts:write"]', DB::table('personal_access_tokens')->value('abilities')); + } + + public function test_a_token_without_a_creation_date_is_listed_with_none(): void + { + $this->actingAs($this->admin(), 'admin'); + $token = AdminUser::query()->sole()->createToken('Old', ['posts:read'])->accessToken; + $token->forceFill(['created_at' => null])->saveQuietly(); + + $this->get('/admin/api-tokens')->assertInertia(fn (AssertableInertia $page) => $page + ->where('tokens.0.created_at', null) + ->where('tokens.0.name', 'Old')); + } + public function test_a_token_without_an_expiry_never_expires(): void { $this->actingAs($this->admin(), 'admin') diff --git a/packages/admin/tests/Feature/BareModelTest.php b/packages/admin/tests/Feature/BareModelTest.php new file mode 100644 index 00000000..a0ec13b3 --- /dev/null +++ b/packages/admin/tests/Feature/BareModelTest.php @@ -0,0 +1,45 @@ +set('atrium.resources', [Bare::class]); + } + + public function test_the_list_the_forms_and_saving_work_without_the_trait(): void + { + $record = Bare::query()->create(['name' => 'First']); + $this->actingAs($this->admin(), 'admin'); + + $this->get('/admin/bares')->assertOk()->assertInertia(fn (AssertableInertia $p) => $p + ->where('can', ['view' => true, 'create' => true, 'update' => true, 'delete' => true]) + ->where('actions', [])); + $this->get('/admin/bares/create')->assertOk(); + $this->get("/admin/bares/{$record->id}/edit")->assertOk(); + + $this->post('/admin/bares', ['name' => 'Second'])->assertRedirect(); + $this->put("/admin/bares/{$record->id}", ['name' => 'Changed'])->assertRedirect(); + + $this->assertSame(['Changed', 'Second'], Bare::query()->orderBy('id')->pluck('name')->all()); + } +} diff --git a/packages/admin/tests/Feature/CaptchaTest.php b/packages/admin/tests/Feature/CaptchaTest.php index 0074f49e..2d32b63f 100644 --- a/packages/admin/tests/Feature/CaptchaTest.php +++ b/packages/admin/tests/Feature/CaptchaTest.php @@ -14,7 +14,10 @@ use Atrium\Admin\Captcha\ImageCaptcha; use Atrium\Admin\Captcha\NoCaptcha; use Atrium\Admin\Captcha\RecaptchaCaptcha; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\TestCase; +use Illuminate\Contracts\Cache\Repository as Cache; +use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Http\Client\Request as HttpRequest; use Illuminate\Http\Request; use Illuminate\Support\Facades\Blade; @@ -25,6 +28,8 @@ final class CaptchaTest extends TestCase { + use PinsExtensionSurface; + public function test_off_by_default_the_forms_draw_and_ask_nothing(): void { $captcha = $this->captcha(); @@ -89,6 +94,33 @@ public function test_an_image_question_is_answered_once_and_expires(): void $this->assertFalse($captcha->verify($this->request($token, $answer)), 'expired'); } + public function test_without_gd_the_sum_is_written_as_text_and_no_picture_is_drawn(): void + { + $captcha = new ImageCaptcha(app(Encrypter::class), app(Cache::class), false); + + $html = (string) $captcha->widget(); + $token = $this->token($html); + $question = Crypt::decrypt($token); + + $this->assertStringContainsString(''.$question['q'].' = ?', $html); + $this->assertStringNotContainsString('assertNull($captcha->image($token)); + $this->assertTrue($captcha->verify($this->request($token, (string) $question['a'])), 'the answer still counts'); + } + + public function test_with_gd_the_sum_is_a_picture_and_not_text(): void + { + $captcha = new ImageCaptcha(app(Encrypter::class), app(Cache::class), true); + + $html = (string) $captcha->widget(); + $token = $this->token($html); + + $this->assertStringContainsString('assertStringNotContainsString(''.Crypt::decrypt($token)['q'], $html); + $this->assertStringStartsWith("\x89PNG", (string) $captcha->image($token)); + $this->assertNull($captcha->image('forged')); + } + public function test_the_rule_puts_the_error_on_the_captcha_field(): void { $captcha = $this->captcha('image'); @@ -183,4 +215,45 @@ private function request(string $token, ?string $answer): Request { return Request::create('/', 'POST', array_filter(['captcha_token' => $token, 'captcha' => $answer], static fn ($value) => $value !== null)); } + + public function test_the_recaptcha_widget_is_exactly_the_script_and_the_div(): void + { + app()->setLocale('pt_BR'); + + $this->assertSame( + '
', + (new RecaptchaCaptcha('a"b', 'secret'))->widget()->toHtml(), + ); + } + + public function test_recaptcha_waits_five_seconds_for_google_and_no_more(): void + { + $options = null; + Http::fake(function (HttpRequest $request, array $given) use (&$options) { + $options = $given; + + return Http::response(['success' => true]); + }); + + $this->assertTrue((new RecaptchaCaptcha('site', 'secret'))->verify(Request::create('/', 'POST', ['g-recaptcha-response' => 'answer']))); + $this->assertSame(5, (int) $options['timeout']); + } + + public function test_recaptcha_needs_both_keys_and_unset_keys_count_as_empty(): void + { + config(['atrium.captcha.recaptcha' => ['site_key' => 'site-key', 'secret_key' => '']]); + $this->assertInstanceOf(ImageCaptcha::class, $this->captcha('recaptcha')->driver()); + + config(['atrium.captcha.recaptcha' => ['site_key' => '', 'secret_key' => 'secret-key']]); + $this->assertInstanceOf(ImageCaptcha::class, $this->captcha('recaptcha')->driver()); + + config(['atrium.captcha.recaptcha' => ['secret_key' => 'secret-key']]); + $this->assertInstanceOf(ImageCaptcha::class, $this->captcha('recaptcha')->driver()); + + config(['atrium.captcha.recaptcha' => ['site_key' => 'site-key']]); + $this->assertInstanceOf(ImageCaptcha::class, $this->captcha('recaptcha')->driver()); + + config(['atrium.captcha.recaptcha' => ['site_key' => 'site-key', 'secret_key' => 'secret-key']]); + $this->assertInstanceOf(RecaptchaCaptcha::class, $this->captcha('recaptcha')->driver()); + } } diff --git a/packages/admin/tests/Feature/CommandsTest.php b/packages/admin/tests/Feature/CommandsTest.php index 89f7c9e6..7f0d5a48 100644 --- a/packages/admin/tests/Feature/CommandsTest.php +++ b/packages/admin/tests/Feature/CommandsTest.php @@ -56,6 +56,9 @@ public function test_make_module_writes_a_translatable_model_and_its_migration() { $model = app_path('Models/Brochure.php'); $before = glob(database_path('migrations/*_create_brochures_table.php')) ?: []; + // The command registers the module in the config of this very application. + $config = config_path('atrium.php'); + $registered = is_file($config) ? file_get_contents($config) : null; try { $this->artisan('atrium:make-module', ['name' => 'Brochure'])->assertSuccessful(); @@ -70,6 +73,10 @@ public function test_make_module_writes_a_translatable_model_and_its_migration() $this->assertStringContainsString("\$table->json('name');", (string) file_get_contents((string) reset($migrations))); } finally { File::delete([$model, ...array_diff(glob(database_path('migrations/*_create_brochures_table.php')) ?: [], $before)]); + + if ($registered !== null) { + file_put_contents($config, $registered); + } } } diff --git a/packages/admin/tests/Feature/ContentLanguagesTest.php b/packages/admin/tests/Feature/ContentLanguagesTest.php index b56d38f1..eea525b3 100644 --- a/packages/admin/tests/Feature/ContentLanguagesTest.php +++ b/packages/admin/tests/Feature/ContentLanguagesTest.php @@ -43,6 +43,9 @@ protected function defineRoutes($router): void Route::localized(function (): void { Route::get('pages/{code}', fn (string $code) => app()->getLocale().':'.$code)->name('pages.show'); }); + + // After the language prefix, which must not swallow what is not a language code. + Route::get('{section}/pages/{code}', fn (string $section, string $code) => "{$section}:{$code}"); } private function addGerman(): Language @@ -243,6 +246,7 @@ public function test_public_routes_answer_in_every_active_language(): void // Inactive languages and the default one under a prefix do not exist. $this->get('/fr/pages/bonjour')->assertNotFound(); $this->get('/en/pages/hello')->assertNotFound(); + $this->get('/shop/pages/hello')->assertOk()->assertSee('shop:hello'); $languages = app(ContentLanguages::class); $this->assertSame(url('/pages/hello'), $languages->route('pages.show', ['code' => 'hello'], 'en')); diff --git a/packages/admin/tests/Feature/DashboardGadgetsTest.php b/packages/admin/tests/Feature/DashboardGadgetsTest.php index cac0c1c6..e7855a9c 100644 --- a/packages/admin/tests/Feature/DashboardGadgetsTest.php +++ b/packages/admin/tests/Feature/DashboardGadgetsTest.php @@ -19,10 +19,13 @@ use Atrium\Admin\Models\PageTiming; use Atrium\Admin\Tests\Fixtures\Handbook; use Atrium\Admin\Tests\Fixtures\Post; +use Atrium\Admin\Tests\Fixtures\Untimed; use Atrium\Admin\Tests\TestCase; use Atrium\Admin\Traits\InteractsWithAdmin; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\DB; +use PDO; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; @@ -139,6 +142,78 @@ public function test_the_summary_is_worked_out_once_per_instance(): void $this->assertSame(1, $stats->samples()); } + public function test_the_summary_is_kept_for_five_minutes_by_default(): void + { + $this->timings([100]); + $this->assertSame(1, (new PageSpeedStats)->samples()); + + $this->timings([200]); + $this->travel(299)->seconds(); + $this->assertSame(1, (new PageSpeedStats)->samples()); + + $this->travel(1)->seconds(); + $this->assertSame(2, (new PageSpeedStats)->samples()); + } + + public function test_an_empty_window_is_a_result_too_and_is_kept(): void + { + $this->assertSame(0, (new PageSpeedStats)->samples()); + + $this->assertSame( + ['samples' => 0, 'median_ms' => null, 'average_ms' => null, 'rate' => null, 'slowest' => []], + Cache::get('atrium.page-speed.7'), + ); + } + + public function test_the_summary_has_the_right_types_when_the_database_hands_everything_over_as_text(): void + { + // MySQL and PostgreSQL return aggregates as strings; SQLite can be made to do the same. + $pdo = DB::connection()->getPdo(); + $pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true); + $this->beforeApplicationDestroyed(fn () => $pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false)); + $this->timings([10, 10, 11, 11, 10], '/a'); + $this->timings([20, 20], '/10'); + + $stats = new PageSpeedStats; + + $this->assertSame(7, $stats->samples()); + $this->assertSame(11, $stats->medianMs()); + $this->assertSame( + [ + 'samples' => 7, + 'median_ms' => 11, + 'average_ms' => 92 / 7, + 'rate' => 7 / (92 / 1000), + // 10.4 rounds down and 20 stays: a slowest list by average, rounded, not rounded up. + 'slowest' => [['path' => '/10', 'ms' => 20, 'hits' => 2], ['path' => '/a', 'ms' => 10, 'hits' => 5]], + ], + Cache::get('atrium.page-speed.7'), + ); + $this->assertSame( + [['path' => '/10', 'ms' => 20, 'hits' => 2], ['path' => '/a', 'ms' => 10, 'hits' => 5]], + $stats->slowest(), + ); + } + + public function test_the_average_is_a_float_even_when_it_is_whole(): void + { + $this->timings([100, 300]); + + $this->assertSame(200.0, (new PageSpeedStats)->averageMs()); + $this->assertSame(200.0, Cache::get('atrium.page-speed.7')['average_ms']); + } + + public function test_the_gadgets_use_the_summary_they_are_given(): void + { + $this->timings([100]); + $stats = new PageSpeedStats(3); + + $this->assertSame(3, (new SiteSpeedGadget([], $stats))->data()['windowDays']); + $this->assertSame(3, (new PerformanceGadget([], $stats))->data()['windowDays']); + $this->assertSame(7, (new SiteSpeedGadget)->data()['windowDays']); + $this->assertSame(7, (new PerformanceGadget)->data()['windowDays']); + } + public function test_a_broken_cache_leaves_the_dashboard_without_numbers(): void { $this->timings([100]); @@ -416,6 +491,19 @@ public function test_the_recent_items_gadget_of_a_model_without_dates_sorts_by_k $this->assertSame([null, null], array_column($items, 'date')); } + public function test_a_model_that_keeps_no_timestamps_sorts_by_key_even_if_its_table_has_the_columns(): void + { + $first = Untimed::query()->create(['name' => '5', 'updated_at' => '2026-08-04 10:00:00']); + $second = Untimed::query()->create(['name' => '0', 'updated_at' => '2026-08-01 10:00:00']); + + $items = (new RecentElementsGadget(['model' => Untimed::class]))->data()['items']; + + $this->assertSame([$second->id, $first->id], array_column($items, 'id')); + $this->assertSame([null, null], array_column($items, 'date')); + // The name is always text; an empty one (here: 0) shows the key instead. + $this->assertSame(['#'.$second->id, '5'], array_column($items, 'name')); + } + public function test_the_recent_items_gadget_survives_a_missing_table(): void { // A database of its own: on PostgreSQL a failed query would abort the diff --git a/packages/admin/tests/Feature/DisplayFieldTest.php b/packages/admin/tests/Feature/DisplayFieldTest.php index a9e43676..176cb1c2 100644 --- a/packages/admin/tests/Feature/DisplayFieldTest.php +++ b/packages/admin/tests/Feature/DisplayFieldTest.php @@ -9,13 +9,18 @@ namespace Atrium\Admin\Tests\Feature; +use Atrium\Admin\Fields\DisplayField; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\Fixtures\Receipt; use Atrium\Admin\Tests\TestCase; +use Illuminate\Support\HtmlString; use Inertia\Testing\AssertableInertia; final class DisplayFieldTest extends TestCase { + use PinsExtensionSurface; + protected function defineEnvironment($app): void { parent::defineEnvironment($app); @@ -53,4 +58,11 @@ public function test_a_submitted_value_is_ignored(): void $this->assertSame('New', $receipt->fresh()?->getAttribute('name')); } + + public function test_whatever_the_closure_returns_is_drawn_as_a_string(): void + { + $this->assertSame('x', DisplayField::make('a')->html(fn (): HtmlString => new HtmlString('x'))->render(new Post)); + $this->assertSame('42', DisplayField::make('a')->html(fn (): int => 42)->render(new Post)); + $this->assertSame('', DisplayField::make('a')->render(new Post)); + } } diff --git a/packages/admin/tests/Feature/EnterSiteFolderTest.php b/packages/admin/tests/Feature/EnterSiteFolderTest.php new file mode 100644 index 00000000..d83de727 --- /dev/null +++ b/packages/admin/tests/Feature/EnterSiteFolderTest.php @@ -0,0 +1,211 @@ +create(['code' => $code, 'name' => ucfirst($code), 'folder' => $folder]); + } + + /** + * @param array $server + */ + private function request(string $uri, array $server = []): Request + { + $request = Request::create($uri, 'GET', server: $server); + $this->app->instance('request', $request); + + return $request; + } + + /** + * @return array what the next layer saw + */ + private function enter(Request $request): array + { + $seen = []; + + app(EnterSiteFolder::class)->handle($request, function (Request $r) use (&$seen): Response { + $seen = [ + 'site' => $r->attributes->get(EnterSiteFolder::SITE), + 'folder' => $r->attributes->get(EnterSiteFolder::FOLDER), + 'path' => $r->getPathInfo(), + 'base' => $r->getBaseUrl(), + 'basePath' => $r->getBasePath(), + 'generator' => url()->getRequest() === $r, + 'url' => url('x'), + 'asset' => asset('a.css'), + ]; + + return new Response('ok'); + }); + + return $seen; + } + + public function test_a_site_at_the_root_is_noted_and_nothing_moves(): void + { + $main = Site::query()->where('code', 'main')->sole(); + $this->site('second', 'site2'); + + $seen = $this->enter($this->request('http://main.test/notes/a')); + + $this->assertSame($main->id, $seen['site']); + $this->assertNull($seen['folder']); + $this->assertSame(['/notes/a', '', ''], [$seen['path'], $seen['base'], $seen['basePath']]); + } + + public function test_a_site_in_a_folder_is_noted_with_its_folder_and_the_rest_of_the_path_is_left(): void + { + $second = $this->site('second', 'site2'); + + $seen = $this->enter($this->request('http://main.test/site2/notes/a')); + + $this->assertSame([$second->id, 'site2'], [$seen['site'], $seen['folder']]); + $this->assertSame(['/notes/a', '/site2', '/site2'], [$seen['path'], $seen['base'], $seen['basePath']]); + + $seen = $this->enter($this->request('http://main.test/site2')); + $this->assertSame(['/', '/site2'], [$seen['path'], $seen['base']]); + } + + public function test_the_folder_is_added_to_a_base_the_request_already_has(): void + { + $this->site('second', 'site2'); + + $seen = $this->enter($this->request('http://main.test/sub/site2/notes/a', [ + 'SCRIPT_NAME' => '/sub/index.php', + 'SCRIPT_FILENAME' => '/var/www/sub/index.php', + 'PHP_SELF' => '/sub/index.php', + ])); + + $this->assertSame(['/notes/a', '/sub/site2', '/sub/site2'], [$seen['path'], $seen['base'], $seen['basePath']]); + } + + public function test_the_admin_the_api_and_the_mcp_are_not_inside_a_folder(): void + { + $this->site('second', 'site2'); + + foreach (['/site2/admin', '/site2/admin/', '/site2/admin/login', '/site2/api/v1/posts', '/site2/mcp'] as $path) { + $request = $this->request('http://main.test'.$path); + $seen = $this->enter($request); + + $this->assertSame([null, null, $path, ''], [$seen['site'], $seen['folder'], $seen['path'], $seen['base']], $path.' went on as a page of the site.'); + } + } + + public function test_a_page_that_only_starts_like_a_prefix_is_a_page_of_the_site(): void + { + $second = $this->site('second', 'site2'); + + foreach (['/site2/administrators', '/site2/apiary', '/site2/mcp-news', '/site2/adm'] as $path) { + $seen = $this->enter($this->request('http://main.test'.$path)); + + $this->assertSame([$second->id, 'site2'], [$seen['site'], $seen['folder']], $path); + } + } + + public function test_prefixes_are_taken_without_their_slashes(): void + { + config()->set('atrium.prefix', '/cp/'); + config()->set('atrium.api.prefix', '/rest/v2/'); + config()->set('atrium.mcp.path', '/ai/'); + $second = $this->site('second', 'site2'); + + foreach (['/site2/cp', '/site2/cp/x', '/site2/rest/v2/posts', '/site2/ai'] as $path) { + $seen = $this->enter($this->request('http://main.test'.$path)); + $this->assertSame([null, null, ''], [$seen['site'], $seen['folder'], $seen['base']], $path); + } + $this->assertSame($second->id, $this->enter($this->request('http://main.test/site2/admin/x'))['site']); + } + + public function test_an_empty_prefix_claims_nothing(): void + { + config()->set('atrium.mcp.path', ''); + $second = $this->site('second', 'site2'); + + $this->assertSame($second->id, $this->enter($this->request('http://main.test/site2/anything'))['site']); + } + + public function test_the_next_layer_builds_addresses_inside_the_folder_with_assets_at_the_root(): void + { + $this->site('second', 'site2'); + $request = $this->request('http://main.test/site2/notes/a'); + url('warm-up'); // the generator has cached the root as it was before the folder + + $seen = $this->enter($request); + + $this->assertTrue($seen['generator']); + $this->assertSame('http://main.test/site2/x', $seen['url']); + $this->assertSame('http://main.test/a.css', $seen['asset']); + } + + public function test_an_asset_origin_that_is_already_set_stays_while_the_folder_is_entered(): void + { + $this->site('second', 'site2'); + $request = $this->request('http://main.test/site2/notes/a'); + url()->useAssetOrigin('https://cdn.test'); + + $seen = $this->enter($request); + + $this->assertSame('https://cdn.test/a.css', $seen['asset']); + $this->assertSame('https://cdn.test/a.css', asset('a.css'), 'And after: the origin of before.'); + } + + public function test_nothing_of_the_folder_outlives_the_request(): void + { + $this->site('second', 'site2'); + $request = $this->request('http://main.test/site2/notes/a'); + url('warm-up'); + + $this->enter($request); + + $outside = url()->getRequest(); + $this->assertNotSame($request, $outside); + $this->assertSame(['/site2/notes/a', ''], [$outside->getPathInfo(), $outside->getBaseUrl()]); + $this->assertSame('http://main.test/x', url('x')); + $this->assertSame('http://main.test/a.css', asset('a.css')); + + // The asset origin worked out for the folder is gone too: the next request is on another host. + $this->request('http://other.test/'); + $this->assertSame('http://other.test/a.css', asset('a.css')); + } + + public function test_nothing_of_the_folder_outlives_a_request_that_failed(): void + { + $this->site('second', 'site2'); + $request = $this->request('http://main.test/site2/notes/a'); + url('warm-up'); + url()->useAssetOrigin('https://cdn.test'); + + try { + app(EnterSiteFolder::class)->handle($request, fn () => throw new RuntimeException('boom')); + $this->fail('The exception must go on.'); + } catch (RuntimeException $e) { + $this->assertSame('boom', $e->getMessage()); + } + + $this->assertSame('http://main.test/x', url('x')); + $this->assertSame('https://cdn.test/a.css', asset('a.css')); + $this->assertSame('', url()->getRequest()->getBaseUrl()); + } +} diff --git a/packages/admin/tests/Feature/FileManagerTest.php b/packages/admin/tests/Feature/FileManagerTest.php index b0f22fd9..5d1a5348 100644 --- a/packages/admin/tests/Feature/FileManagerTest.php +++ b/packages/admin/tests/Feature/FileManagerTest.php @@ -13,6 +13,7 @@ use Atrium\Admin\Models\AdminUser; use Atrium\Admin\Models\MediaCollection; use Atrium\Admin\Models\MediaItem; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\TestCase; use Illuminate\Filesystem\Filesystem; use Illuminate\Http\UploadedFile; @@ -29,6 +30,8 @@ */ final class FileManagerTest extends TestCase { + use PinsExtensionSurface; + protected function setUp(): void { parent::setUp(); @@ -338,6 +341,66 @@ public function test_the_size_limit_is_named_in_megabytes(): void ->assertJsonValidationErrors(['file' => 'The file is too large. Maximum size: 1.5 MB.']); } + /** + * @return array + */ + public static function roundedSizes(): array + { + return [ + 'just under a half' => [1484, 1485, '1.4'], + 'just over a half' => [1486, 1487, '1.5'], + ]; + } + + #[DataProvider('roundedSizes')] + public function test_the_size_limit_is_divided_by_exactly_1024_and_rounded_to_a_tenth(int $limit, int $kilobytes, string $megabytes): void + { + config()->set('atrium.uploads.max_size', $limit); + + $this->upload($this->file('offer.pdf', $kilobytes)) + ->assertJsonValidationErrors(['file' => "The file is too large. Maximum size: {$megabytes} MB."]); + } + + /** + * @return array + */ + public static function defaultTypes(): array + { + return array_map( + static fn (string $name): array => [$name], + array_combine( + $names = ['a.jpg', 'a.jpeg', 'a.png', 'a.gif', 'a.webp', 'a.pdf', 'a.doc', 'a.docx', 'a.xls', 'a.xlsx'], + $names, + ), + ); + } + + #[DataProvider('defaultTypes')] + public function test_without_a_configured_list_the_usual_pictures_and_documents_are_kept(string $name): void + { + config()->set('atrium.uploads', []); + + $this->upload($this->file($name))->assertOk(); + } + + public function test_without_a_configured_list_anything_else_is_refused_and_named(): void + { + config()->set('atrium.uploads', []); + + $this->upload($this->file('notes.txt')) + ->assertStatus(422) + ->assertJsonPath('message', __('atrium::files.errors.type_not_allowed', ['types' => 'jpg, jpeg, png, gif, webp, pdf, doc, docx, xls, xlsx'])); + } + + public function test_without_a_configured_limit_ten_megabytes_are_kept_and_one_kilobyte_more_is_not(): void + { + config()->set('atrium.uploads', []); + + $this->upload($this->file('offer.pdf', 10240))->assertOk(); + $this->upload($this->file('offer.pdf', 10241)) + ->assertJsonValidationErrors(['file' => 'The file is too large. Maximum size: 10 MB.']); + } + public function test_a_missing_or_broken_file_is_refused_by_name(): void { $admin = $this->admin(); @@ -426,6 +489,7 @@ public function test_the_list_pages_newest_first(): void } $first = $this->files()->assertOk(); + $this->assertSame(2, $first->json('last_page'), 'A whole number, not 2.0.'); $first->assertJsonPath('total', 25) ->assertJsonPath('page', 1) ->assertJsonPath('per_page', 24) @@ -489,6 +553,8 @@ public function test_the_list_is_filtered_by_kind_collection_and_text(): void $this->assertSame(['beach.jpg', 'scan.pdf'], $names(['collection' => $photos->id])); $this->assertSame(['scan.pdf'], $names(['collection' => $photos->id, 'type' => 'document'])); $this->assertSame(['beach.jpg', 'contract.pdf', 'scan.pdf'], $names(['collection' => 0])); + $this->assertSame(['beach.jpg', 'contract.pdf', 'scan.pdf'], $names(['collection' => 'abc'])); + $this->assertSame(['beach.jpg', 'contract.pdf', 'scan.pdf'], $names(['type' => ['image']])); $this->assertSame(['beach.jpg'], $names(['search' => 'each'])); $this->assertSame(['beach.jpg'], $names(['search' => 'sun'])); $this->assertSame([], $names(['search' => '0_%'])); diff --git a/packages/admin/tests/Feature/FolderSitesTest.php b/packages/admin/tests/Feature/FolderSitesTest.php index 42acd427..360c1a1a 100644 --- a/packages/admin/tests/Feature/FolderSitesTest.php +++ b/packages/admin/tests/Feature/FolderSitesTest.php @@ -14,6 +14,7 @@ use Atrium\Admin\Models\SlugHistory; use Atrium\Admin\Support\ContentLanguages; use Atrium\Admin\Support\Sites; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Note; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; @@ -27,6 +28,8 @@ */ final class FolderSitesTest extends TestCase { + use PinsExtensionSurface; + protected function defineEnvironment($app): void { parent::defineEnvironment($app); diff --git a/packages/admin/tests/Feature/FormRulesTest.php b/packages/admin/tests/Feature/FormRulesTest.php index 019a8175..a28770ed 100644 --- a/packages/admin/tests/Feature/FormRulesTest.php +++ b/packages/admin/tests/Feature/FormRulesTest.php @@ -12,6 +12,7 @@ use Atrium\Admin\Models\AdminUser; use Atrium\Admin\Models\Language; use Atrium\Admin\Models\SeoMeta; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\ApiArticle; use Atrium\Admin\Tests\Fixtures\Chapter; use Atrium\Admin\Tests\Fixtures\Page; @@ -29,6 +30,8 @@ */ final class FormRulesTest extends TestCase { + use PinsExtensionSurface; + protected function defineEnvironment($app): void { parent::defineEnvironment($app); diff --git a/packages/admin/tests/Feature/HasAdminFilesTest.php b/packages/admin/tests/Feature/HasAdminFilesTest.php index 52c3931b..72702356 100644 --- a/packages/admin/tests/Feature/HasAdminFilesTest.php +++ b/packages/admin/tests/Feature/HasAdminFilesTest.php @@ -10,6 +10,7 @@ namespace Atrium\Admin\Tests\Feature; use Atrium\Admin\Models\File; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Handbook; use Atrium\Admin\Tests\TestCase; use Illuminate\Support\Facades\Storage; @@ -17,6 +18,8 @@ final class HasAdminFilesTest extends TestCase { + use PinsExtensionSurface; + protected function setUp(): void { parent::setUp(); diff --git a/packages/admin/tests/Feature/HasAdminSeoTest.php b/packages/admin/tests/Feature/HasAdminSeoTest.php index efdd8b42..1e90bbf0 100644 --- a/packages/admin/tests/Feature/HasAdminSeoTest.php +++ b/packages/admin/tests/Feature/HasAdminSeoTest.php @@ -11,12 +11,16 @@ use Atrium\Admin\Fields\TextField; use Atrium\Admin\Models\SeoMeta; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Handbook; use Atrium\Admin\Tests\TestCase; +use Illuminate\Database\Eloquent\Relations\Relation; use PHPUnit\Framework\Attributes\DataProvider; final class HasAdminSeoTest extends TestCase { + use PinsExtensionSurface; + public function test_the_title_from_the_seo_tab_wins_and_fills_its_placeholders(): void { $article = Handbook::query()->create(['name' => 'Chair', 'code' => 'chair']); @@ -25,6 +29,23 @@ public function test_the_title_from_the_seo_tab_wins_and_fills_its_placeholders( $this->assertSame('Buy Chair — chair', $article->fresh()?->getSeoTitle()); } + public function test_saving_the_seo_tab_again_updates_the_one_record_even_when_the_model_has_a_morph_alias(): void + { + Relation::morphMap(['handbook' => Handbook::class]); + + try { + $article = Handbook::query()->create(['name' => 'Chair']); + $article->updateSeoMeta(['title' => 'First']); + $article->updateSeoMeta(['title' => 'Second']); + + $this->assertSame(1, SeoMeta::query()->count()); + $this->assertSame('Second', $article->fresh()?->getSeoTitle()); + $this->assertSame('handbook', SeoMeta::query()->sole()->seoable_type); + } finally { + Relation::morphMap([], false); + } + } + public function test_without_a_title_the_template_of_the_model_is_used(): void { config()->set('atrium.seo.templates.'.Handbook::class.'.title', '{name} in our shop'); @@ -49,6 +70,42 @@ public function test_an_unknown_placeholder_or_an_empty_relation_stays_as_it_is( $this->assertSame('{price} {parent} Chair', $article->fresh()?->getSeoTitle()); } + public function test_a_placeholder_naming_a_related_record_gives_its_name(): void + { + $parent = Handbook::query()->create(['name' => 'Furniture']); + $article = Handbook::query()->create(['name' => 'Chair', 'parent_id' => $parent->id]); + $article->updateSeoMeta(['title' => '{name} in {parent}']); + + $this->assertSame('Chair in Furniture', $article->fresh()?->getSeoTitle()); + } + + public function test_a_related_record_without_a_name_leaves_its_placeholder(): void + { + $parent = Handbook::query()->create(['name' => null]); + $article = Handbook::query()->create(['name' => 'Chair', 'parent_id' => $parent->id]); + $article->updateSeoMeta(['title' => '{name} in {parent}']); + + $this->assertSame('Chair in {parent}', $article->fresh()?->getSeoTitle()); + } + + public function test_the_name_of_a_related_record_is_stripped_of_tags(): void + { + $parent = Handbook::query()->create(['name' => 'Furniture']); + $article = Handbook::query()->create(['name' => 'Chair', 'parent_id' => $parent->id]); + $article->updateSeoMeta(['title' => '{parent}']); + + $this->assertSame('Furniture', $article->fresh()?->getSeoTitle()); + } + + public function test_a_list_or_a_missing_value_leaves_its_placeholder_and_numbers_and_dates_are_written_out(): void + { + $this->travelTo(now()->setDate(2026, 3, 4)->setTime(10, 20, 30)); + $article = Handbook::query()->create(['name' => 'Chair']); + $article->updateSeoMeta(['title' => '{files}|{id}|{created_at}|{description}']); + + $this->assertSame("{files}|{$article->id}|2026-03-04 10:20:30|{description}", $article->fresh()?->getSeoTitle()); + } + public function test_the_description_from_the_seo_tab_wins(): void { $article = Handbook::query()->create(['name' => 'Chair', 'preview_text' => 'Preview']); diff --git a/packages/admin/tests/Feature/HasAdminSlugTest.php b/packages/admin/tests/Feature/HasAdminSlugTest.php index 7f9cd60e..de921009 100644 --- a/packages/admin/tests/Feature/HasAdminSlugTest.php +++ b/packages/admin/tests/Feature/HasAdminSlugTest.php @@ -11,6 +11,7 @@ use Atrium\Admin\Models\Slug; use Atrium\Admin\Models\SlugHistory; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Handbook; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; @@ -19,6 +20,8 @@ final class HasAdminSlugTest extends TestCase { + use PinsExtensionSurface; + /** * @return array */ diff --git a/packages/admin/tests/Feature/HooksTest.php b/packages/admin/tests/Feature/HooksTest.php index 3a9355c9..69eaa495 100644 --- a/packages/admin/tests/Feature/HooksTest.php +++ b/packages/admin/tests/Feature/HooksTest.php @@ -75,6 +75,51 @@ public function test_filters_run_in_order_of_priority_and_pass_the_value_on(): v $this->assertTrue(Hook::has('acme.sources')); } + public function test_arguments_given_by_name_reach_the_listeners_and_filters_by_position(): void + { + $heard = []; + Hook::on('acme.named', function (int $first, string $second) use (&$heard): void { + $heard[] = "{$first} {$second}"; + }); + Hook::filter('acme.named.filter', fn (string $value, string $extra): string => $value.$extra); + + $everyone = []; + Hook::on('acme.*', function (string $event, array $payload) use (&$everyone): void { + $everyone = $payload; + }); + + Hook::fire('acme.named', order: 7, by: 'card'); + + $this->assertSame(['7 card'], $heard); + $this->assertSame([7, 'card'], $everyone, 'A listener of a pattern gets the arguments as a list too.'); + $this->assertSame('ab', Hook::apply('acme.named.filter', 'a', suffix: 'b')); + } + + public function test_a_filter_without_a_priority_runs_at_ten_between_nine_and_eleven(): void + { + Hook::filter('acme.order', fn (string $value): string => $value.'-eleven', 11); + Hook::filter('acme.order', fn (string $value): string => $value.'-default'); + Hook::filter('acme.order', fn (string $value): string => $value.'-nine', 9); + + $this->assertSame('start-nine-default-eleven', Hook::apply('acme.order', 'start')); + } + + public function test_a_filter_added_later_joins_the_ones_that_already_ran(): void + { + Hook::filter('acme.later', fn (string $value): string => $value.'-first'); + $this->assertSame('x-first', Hook::apply('acme.later', 'x')); + + Hook::filter('acme.later', fn (string $value): string => $value.'-second'); + $this->assertSame('x-first-second', Hook::apply('acme.later', 'x')); + } + + public function test_a_filter_may_be_the_name_of_a_function(): void + { + Hook::filter('acme.function', 'strtoupper'); + + $this->assertSame('ABC', Hook::apply('acme.function', 'abc')); + } + public function test_saving_and_deleting_a_record_in_the_panel_fires_the_core_hooks(): void { $saved = []; diff --git a/packages/admin/tests/Feature/ImageCaptchaExactTest.php b/packages/admin/tests/Feature/ImageCaptchaExactTest.php new file mode 100644 index 00000000..336198d6 --- /dev/null +++ b/packages/admin/tests/Feature/ImageCaptchaExactTest.php @@ -0,0 +1,365 @@ + */ + private array $drawn = []; + + /** @var list */ + private array $decrypted = []; + + protected function tearDown(): void + { + Str::createRandomStringsNormally(); + + parent::tearDown(); + } + + /** + * Every call is noted. 'low' answers with the lower limit, 'high' with + * the upper one, and an angle stays 0 in both: a turned picture is + * resampled, and the resampling differs between GD builds. + * + * @return Closure(int,int):int + */ + private function numbers(string $answer): Closure + { + return function (int $min, int $max) use ($answer): int { + $this->drawn[] = [$min, $max]; + + return $min < 0 ? 0 : ($answer === 'high' ? $max : $min); + }; + } + + private function captcha(string $answer = 'low', bool $gd = true): ImageCaptcha + { + $encrypter = new class($this->decrypted) implements Encrypter + { + /** @param list $decrypted */ + public function __construct(private array &$decrypted) {} + + public function encrypt($value, $serialize = true): string + { + return 'sealed:'.json_encode($value); + } + + public function decrypt($payload, $unserialize = true): mixed + { + $this->decrypted[] = $payload; + + if (! is_string($payload) || ! str_starts_with($payload, 'sealed:')) { + throw new DecryptException('not ours'); + } + + return json_decode(substr($payload, 7), true); + } + + public function getKey(): string + { + return 'key'; + } + + public function getAllKeys(): array + { + return ['key']; + } + + public function getPreviousKeys(): array + { + return []; + } + }; + + return new ImageCaptcha($encrypter, $this->app['cache']->store('array'), $gd, $this->numbers($answer)); + } + + /** + * @return list + */ + private function pixels(string $png): array + { + $image = imagecreatefromstring($png); + $this->assertInstanceOf(\GdImage::class, $image); + $this->assertSame([150, 50], [imagesx($image), imagesy($image)]); + + $pixels = []; + + for ($y = 0; $y < 50; $y++) { + for ($x = 0; $x < 150; $x++) { + $pixels[] = imagecolorat($image, $x, $y) & 0xFFFFFF; + } + } + + return $pixels; + } + + private function question(string $q = '3 + 4', int $a = 7, int $in = 60): string + { + return 'sealed:'.json_encode(['q' => $q, 'a' => $a, 'n' => 'nonce', 'e' => now()->addSeconds($in)->getTimestamp()]); + } + + private function request(mixed $token, mixed $answer): Request + { + return Request::create('/form', 'POST', [ImageCaptcha::TOKEN => $token, CaptchaManager::FIELD => $answer]); + } + + /** + * @return array{list,list} + */ + private function picture(string $answer, string $q): array + { + $this->drawn = []; + $png = $this->captcha($answer)->image($this->question($q)); + $this->assertIsString($png); + + return [$this->pixels($png), $this->drawn]; + } + + /** + * @param list $calls + * @return array + */ + private function counted(array $calls): array + { + $counts = array_count_values(array_map(static fn (array $call): string => $call[0].','.$call[1], $calls)); + ksort($counts); + + return $counts; + } + + // ---- the widget ------------------------------------------------------------------------------ + + /** + * @return array + */ + public static function widgets(): array + { + return [ + 'a picture of the lowest sum' => ['low', true, 1, 1], + 'a picture of the highest sum' => ['high', true, 9, 9], + 'text of the lowest sum' => ['low', false, 1, 1], + 'text of the highest sum' => ['high', false, 9, 9], + ]; + } + + #[DataProvider('widgets')] + public function test_the_widget_is_exactly_the_question_the_token_and_the_answer_field(string $answer, bool $gd, int $a, int $b): void + { + $this->travelTo('2026-03-04 10:00:00'); + $lengths = []; + Str::createRandomStringsUsing(function (int $length) use (&$lengths): string { + $lengths[] = $length; + + return str_repeat((string) count($lengths), $length); + }); + + $html = (string) $this->captcha($answer, $gd)->widget(); + + $token = 'sealed:'.json_encode(['q' => "$a + $b", 'a' => $a + $b, 'n' => str_repeat('1', 20), 'e' => now()->addMinutes(10)->getTimestamp()]); + $question = $gd + ? ''.e(__('atrium::captcha.image')).'' + : "$a + $b = ?"; + + $this->assertSame( + ''.$question.'' + .'' + .'' + .'', + $html, + ); + $this->assertSame([20, 6], $lengths); + $this->assertSame([[1, 9], [1, 9]], $this->drawn); + } + + public function test_a_question_lives_for_the_configured_minutes(): void + { + $this->travelTo('2026-03-04 10:00:00'); + $expires = static fn (string $html): int => json_decode(substr(html_entity_decode(preg_match('/name="captcha_token" value="([^"]+)"/', $html, $m) === 1 ? $m[1] : ''), 7), true)['e']; + + // Nothing configured: ten minutes. + config(['atrium.captcha' => []]); + $this->assertSame(now()->addMinutes(10)->getTimestamp(), $expires((string) $this->captcha()->widget())); + + foreach ([0 => 1, 1 => 1, 2 => 2, 3 => 3, 25 => 25] as $configured => $minutes) { + config(['atrium.captcha.image.ttl' => $configured]); + + $this->assertSame(now()->addMinutes($minutes)->getTimestamp(), $expires((string) $this->captcha()->widget()), "ttl {$configured}"); + } + } + + // ---- the answer ------------------------------------------------------------------------------ + + public function test_a_right_answer_is_taken_once_and_remembered_for_the_lifetime_of_the_question(): void + { + $this->travelTo('2026-03-04 10:00:00'); + config(['atrium.captcha.image.ttl' => 5]); + $captcha = $this->captcha(); + $token = $this->question(); + + $this->assertTrue($captcha->verify($this->request($token, '7'))); + $this->assertTrue($this->app['cache']->store('array')->get('atrium-captcha:nonce'), 'what is kept is a plain true under the nonce'); + + $this->assertFalse($captcha->verify($this->request($token, '7')), 'used up'); + + $this->travel(4)->minutes(); + $this->assertFalse($captcha->verify($this->request($token, '7')), 'still remembered a minute before the lifetime ends'); + + $this->travel(2)->minutes(); + $this->assertNull($this->app['cache']->store('array')->get('atrium-captcha:nonce'), 'forgotten after the configured minutes'); + } + + public function test_a_wrong_answer_is_refused_and_uses_the_question_up(): void + { + $captcha = $this->captcha(); + $token = $this->question(); + + $this->assertFalse($captcha->verify($this->request($token, '8'))); + $this->assertFalse($captcha->verify($this->request($token, '7'))); + } + + public function test_the_answer_is_trimmed_and_compared_as_text(): void + { + $captcha = $this->captcha(); + + $this->assertTrue($captcha->verify($this->request($this->question(), " 7 \n"))); + $this->assertFalse($captcha->verify($this->request($this->question(a: 7), '07'))); + $this->assertFalse($captcha->verify($this->request($this->question(a: 7), '7.0'))); + $this->assertFalse($captcha->verify($this->request($this->question(a: 7), ''))); + } + + public function test_an_answer_that_is_not_text_is_refused_without_using_the_question_up(): void + { + $captcha = $this->captcha(); + $token = $this->question(); + + $this->assertFalse($captcha->verify($this->request($token, ['7']))); + $this->assertFalse($captcha->verify($this->request($token, null))); + $this->assertTrue($captcha->verify($this->request($token, '7')), 'the question was still there'); + } + + /** + * @return array + */ + public static function badTokens(): array + { + return [ + 'none' => [null], + 'empty' => [''], + 'a list' => [['sealed:{}']], + 'a number' => [7], + 'not ours' => ['forged'], + 'not an array' => ['sealed:"text"'], + 'no sum' => ['sealed:{"a":7,"n":"nonce","e":9999999999}'], + 'no answer' => ['sealed:{"q":"3 + 4","n":"nonce","e":9999999999}'], + 'an empty answer' => ['sealed:{"q":"3 + 4","a":null,"n":"nonce","e":9999999999}'], + 'no nonce' => ['sealed:{"q":"3 + 4","a":7,"e":9999999999}'], + 'no expiry' => ['sealed:{"q":"3 + 4","a":7,"n":"nonce"}'], + 'expired a second ago' => ['expired'], + ]; + } + + #[DataProvider('badTokens')] + public function test_a_token_that_is_not_a_live_question_is_refused_and_draws_nothing(mixed $token): void + { + $this->travelTo('2026-03-04 10:00:00'); + $token = $token === 'expired' ? $this->question(in: -1) : $token; + $captcha = $this->captcha(); + + $this->assertFalse($captcha->verify($this->request($token, '7'))); + $this->assertNull($captcha->image($token)); + $this->assertNull($this->app['cache']->store('array')->get('atrium-captcha:nonce')); + } + + public function test_a_token_that_is_not_text_never_reaches_the_decryption(): void + { + $captcha = $this->captcha(); + + foreach ([null, '', ['sealed:{}'], 7] as $token) { + $this->assertFalse($captcha->verify($this->request($token, '7'))); + $this->assertNull($captcha->image($token)); + } + + $this->assertSame([], $this->decrypted); + + $captcha->image('forged'); + $this->assertSame(['forged'], $this->decrypted); + } + + public function test_a_question_is_live_until_the_second_it_expires(): void + { + $this->travelTo('2026-03-04 10:00:00'); + $captcha = $this->captcha(); + + $this->assertTrue($captcha->verify($this->request($this->question(in: 0), '7')), 'expires now: still good'); + $this->assertFalse($captcha->verify($this->request($this->question(in: -1), '7'))); + } + + // ---- the picture ------------------------------------------------------------------------------ + + public function test_without_gd_there_is_no_picture(): void + { + $this->assertNull($this->captcha('low', false)->image($this->question())); + } + + public function test_the_picture_is_the_sum_drawn_with_the_lowest_numbers(): void + { + [$pixels, $calls] = $this->picture('low', '3 + 4'); + + // Noise lands on the corner, so the rest of the picture is the plain background and the five signs. + $this->assertSame(0x3C3C3C, $pixels[0], 'the last noise dot, on the corner'); + $this->assertSame(0xE1E1E1, $pixels[149], 'the background'); + $this->assertSame(0xE1E1E1, $pixels[49 * 150 + 149], 'the background'); + $this->assertSame('4fa27fa9080c0c5a29b93ee66f0fc17e50cbbab9', sha1(implode(',', $pixels))); + $this->assertSame([ + '-20,20' => 5, '0,149' => 250, '0,150' => 12, '0,49' => 250, '0,50' => 12, '1,2' => 6, '1,4' => 5, + '120,190' => 18, '2,24' => 5, '20,90' => 15, '225,250' => 3, '24,30' => 5, '60,200' => 750, + ], $this->counted($calls)); + } + + public function test_the_picture_is_the_sum_drawn_with_the_highest_numbers(): void + { + [$pixels, $calls] = $this->picture('high', '3 + 4'); + + $this->assertSame(0xC8C8C8, $pixels[49 * 150 + 149], 'a noise dot on the far corner'); + $this->assertSame(0xFAFAFA, $pixels[0], 'the background'); + $this->assertSame('b2f8d0c0c4b65c7674ad20e277d627e9d4b05f64', sha1(implode(',', $pixels))); + $this->assertSame([ + '-20,20' => 5, '0,149' => 250, '0,150' => 12, '0,49' => 250, '0,50' => 12, '1,2' => 6, '1,4' => 5, + '120,190' => 18, '2,18' => 5, '20,90' => 15, '225,250' => 3, '24,30' => 5, '60,200' => 750, + ], $this->counted($calls)); + } + + public function test_a_longer_sum_draws_a_sign_more_for_every_character_but_the_spaces(): void + { + [, $calls] = $this->picture('low', '3 + 4'); + [, $more] = $this->picture('low', '33 + 44'); + + $this->assertSame(5, $this->counted($calls)['-20,20']); + $this->assertSame(7, $this->counted($more)['-20,20']); + } +} diff --git a/packages/admin/tests/Feature/IndexMediaTest.php b/packages/admin/tests/Feature/IndexMediaTest.php index 683ad431..1e546993 100644 --- a/packages/admin/tests/Feature/IndexMediaTest.php +++ b/packages/admin/tests/Feature/IndexMediaTest.php @@ -85,7 +85,10 @@ public function test_no_upload_folder_means_nothing_to_add(): void { Storage::fake('public')->put('other/file.txt', 'x'); - $this->artisan('atrium:media:index')->expectsOutput('No files found.')->assertSuccessful(); + $this->artisan('atrium:media:index') + ->expectsOutput('No files found.') + ->doesntExpectOutput('Added: 0') + ->assertSuccessful(); $this->assertSame(0, MediaItem::query()->count()); } @@ -95,12 +98,14 @@ public function test_a_dry_run_lists_and_adds_nothing(): void $disk = Storage::fake('public'); $disk->put('uploads/a.png', 'png'); $disk->put('uploads/b.png', 'png'); + $disk->put('uploads/c.png', 'png'); MediaItem::query()->create(['name' => 'a.png', 'url' => '/storage/uploads/a.png', 'disk' => 'public', 'path' => 'uploads/a.png', 'extension' => 'png', 'size' => 3, 'is_image' => true]); $this->artisan('atrium:media:index', ['--dry-run' => true]) ->expectsOutput(' /storage/uploads/b.png') + ->expectsOutput(' /storage/uploads/c.png') ->doesntExpectOutput(' /storage/uploads/a.png') - ->expectsOutput('Would be added: 1') + ->expectsOutput('Would be added: 2') ->assertSuccessful(); $this->assertSame(['/storage/uploads/a.png'], MediaItem::query()->pluck('url')->all()); diff --git a/packages/admin/tests/Feature/InstallCommandTest.php b/packages/admin/tests/Feature/InstallCommandTest.php index 4c7f3bd9..72361a5e 100644 --- a/packages/admin/tests/Feature/InstallCommandTest.php +++ b/packages/admin/tests/Feature/InstallCommandTest.php @@ -19,8 +19,11 @@ use Illuminate\Contracts\Console\Kernel as ConsoleKernel; use Illuminate\Filesystem\Filesystem; use Illuminate\Foundation\Console\ClosureCommand; +use Illuminate\Support\Facades\Artisan; use Illuminate\Testing\PendingCommand; +use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; +use Symfony\Component\Console\Output\BufferedOutput; /** * atrium:install: from `composer require` to a working panel. Publishing, @@ -34,6 +37,9 @@ final class InstallCommandTest extends TestCase /** @var array the stand-in commands, in the order they ran */ private array $ran = []; + /** @var array the exit code a stand-in command gives, 0 by default */ + private array $exits = []; + protected function defineEnvironment($app): void { parent::defineEnvironment($app); @@ -55,11 +61,14 @@ protected function setUp(): void // Inside the callback $this is the command; the list is shared by reference. $ran = &$this->ran; + $exits = &$this->exits; foreach (['vendor:publish {--tag=} {--force}', 'migrate {--force}', 'storage:link'] as $signature) { - $this->app->make(ConsoleKernel::class)->registerCommand(new ClosureCommand($signature, function () use (&$ran, $signature): void { + $this->app->make(ConsoleKernel::class)->registerCommand(new ClosureCommand($signature, function () use (&$ran, &$exits, $signature): int { $tag = $this->hasOption('tag') ? $this->option('tag') : null; $force = $this->hasOption('force') && $this->option('force'); $ran[] = strtok($signature, ' ').($tag ? " {$tag}" : '').($force ? ' --force' : ''); + + return $exits[strtok($signature, ' ')] ?? 0; })); } } @@ -96,6 +105,7 @@ public function test_a_fresh_install_publishes_migrates_links_and_creates_the_fi $this->install() ->expectsOutputToContain('Create the first administrator.') ->expectsOutputToContain('Atrium is ready: http://localhost/admin') + ->doesntExpectOutputToContain('is served instead') ->assertSuccessful(); $this->assertSame([ @@ -202,4 +212,81 @@ public function test_demo_without_migrations_asks_to_migrate_first(): void $this->assertSame(0, Post::query()->count()); $this->assertSame(['acme/atrium-shelves'], config('atrium.modules')); } + + /** + * What the command printed, as one text. + * + * @param array $options + */ + private function printed(array $options = []): string + { + $output = new BufferedOutput; + Artisan::call('atrium:install', $options + ['--name' => 'Ann', '--email' => 'ann@example.com', '--password' => 'long-enough'], $output); + + return $output->fetch(); + } + + /** + * @return array + */ + public static function exitCodes(): array + { + return ['succeeds' => [0, 'DONE'], 'fails' => [1, 'FAIL']]; + } + + #[DataProvider('exitCodes')] + public function test_every_step_is_reported_by_what_its_command_returned(int $exit, string $result): void + { + $this->exits = ['vendor:publish' => $exit, 'migrate' => $exit, 'storage:link' => $exit]; + + $printed = $this->printed(); + + foreach (['Publishing config', 'Publishing assets', 'Publishing Sanctum migration', 'Running migrations', 'Linking public/storage'] as $step) { + $this->assertMatchesRegularExpression('/'.preg_quote($step, '/').'[ .]*\S* '.$result.'/', $printed, $step); + } + } + + public function test_the_first_administrator_and_the_closing_line_stand_apart_from_the_steps(): void + { + $printed = $this->printed(); + + $this->assertMatchesRegularExpression('/DONE\s*\n\s*\n\s*INFO\s+Create the first administrator\./', $printed); + $this->assertMatchesRegularExpression('/\n\s*\n\s*INFO\s+Atrium is ready/', $printed); + } + + public function test_an_option_left_out_is_asked_for_by_the_user_command(): void + { + $this->artisan('atrium:install', ['--email' => 'ann@example.com', '--password' => 'long-enough']) + ->expectsQuestion('Enter admin name', 'Asked Ann') + ->assertSuccessful(); + + $this->assertSame('Asked Ann', AdminUser::query()->where('email', 'ann@example.com')->sole()->name); + } + + public function test_the_stock_robots_txt_is_removed_with_a_step_and_no_warning(): void + { + file_put_contents($this->root.'/public/robots.txt', "User-agent: *\nDisallow:\n"); + + $printed = $this->printed(); + + $this->assertMatchesRegularExpression('/Removing public\/robots\.txt .*DONE/', $printed); + $this->assertStringNotContainsString('is served instead', $printed); + } + + public function test_demo_steps_are_reported_as_done_and_a_module_with_content_does_not_hide_one_without(): void + { + $this->onlyModules( + new Module(name: 'acme/atrium-shelves', demo: ShelfDemoSeeder::class, suggests: ['acme/atrium-brands']), + new Module(name: 'acme/atrium-brands', demo: BrandDemoSeeder::class), + ); + Post::query()->create(['name' => 'Demo shelf']); + + $printed = $this->printed(['--demo' => true]); + + $this->assertMatchesRegularExpression('/Installing acme\/atrium-shelves[ .]*\S* DONE/', $printed); + $this->assertMatchesRegularExpression('/Filling acme\/atrium-brands[ .]*\S* DONE/', $printed); + $this->assertMatchesRegularExpression('/Filling acme\/atrium-shelves[ .]*\S* DONE/', $printed); + $this->assertStringNotContainsString('nothing was added', $printed); + $this->assertSame(['Demo shelf', 'Demo brand'], Post::query()->orderBy('id')->pluck('name')->all()); + } } diff --git a/packages/admin/tests/Feature/LanguageExactnessTest.php b/packages/admin/tests/Feature/LanguageExactnessTest.php new file mode 100644 index 00000000..b47feed7 --- /dev/null +++ b/packages/admin/tests/Feature/LanguageExactnessTest.php @@ -0,0 +1,108 @@ + + */ + private function fields(): array + { + $fields = []; + + foreach (Language::getAdministrationFields() as $field) { + $fields[$field->getName().($field->shouldShowOnEdit() ? '' : ':create')] = $field; + } + + return $fields; + } + + public function test_the_fields_and_their_limits(): void + { + $fields = $this->fields(); + + $this->assertSame(['name', 'code:create', 'code', 'active', 'is_default', 'sort'], array_keys($fields)); + $this->assertTrue($fields['name']->isRequired()); + $this->assertSame(255, $fields['name']->getMaxLength()); + $this->assertContains('string', $fields['code:create']->getValidationRules()); + $this->assertContains('max:12', $fields['code:create']->getValidationRules()); + $this->assertTrue($fields['active']->getDefault()); + $this->assertFalse($fields['is_default']->getDefault()); + $this->assertSame(500, $fields['sort']->getDefault()); + } + + public function test_the_flags_are_booleans(): void + { + $language = Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'active' => 1]); + + $this->assertTrue($language->fresh()->active); + $this->assertTrue(Language::query()->where('code', 'de')->sole()->active); + } + + public function test_the_default_language_is_always_active(): void + { + $language = Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'active' => false, 'is_default' => true]); + + $this->assertTrue($language->active); + $this->assertTrue($language->fresh()->active); + $this->assertFalse(Language::query()->where('code', 'en')->sole()->is_default); + } + + public function test_the_code_of_a_saved_language_cannot_be_changed(): void + { + $language = Language::query()->create(['code' => 'de', 'name' => 'Deutsch']); + $language->code = 'fr'; + $language->save(); + + $this->assertSame('de', $language->code); + $this->assertSame('de', $language->fresh()->code); + } + + public function test_saving_and_deleting_a_language_empty_the_caches(): void + { + $after = function (callable $change): array { + app(ContentLanguages::class)->all(); + $before = Cache::get('atrium.sitemap.version'); + DB::table('admin_languages')->where('code', 'en')->update(['name' => 'Changed']); + + $change(); + + return [ + (string) app(ContentLanguages::class)->all()->firstWhere('code', 'en')?->name, + $before === Cache::get('atrium.sitemap.version') ? 'stale' : 'fresh', + ]; + }; + + $this->assertSame(['Changed', 'fresh'], $after(fn () => Language::query()->create(['code' => 'de', 'name' => 'Deutsch']))); + + $language = Language::query()->where('code', 'de')->sole(); + DB::table('admin_languages')->where('code', 'en')->update(['name' => 'English']); + $this->assertSame(['Changed', 'fresh'], $after(fn () => $language->delete())); + } + + public function test_hreflang_upcases_everything_after_the_first_dash(): void + { + $this->assertSame('pt-BR', (new Language(['code' => 'pt-br']))->hreflang()); + $this->assertSame('zh-HANT-TW', (new Language(['code' => 'zh-hant-tw']))->hreflang()); + $this->assertSame('en', (new Language(['code' => 'en']))->hreflang()); + } +} diff --git a/packages/admin/tests/Feature/LocaleTest.php b/packages/admin/tests/Feature/LocaleTest.php index 24233f03..d010a154 100644 --- a/packages/admin/tests/Feature/LocaleTest.php +++ b/packages/admin/tests/Feature/LocaleTest.php @@ -10,10 +10,13 @@ namespace Atrium\Admin\Tests\Feature; use Atrium\Admin\Support\Locales; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\TestCase; final class LocaleTest extends TestCase { + use PinsExtensionSurface; + public function test_a_guest_gets_the_browser_language_when_the_panel_has_it(): void { $response = $this->get('/admin/login', ['Accept-Language' => 'ru-RU,ru;q=0.9,en;q=0.8']); @@ -31,6 +34,17 @@ public function test_an_unknown_browser_language_falls_back_to_the_configured_de $this->assertSame('de', $response->inertiaProps('locale')); } + public function test_a_default_that_is_not_text_or_not_available_falls_back_to_english(): void + { + foreach ([null, 5, 'xx'] as $configured) { + config(['atrium.locale' => $configured]); + + $response = $this->get('/admin/login', ['Accept-Language' => 'sw-KE,sw;q=0.9']); + + $this->assertSame('en', $response->inertiaProps('locale'), var_export($configured, true)); + } + } + public function test_regional_codes_are_matched(): void { $this->assertSame('pt_BR', $this->get('/admin/login', ['Accept-Language' => 'pt-BR'])->inertiaProps('locale')); @@ -44,6 +58,11 @@ public function test_the_switch_on_the_sign_in_page_is_remembered_for_the_sessio $this->assertSame('uk', $this->get('/admin/login')->inertiaProps('locale')); } + public function test_a_language_is_required(): void + { + $this->from('/admin/login')->post('/admin/locale', [])->assertSessionHasErrors('locale'); + } + public function test_an_admin_keeps_the_language_on_the_account(): void { $admin = $this->admin(); diff --git a/packages/admin/tests/Feature/LoginTest.php b/packages/admin/tests/Feature/LoginTest.php index e6f10e2c..e57771b4 100644 --- a/packages/admin/tests/Feature/LoginTest.php +++ b/packages/admin/tests/Feature/LoginTest.php @@ -9,7 +9,10 @@ namespace Atrium\Admin\Tests\Feature; +use Atrium\Admin\Http\Requests\Auth\LoginRequest; use Atrium\Admin\Tests\TestCase; +use Illuminate\Support\Facades\RateLimiter; +use Illuminate\Validation\ValidationException; use Inertia\Testing\AssertableInertia; use PHPUnit\Framework\Attributes\DataProvider; @@ -189,6 +192,19 @@ public function test_signing_out_ends_the_session(): void $this->get('/admin')->assertRedirect('/admin/login'); } + public function test_signing_out_leaves_the_session_a_new_csrf_token(): void + { + $this->actingAs($this->admin(), 'admin') + ->withSession(['_token' => 'old-token']) + ->post('/admin/logout') + ->assertRedirect('/admin/login'); + + $token = $this->app['session.store']->token(); + + $this->assertNotEmpty($token); + $this->assertNotSame('old-token', $token); + } + public function test_guests_cannot_sign_out(): void { $this->post('/admin/logout')->assertRedirect('/admin/login'); @@ -220,4 +236,38 @@ public function test_an_admin_switched_off_mid_session_gets_403_in_json(): void $this->getJson('/admin/posts')->assertForbidden()->assertJsonPath('message', 'Your account is deactivated.'); $this->assertGuest('admin'); } + + public function test_the_throttle_key_is_the_lower_case_email_and_the_address_and_it_locks_after_five_hits(): void + { + $request = LoginRequest::create('/admin/login', 'POST', ['email' => 'Admin@Example.com'], server: ['REMOTE_ADDR' => '10.1.2.3']); + + $this->assertSame('admin@example.com|10.1.2.3', $request->throttleKey()); + + $request->ensureIsNotRateLimited(); + for ($i = 0; $i < 4; $i++) { + RateLimiter::hit($request->throttleKey()); + } + $request->ensureIsNotRateLimited(); + + RateLimiter::hit($request->throttleKey()); + try { + $request->ensureIsNotRateLimited(); + $this->fail('Five hits did not lock the key.'); + } catch (ValidationException $e) { + $this->assertSame(['email' => [__('atrium::auth.throttle', ['seconds' => 60])]], $e->errors()); + } + } + + public function test_a_guard_whose_provider_does_not_exist_refuses_everyone_on_the_email_field(): void + { + config(['auth.guards.admin.provider' => 'nowhere']); + $request = LoginRequest::create('/admin/login', 'POST', ['email' => 'admin@example.com', 'password' => 'x']); + + try { + $request->validateCredentials(); + $this->fail('A missing provider let someone in.'); + } catch (ValidationException $e) { + $this->assertSame(['email' => [__('atrium::auth.failed')]], $e->errors()); + } + } } diff --git a/packages/admin/tests/Feature/MakeModuleCommandTest.php b/packages/admin/tests/Feature/MakeModuleCommandTest.php index 3618cb6c..cce91f62 100644 --- a/packages/admin/tests/Feature/MakeModuleCommandTest.php +++ b/packages/admin/tests/Feature/MakeModuleCommandTest.php @@ -89,4 +89,45 @@ public function test_a_model_that_exists_is_kept_unless_forced(): void $this->assertStringContainsString('class Brochure extends Model', (string) file_get_contents($this->root.'/app/Models/Brochure.php')); $this->assertCount(1, glob($this->root.'/database/migrations/*_create_brochures_table.php') ?: []); } + + public function test_the_model_and_the_migration_carry_the_namespace_table_label_and_are_announced(): void + { + $this->artisan('atrium:make-module', ['name' => 'price list']) + ->expectsOutputToContain('Model ['.$this->root.'/app/Models/PriceList.php] created.') + ->expectsOutputToContain('Migration ['.$this->root.'/database/migrations/') + ->assertSuccessful(); + + $model = (string) file_get_contents($this->root.'/app/Models/PriceList.php'); + $this->assertStringContainsString("\nnamespace App\\Models;\n", $model); + $this->assertStringContainsString("return 'Price Lists';", $model); + $this->assertStringContainsString("->unique('price_lists', 'code')", $model); + + $migrations = glob($this->root.'/database/migrations/*') ?: []; + $this->assertCount(1, $migrations); + $this->assertMatchesRegularExpression('#/\d{4}_\d{2}_\d{2}_\d{6}_create_price_lists_table\.php$#', $migrations[0]); + $migration = (string) file_get_contents($migrations[0]); + $this->assertStringContainsString("Schema::create('price_lists'", $migration); + $this->assertStringContainsString("Schema::dropIfExists('price_lists')", $migration); + $this->assertStringNotContainsString('{{', $model.$migration); + } + + public function test_a_backslash_in_the_label_is_escaped_and_an_empty_label_falls_back_to_the_plural(): void + { + $this->artisan('atrium:make-module', ['name' => 'Brochure', '--label' => 'A\\B'])->assertSuccessful(); + $this->assertStringContainsString("return 'A\\\\B';", (string) file_get_contents($this->root.'/app/Models/Brochure.php')); + + $this->artisan('atrium:make-module', ['name' => 'Brochure', '--label' => '', '--force' => true])->assertSuccessful(); + $this->assertStringContainsString("return 'Brochures';", (string) file_get_contents($this->root.'/app/Models/Brochure.php')); + } + + public function test_a_stub_of_the_application_wins_over_the_packaged_one(): void + { + $this->app->setBasePath($this->root); + mkdir($this->root.'/stubs/atrium', 0777, true); + file_put_contents($this->root.'/stubs/atrium/model.stub', 'artisan('atrium:make-module', ['name' => 'Brochure', '--no-migration' => true])->assertSuccessful(); + + $this->assertSame('root.'/app/Models/Brochure.php')); + } } diff --git a/packages/admin/tests/Feature/McpTest.php b/packages/admin/tests/Feature/McpTest.php index e1e46f53..08db8f9e 100644 --- a/packages/admin/tests/Feature/McpTest.php +++ b/packages/admin/tests/Feature/McpTest.php @@ -13,6 +13,7 @@ use Atrium\Admin\Mcp\Tools\ListModules; use Atrium\Admin\Models\AdminRole; use Atrium\Admin\Models\AdminUser; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; use Illuminate\Testing\TestResponse; @@ -26,6 +27,8 @@ */ final class McpTest extends TestCase { + use PinsExtensionSurface; + protected function defineDatabaseMigrations(): void { parent::defineDatabaseMigrations(); @@ -280,6 +283,137 @@ public function test_tools_of_other_packages_join_the_server(): void ); } + public function test_every_tool_describes_its_arguments_exactly(): void + { + $module = ['description' => 'Module key from list_modules, e.g. "articles".', 'type' => 'string']; + $site = ['description' => 'Site code, when the record belongs to another site than this address.', 'type' => 'string']; + $id = ['description' => 'Record id.', 'type' => 'integer']; + + $expected = [ + 'list_modules' => [], + 'describe_module' => ['properties' => ['module' => $module], 'required' => ['module']], + 'list_records' => ['properties' => [ + 'module' => $module, + 'site' => $site, + 'search' => ['description' => 'Text to look for in the searchable columns.', 'type' => 'string'], + 'filter' => ['description' => 'Exact column values, e.g. {"active": 1, "section_id": 4}.', 'type' => 'object'], + 'sort' => ['description' => 'Column to sort by. Default: id.', 'type' => 'string'], + 'direction' => ['description' => 'Default: asc.', 'enum' => ['asc', 'desc'], 'type' => 'string'], + 'page' => ['description' => 'Page number, from 1.', 'type' => 'integer'], + 'per_page' => ['description' => 'Records per page, 1 to 100. Default: 20.', 'type' => 'integer'], + ], 'required' => ['module']], + 'get_record' => ['properties' => ['module' => $module, 'site' => $site, 'id' => $id], 'required' => ['module', 'id']], + 'create_record' => ['properties' => [ + 'module' => $module, + 'site' => $site, + 'data' => ['description' => 'Field values keyed by field name.', 'type' => 'object'], + ], 'required' => ['module', 'data']], + 'update_record' => ['properties' => [ + 'module' => $module, + 'site' => $site, + 'id' => $id, + 'data' => ['description' => 'The fields to change, keyed by field name.', 'type' => 'object'], + ], 'required' => ['module', 'id', 'data']], + 'delete_record' => ['properties' => ['module' => $module, 'site' => $site, 'id' => $id], 'required' => ['module', 'id']], + ]; + + $tools = $this->mcp($this->token(['posts.view']), 'tools/list')->json('result.tools'); + $actual = []; + foreach ($tools as $tool) { + $schema = $tool['inputSchema']; + unset($schema['type']); + $actual[$tool['name']] = $schema === ['properties' => []] ? [] : $schema; + } + + $this->assertSame(array_keys($expected), array_keys($actual)); + foreach ($expected as $name => $schema) { + $this->assertEquals($schema, $actual[$name], $name); + $this->assertSame(array_keys($schema['properties'] ?? []), array_keys($actual[$name]['properties'] ?? []), "{$name}: order"); + } + } + + public function test_a_module_that_is_not_a_string_is_still_refused_by_name(): void + { + $token = $this->token(['posts.view'], ['posts:read']); + + $this->mcp($token, 'tools/call', ['name' => 'list_records', 'arguments' => ['module' => 123]]) + ->assertJsonPath('result.isError', true) + ->assertJsonPath('result.content.0.text', 'No module "123". See list_modules.'); + $this->mcp($token, 'tools/call', ['name' => 'describe_module', 'arguments' => ['module' => 123]]) + ->assertJsonPath('result.isError', true) + ->assertJsonPath('result.content.0.text', 'No module "123" for this token. See list_modules.'); + } + + public function test_an_empty_or_missing_site_adds_nothing_to_the_query(): void + { + $token = $this->token(['posts.view']); + + foreach ([['site' => ''], ['site' => null], []] as $extra) { + $this->assertSame(0, $this->callTool($token, 'list_records', ['module' => 'posts'] + $extra)['meta']['total']); + } + } + + public function test_unknown_modules_stay_closed_even_for_a_token_that_may_do_anything(): void + { + $owner = AdminUser::query()->forceCreate([ + 'name' => 'Root', 'email' => 'root@example.com', 'password' => 'secret-password', 'is_active' => true, 'is_superadmin' => true, + ]); + $token = $owner->createToken('all', ['*'])->plainTextToken; + + $this->mcp($token, 'tools/call', ['name' => 'describe_module', 'arguments' => ['module' => 'nope']]) + ->assertJsonPath('result.isError', true) + ->assertJsonPath('result.content.0.text', 'No module "nope" for this token. See list_modules.'); + $this->assertSame('Posts', $this->callTool($token, 'describe_module', ['module' => 'posts'])['label']); + } + + public function test_get_update_and_delete_take_the_id_as_a_number(): void + { + $post = Post::query()->create(['name' => 'Hello']); + $token = $this->token(['posts.view', 'posts.update', 'posts.delete'], ['posts:read', 'posts:write']); + + // Whatever arrives is made an integer first, so it can never add anything to the address. + $id = $post->id + 0.5; + + $this->assertSame($post->id, $this->callTool($token, 'get_record', ['module' => 'posts', 'id' => $id])['data']['id']); + $this->assertSame('Hi', $this->callTool($token, 'update_record', ['module' => 'posts', 'id' => $id, 'data' => ['name' => 'Hi']])['data']['name']); + $this->mcp($token, 'tools/call', ['name' => 'delete_record', 'arguments' => ['module' => 'posts', 'id' => $id]]) + ->assertJsonPath('result.isError', false); + $this->assertSame(0, Post::query()->count()); + } + + public function test_list_records_sends_only_what_was_asked_for(): void + { + foreach (['B', 'A'] as $i => $name) { + Post::query()->create(['name' => $name, 'sort' => $i]); + } + $token = $this->token(['posts.view']); + + // Empty values must not reach the API as filters: "sort" of "" would be an invalid column. + $found = $this->callTool($token, 'list_records', ['module' => 'posts', 'sort' => '', 'direction' => '', 'page' => null, 'per_page' => null, 'search' => null, 'filter' => []]); + $this->assertSame(['B', 'A'], array_column($found['data'], 'name')); + + $this->assertSame(['A', 'B'], array_column($this->callTool($token, 'list_records', ['module' => 'posts', 'sort' => 'name'])['data'], 'name')); + $this->assertSame(['B'], array_column($this->callTool($token, 'list_records', ['module' => 'posts', 'page' => 1, 'per_page' => 1])['data'], 'name')); + $this->assertSame(['A'], array_column($this->callTool($token, 'list_records', ['module' => 'posts', 'page' => 2, 'per_page' => 1])['data'], 'name')); + $this->assertSame(['B', 'A'], array_column($this->callTool($token, 'list_records', ['module' => 'posts', 'sort' => 'sort', 'direction' => 'asc'])['data'], 'name')); + } + + public function test_a_config_without_extra_tools_changes_nothing(): void + { + $token = $this->token(['posts.view']); + + foreach ([null, []] as $value) { + config()->set('atrium.mcp.tools', $value); + + $names = array_column($this->mcp($token, 'tools/list')->json('result.tools'), 'name'); + + $this->assertSame( + ['list_modules', 'describe_module', 'list_records', 'get_record', 'create_record', 'update_record', 'delete_record'], + $names, + ); + } + } + /** * @param array $permissions * @param array $abilities diff --git a/packages/admin/tests/Feature/McpToolQueryTest.php b/packages/admin/tests/Feature/McpToolQueryTest.php new file mode 100644 index 00000000..dffe7265 --- /dev/null +++ b/packages/admin/tests/Feature/McpToolQueryTest.php @@ -0,0 +1,103 @@ +sent(new ListRecords, [ + 'module' => 'posts', 'site' => 'shop', 'search' => 'tea', 'filter' => ['active' => 1], 'sort' => 'name', + 'direction' => 'desc', 'page' => 2, 'per_page' => 5, + ]); + + $this->assertSame('GET', $seen->getMethod()); + $this->assertSame('/api/v1/posts', $seen->getPathInfo()); + $this->assertSame( + ['search' => 'tea', 'filter' => ['active' => 1], 'sort' => 'name', 'direction' => 'desc', 'page' => 2, 'per_page' => 5, 'site' => 'shop'], + $seen->query->all(), + ); + } + + public function test_list_records_leaves_out_what_is_null_empty_or_an_empty_list(): void + { + $this->assertSame([], $this->sent(new ListRecords, ['module' => 'posts'])->query->all()); + $this->assertSame([], $this->sent(new ListRecords, [ + 'module' => 'posts', 'site' => '', 'search' => '', 'filter' => [], 'sort' => null, 'direction' => '', 'page' => null, 'per_page' => null, + ])->query->all()); + } + + public function test_the_site_is_sent_as_text_and_only_when_there_is_one(): void + { + $this->assertSame([], $this->sent(new GetRecord, ['module' => 'posts', 'id' => 1, 'site' => null])->query->all()); + $this->assertSame(['site' => '5'], $this->sent(new GetRecord, ['module' => 'posts', 'id' => 1, 'site' => 5])->query->all()); + $this->assertSame(['site' => '0'], $this->sent(new GetRecord, ['module' => 'posts', 'id' => 1, 'site' => '0'])->query->all()); + } + + public function test_list_records_keeps_values_that_are_falsy_but_not_empty(): void + { + $this->assertSame( + ['search' => '0', 'page' => 0], + $this->sent(new ListRecords, ['module' => 'posts', 'search' => '0', 'page' => 0])->query->all(), + ); + } + + public function test_get_and_delete_address_one_record(): void + { + $seen = $this->sent(new GetRecord, ['module' => 'posts', 'id' => 7, 'site' => 'shop']); + $this->assertSame(['GET', '/api/v1/posts/7', ['site' => 'shop']], [$seen->getMethod(), $seen->getPathInfo(), $seen->query->all()]); + + $seen = $this->sent(new DeleteRecord, ['module' => 'posts', 'id' => 7]); + $this->assertSame(['DELETE', '/api/v1/posts/7', []], [$seen->getMethod(), $seen->getPathInfo(), $seen->query->all()]); + } + + public function test_create_and_update_send_the_data_as_the_body(): void + { + $seen = $this->sent(new CreateRecord, ['module' => 'posts', 'data' => ['name' => 'Tea'], 'site' => 'shop']); + $this->assertSame(['POST', '/api/v1/posts', ['site' => 'shop'], '{"name":"Tea"}'], [$seen->getMethod(), $seen->getPathInfo(), $seen->request->all(), $seen->getContent()]); + + $seen = $this->sent(new UpdateRecord, ['module' => 'posts', 'id' => 7, 'data' => ['name' => 'Tea']]); + $this->assertSame(['PATCH', '/api/v1/posts/7', [], '{"name":"Tea"}'], [$seen->getMethod(), $seen->getPathInfo(), $seen->request->all(), $seen->getContent()]); + + $seen = $this->sent(new CreateRecord, ['module' => 'posts']); + $this->assertSame('[]', $seen->getContent()); + + // Data that is not an object is still wrapped into a list, never handed on as a bare scalar. + $this->assertSame('["x"]', $this->sent(new CreateRecord, ['module' => 'posts', 'data' => 'x'])->getContent()); + $this->assertSame('["x"]', $this->sent(new UpdateRecord, ['module' => 'posts', 'id' => 1, 'data' => 'x'])->getContent()); + $this->assertSame('[]', $this->sent(new UpdateRecord, ['module' => 'posts', 'id' => 1])->getContent()); + } + + /** + * @param array $arguments + */ + private function sent(ListRecords|GetRecord|DeleteRecord|CreateRecord|UpdateRecord $tool, array $arguments): Request + { + $router = $this->recordingRouter(fn () => new Response('{}', 200)); + $tool->handle(new McpRequest($arguments), new ApiGateway($router)); + + return $router->seen; + } +} diff --git a/packages/admin/tests/Feature/MediaAndSeoModelsTest.php b/packages/admin/tests/Feature/MediaAndSeoModelsTest.php index f95ddd03..80f59780 100644 --- a/packages/admin/tests/Feature/MediaAndSeoModelsTest.php +++ b/packages/admin/tests/Feature/MediaAndSeoModelsTest.php @@ -13,6 +13,7 @@ use Atrium\Admin\Models\MediaCollection; use Atrium\Admin\Models\MediaItem; use Atrium\Admin\Models\SeoMeta; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Handbook; use Atrium\Admin\Tests\TestCase; use Illuminate\Support\Facades\Storage; @@ -20,6 +21,8 @@ final class MediaAndSeoModelsTest extends TestCase { + use PinsExtensionSurface; + public function test_the_effective_title_and_description_fall_back_in_order(): void { $meta = new SeoMeta(['title' => 'Title', 'og_title' => 'Share title', 'description' => 'Text', 'og_description' => 'Share text']); diff --git a/packages/admin/tests/Feature/ModuleCommandsTest.php b/packages/admin/tests/Feature/ModuleCommandsTest.php index d23feab1..cd2e1c39 100644 --- a/packages/admin/tests/Feature/ModuleCommandsTest.php +++ b/packages/admin/tests/Feature/ModuleCommandsTest.php @@ -9,14 +9,22 @@ namespace Atrium\Admin\Tests\Feature; +use Atrium\Admin\Facades\Hook; +use Atrium\Admin\Models\AdminRole; use Atrium\Admin\Modules\Module; use Atrium\Admin\Modules\Modules; +use Atrium\Admin\Tests\Fixtures\Page; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\Fixtures\ShelfDemoSeeder; use Atrium\Admin\Tests\TestCase; use Illuminate\Contracts\Console\Kernel as ConsoleKernel; use Illuminate\Filesystem\Filesystem; use Illuminate\Foundation\Console\ClosureCommand; +use Illuminate\Support\Facades\Artisan; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Schema; +use PHPUnit\Framework\Attributes\DataProvider; +use Symfony\Component\Console\Output\BufferedOutput; /** * atrium:module:install and atrium:module:remove where things go wrong: @@ -137,4 +145,188 @@ public function test_cached_config_and_routes_are_built_again_only_when_they_wer $this->artisan('atrium:module:remove', ['package' => self::SHELVES])->assertSuccessful(); $this->assertSame(['config:cache' => 1, 'route:cache' => 1], $this->built); } + + /** + * @return array + */ + public static function exitCodes(): array + { + return ['succeeds' => [0, 'DONE'], 'fails' => [1, 'FAIL']]; + } + + /** + * A module with a migrations folder and a migrate that only records how it was called. + * + * @param array> $calls + */ + private function crates(int $exit, array &$calls): string + { + $path = $this->root.'/crates'; + mkdir($path); + $this->app->make(Modules::class)->add(new Module(name: 'acme/atrium-crates', migrations: [$path])); + + foreach (['migrate', 'migrate:reset'] as $name) { + $this->app->make(ConsoleKernel::class)->registerCommand(new ClosureCommand($name.' {--path=*} {--realpath} {--force}', function () use (&$calls, $name, $exit): int { + $calls[] = [$name, $this->option('path'), $this->option('realpath'), $this->option('force')]; + + return $exit; + })); + } + + return $path; + } + + private function printed(string $command, array $options): string + { + $output = new BufferedOutput; + Artisan::call($command, $options, $output); + + return $output->fetch(); + } + + #[DataProvider('exitCodes')] + public function test_the_migrations_of_a_module_are_run_for_its_folder_and_reported_by_their_result(int $exit, string $result): void + { + $calls = []; + $path = $this->crates($exit, $calls); + + $printed = $this->printed('atrium:module:install', ['package' => 'acme/atrium-crates']); + + $this->assertSame([['migrate', [$path], true, true]], $calls); + $this->assertMatchesRegularExpression('/Running its migrations[ .]*\S* '.$result.'/', $printed); + } + + #[DataProvider('exitCodes')] + public function test_the_tables_of_a_module_are_dropped_for_its_folder_and_reported_by_their_result(int $exit, string $result): void + { + $calls = []; + $path = $this->crates($exit, $calls); + $this->printed('atrium:module:install', ['package' => 'acme/atrium-crates']); + $calls = []; + + $printed = $this->printed('atrium:module:remove', ['package' => 'acme/atrium-crates', '--delete-data' => true]); + + $this->assertSame([['migrate:reset', [$path], true, true]], $calls); + $this->assertMatchesRegularExpression('/Dropping its tables[ .]*\S* '.$result.'/', $printed); + } + + public function test_an_unknown_module_is_refused_with_the_modules_that_could_be_installed(): void + { + $printed = $this->printed('atrium:module:install', ['package' => 'acme/atrium-missing']); + + $this->assertStringContainsString('acme/atrium-missing is not an Atrium module Composer has installed.', $printed); + $this->assertStringContainsString(self::SHELVES, $printed); + + $this->artisan('atrium:module:install', ['package' => self::SHELVES])->assertSuccessful(); + $this->assertStringNotContainsString(self::SHELVES, $this->printed('atrium:module:install', ['package' => 'acme/atrium-missing'])); + } + + public function test_the_closing_line_names_the_keys_the_module_added_to_the_menu(): void + { + $this->app->make(Modules::class)->add(new Module(name: 'acme/atrium-posts', resources: [Post::class])); + + $this->assertStringContainsString( + 'acme/atrium-posts is installed. In the menu and the role form: posts.', + $this->printed('atrium:module:install', ['package' => 'acme/atrium-posts']), + ); + $this->assertStringContainsString( + 'acme/atrium-posts was installed already; its tables are up to date.', + $this->printed('atrium:module:install', ['package' => 'acme/atrium-posts']), + ); + } + + public function test_the_menu_keys_are_those_of_the_modules_that_can_be_administered_all_of_them(): void + { + $this->app->make(Modules::class)->add(new Module(name: 'acme/atrium-mixed', resources: [Post::class, 'Acme\\Missing', \stdClass::class, Page::class])); + + $this->assertStringContainsString( + 'acme/atrium-mixed is installed. In the menu and the role form: posts, pages', + $this->printed('atrium:module:install', ['package' => 'acme/atrium-mixed']), + ); + } + + public function test_the_package_name_is_trimmed_and_lowercased(): void + { + $this->artisan('atrium:module:install', ['package' => ' ACME/Atrium-Shelves '])->assertSuccessful(); + + $this->assertContains(self::SHELVES, (require $this->root.'/config/atrium.php')['modules']); + } + + public function test_the_installed_hook_is_fired_with_the_module(): void + { + $heard = []; + Hook::on('atrium.module.installed', static function (Module $module) use (&$heard): void { + $heard[] = $module->name; + }); + + $this->artisan('atrium:module:install', ['package' => self::SHELVES])->assertSuccessful(); + + $this->assertSame([self::SHELVES], $heard); + } + + public function test_a_submodule_is_filled_with_demo_content_only_when_its_parent_is(): void + { + $modules = $this->app->make(Modules::class); + $modules->add(new Module(name: 'acme/atrium-parent')); + $modules->add(new Module(name: 'acme/atrium-child', demo: ShelfDemoSeeder::class, parent: 'acme/atrium-parent')); + + $this->artisan('atrium:module:install', ['package' => 'acme/atrium-parent'])->assertSuccessful(); + $this->assertSame(0, Post::query()->count()); + + $this->artisan('atrium:module:remove', ['package' => 'acme/atrium-parent'])->assertSuccessful(); + $this->artisan('atrium:module:install', ['package' => 'acme/atrium-parent', '--demo' => true])->assertSuccessful(); + $this->assertSame(['Demo shelf'], Post::query()->pluck('name')->all()); + } + + public function test_a_permission_that_comes_with_another_goes_to_the_roles_that_have_it_once(): void + { + $this->app->make(Modules::class)->add(new Module(name: 'acme/atrium-orders', declaredPermissions: [ + 'orders.refund' => ['label' => 'Refund', 'with' => 'orders.view'], + 'orders.export' => ['label' => 'Export', 'with' => 'orders.view'], + 'orders.audit' => ['label' => 'Audit', 'with' => null], + ])); + $holder = AdminRole::query()->create(['name' => 'Holder', 'permissions' => ['orders.view', 'orders.view', 'posts.view']]); + $already = AdminRole::query()->create(['name' => 'Already', 'permissions' => ['orders.view', 'orders.refund', 'orders.export']]); + $other = AdminRole::query()->create(['name' => 'Other', 'permissions' => ['posts.view']]); + DB::table('admin_roles')->insert(['name' => 'Nothing', 'permissions' => 'null', 'created_at' => now(), 'updated_at' => now()]); + $nothing = AdminRole::query()->where('name', 'Nothing')->sole(); + $saved = []; + AdminRole::saved(static function (AdminRole $role) use (&$saved): void { + $saved[] = $role->name; + }); + + $this->artisan('atrium:module:install', ['package' => 'acme/atrium-orders'])->assertSuccessful(); + + $this->assertSame(['orders.view', 'posts.view', 'orders.refund', 'orders.export'], $holder->fresh()->permissions); + $this->assertSame(['orders.view', 'orders.refund', 'orders.export'], $already->fresh()->permissions); + $this->assertSame(['posts.view'], $other->fresh()->permissions); + $this->assertSame([], (array) $nothing->fresh()->permissions); + $this->assertSame(['Holder'], $saved, 'Only a role that lacked something was written.'); + } + + public function test_a_module_without_permissions_that_come_with_another_leaves_the_roles_alone(): void + { + $role = AdminRole::query()->create(['name' => 'Holder', 'permissions' => ['orders.view']]); + $saved = 0; + AdminRole::saved(static function () use (&$saved): void { + $saved++; + }); + $this->app->make(Modules::class)->add(new Module(name: 'acme/atrium-orders', declaredPermissions: ['orders.audit' => ['label' => 'Audit', 'with' => null]])); + + $this->artisan('atrium:module:install', ['package' => 'acme/atrium-orders'])->assertSuccessful(); + + $this->assertSame(0, $saved); + $this->assertSame(['orders.view'], $role->fresh()->permissions); + } + + public function test_the_permissions_step_is_skipped_when_the_roles_table_is_missing(): void + { + $this->app->make(Modules::class)->add(new Module(name: 'acme/atrium-orders', declaredPermissions: ['orders.refund' => ['label' => 'Refund', 'with' => 'orders.view']])); + Schema::drop('admin_role_user'); + Schema::drop('admin_roles'); + + $this->artisan('atrium:module:install', ['package' => 'acme/atrium-orders'])->assertSuccessful(); + + $this->assertContains('acme/atrium-orders', (require $this->root.'/config/atrium.php')['modules']); + } } diff --git a/packages/admin/tests/Feature/ModuleControllerExactnessTest.php b/packages/admin/tests/Feature/ModuleControllerExactnessTest.php new file mode 100644 index 00000000..7e97bf9d --- /dev/null +++ b/packages/admin/tests/Feature/ModuleControllerExactnessTest.php @@ -0,0 +1,188 @@ +resolving(Modules::class, static function (Modules $modules): void { + $modules->add(new Module('acme/atrium-zed', 'The last by label', title: 'Zed')); + $modules->add(new Module('acme/atrium-plain', 'Without settings', title: 'Plain')); + $modules->add(new Module('acme/atrium-child', 'A child with settings', settings: LabelSettings::class, title: 'Child', parent: 'acme/atrium-plain')); + $modules->add(new Module('acme/atrium-note', 'Settings per site', settings: NoteSettings::class, title: 'Note')); + $modules->add(Label::module()); + }); + + $app['config']->set('atrium.modules', ['acme/atrium-zed', 'acme/atrium-plain', 'acme/atrium-child', 'acme/atrium-note']); + + $this->root = sys_get_temp_dir().'/atrium-modules-exact-'.uniqid(); + mkdir($this->root.'/config', 0777, true); + copy(dirname(__DIR__, 2).'/config/atrium.php', $this->root.'/config/atrium.php'); + $app->useConfigPath($this->root.'/config'); + } + + protected function tearDown(): void + { + (new Filesystem)->deleteDirectory($this->root); + + parent::tearDown(); + } + + private function editor(array $permissions): AdminUser + { + $user = AdminUser::query()->create(['name' => 'Editor', 'email' => 'editor@example.com', 'password' => 'secret-password', 'is_active' => true]); + $user->roles()->attach(AdminRole::query()->create(['name' => 'Role', 'permissions' => $permissions])); + + return $user->fresh(); + } + + public function test_a_superadmin_sees_every_module_with_its_children_right_under_it(): void + { + $this->actingAs($this->admin(), 'admin')->get('/admin/modules') + ->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page + ->component('Admin/Modules/Index') + ->where('canManage', true) + ->where('title', __('atrium::modules.title')) + ->where('modules', [ + ['name' => 'acme/atrium-note', 'key' => 'note', 'label' => 'Note', 'description' => 'Settings per site', 'settings' => true, 'enabled' => true, 'parent' => null], + ['name' => 'acme/atrium-plain', 'key' => 'plain', 'label' => 'Plain', 'description' => 'Without settings', 'settings' => false, 'enabled' => true, 'parent' => null], + ['name' => 'acme/atrium-child', 'key' => 'child', 'label' => 'Child', 'description' => 'A child with settings', 'settings' => true, 'enabled' => true, 'parent' => 'acme/atrium-plain'], + ['name' => 'acme/atrium-zed', 'key' => 'zed', 'label' => 'Zed', 'description' => 'The last by label', 'settings' => false, 'enabled' => true, 'parent' => null], + ])); + } + + public function test_someone_who_sets_up_one_module_sees_only_that_one_and_a_child_without_its_parent_stands_alone(): void + { + $this->actingAs($this->editor(['child.settings']), 'admin')->get('/admin/modules') + ->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('canManage', false) + ->where('required', []) + ->where('modules', [ + ['name' => 'acme/atrium-child', 'key' => 'child', 'label' => 'Child', 'description' => 'A child with settings', 'settings' => true, 'enabled' => true, 'parent' => 'acme/atrium-plain'], + ])); + } + + public function test_a_module_with_nothing_to_set_up_does_not_hide_the_ones_after_it(): void + { + // "plain" has no settings and comes before "child" and "note" in the list. + $this->actingAs($this->editor(['note.settings', 'child.settings']), 'admin')->get('/admin/modules') + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('modules.0.key', 'child') + ->where('modules.1.key', 'note') + ->has('modules', 2)); + } + + public function test_the_settings_screen_is_given_the_module_its_fields_values_and_site(): void + { + $admin = $this->admin(); + + $response = $this->actingAs($admin, 'admin')->get('/admin/modules/note/settings', ['X-Inertia' => 'true', 'X-Inertia-Version' => '']); + $page = $response->json(); + + $this->assertSame('Admin/Modules/Settings', $page['component']); + $this->assertSame(['key' => 'note', 'name' => 'acme/atrium-note', 'label' => 'Note'], $page['props']['module']); + $this->assertSame(['motto', 'badge'], array_column($page['props']['fields'], 'name')); + $this->assertSame('Badge', $page['props']['fields'][1]['label']); + $this->assertSame(__('atrium::modules.settings_title', ['module' => 'Note']), $page['props']['title']); + $this->assertSame(['id', 'name'], array_keys($page['props']['site'])); + $this->assertStringContainsString('"values":{}', (string) $response->getContent(), 'No values yet: an object, not a list.'); + + $this->actingAs($admin, 'admin')->get('/admin/modules/child/settings') + ->assertInertia(fn (AssertableInertia $page) => $page->where('site', null)); + } + + public function test_the_settings_of_a_module_per_site_name_the_site_and_without_any_site_name_none(): void + { + $admin = $this->admin(); + $main = $this->app->make(Sites::class)->default(); + + $this->actingAs($admin, 'admin')->get('/admin/modules/note/settings') + ->assertInertia(fn (AssertableInertia $page) => $page->where('site', ['id' => $main->id, 'name' => $main->name])); + + DB::table('admin_sites')->delete(); + $this->app->make(Sites::class)->flush(); + + $this->actingAs($admin, 'admin')->get('/admin/modules/note/settings') + ->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page->where('site', null)); + } + + public function test_the_error_for_a_field_without_a_label_names_the_field(): void + { + $this->actingAs($this->admin(), 'admin') + ->from('/admin/modules/note/settings') + ->put('/admin/modules/note/settings', ['motto' => '']) + ->assertSessionHasErrors(['motto' => __('validation.required', ['attribute' => 'motto'])]); + } + + public function test_a_file_sent_for_a_field_is_checked_as_an_upload_and_a_path_as_a_path(): void + { + $admin = $this->admin(); + + $this->actingAs($admin, 'admin') + ->put('/admin/modules/note/settings', ['motto' => 'Hi', 'badge' => UploadedFile::fake()->create('badge.txt', 4, 'text/plain')]) + ->assertSessionHasErrors('badge'); + + $this->actingAs($admin, 'admin') + ->put('/admin/modules/note/settings', ['motto' => 'Hi', 'badge' => 'storage/badge.png']) + ->assertSessionHasNoErrors(); + } + + public function test_switching_on_a_module_runs_the_migrations_it_shipped_and_only_those(): void + { + // A stand-in for the real command, which would migrate the test database. + $runs = []; + $stand = new ClosureCommand('migrate {--path=*} {--realpath} {--force}', function () use (&$runs): void { + $runs[] = [$this->option('path'), $this->option('realpath'), $this->option('force')]; + }); + $this->app->make(ConsoleKernel::class)->registerCommand($stand); + + $this->app['config']->set('atrium.modules', [...config('atrium.modules'), 'acme/atrium-labels']); + $this->app['config']->set('atrium.disabled_modules', ['acme/atrium-zed', 'acme/atrium-labels']); + $admin = $this->admin(); + + $this->actingAs($admin, 'admin')->post('/admin/modules/zed/enable')->assertSessionHas('success'); + $this->assertSame([], $runs, 'A module with no migrations runs none.'); + + $this->actingAs($admin, 'admin')->post('/admin/modules/labels/enable')->assertSessionHas('success'); + $this->assertSame([[Label::module()->migrations, true, true]], $runs); + } +} diff --git a/packages/admin/tests/Feature/ModulePermissionsTest.php b/packages/admin/tests/Feature/ModulePermissionsTest.php index 0316c6d2..1ee16967 100644 --- a/packages/admin/tests/Feature/ModulePermissionsTest.php +++ b/packages/admin/tests/Feature/ModulePermissionsTest.php @@ -31,7 +31,15 @@ protected function defineEnvironment($app): void { parent::defineEnvironment($app); - $app->resolving(Modules::class, static fn (Modules $modules) => $modules->add(Label::module())); + $app->resolving(Modules::class, static function (Modules $modules): void { + $modules->add(Label::module()); + $modules->add(Module::fromComposer(['name' => 'acme/atrium-shop', 'type' => Modules::TYPE, 'extra' => ['atrium' => ['key' => 'store', 'permissions' => [ + 'refund' => 'Refund orders', + 'reports.export' => ['label' => 'Export reports'], + 'reports.archive' => 'atrium::menu', + 'reports.quiet' => '', + ]]]], '/tmp')); + }); $this->root = sys_get_temp_dir().'/atrium-permissions-'.uniqid(); mkdir($this->root.'/config', 0777, true); @@ -54,9 +62,9 @@ public function test_the_manifest_names_them_a_bare_action_belonging_to_the_modu ], Label::module()->declaredPermissions); $module = Module::fromComposer(['name' => 'acme/atrium-shop', 'extra' => ['atrium' => ['key' => 'store', 'permissions' => [ - 'refund' => 'Refund', 'Not a name!' => 'Skipped', 'a.b.c' => 'Skipped too', + 'refund' => 'Refund', ]]]], '/tmp'); $this->assertSame(['store.refund'], $module->permissions()); @@ -113,6 +121,29 @@ public function test_installing_gives_them_to_the_roles_they_come_with_and_remov $this->assertSame(['posts.view', 'posts.update'], $editor->fresh()->permissions); } + #[DefineEnvironment('installShop')] + public function test_a_permission_of_a_section_nobody_else_owns_opens_a_row_of_its_own_with_its_labels(): void + { + $sections = collect($this->app->make(Permissions::class)->sections())->keyBy('key'); + + // "refund" is the module's own: a row under the module's name. + $this->assertSame(['key' => 'store', 'label' => 'Store', 'actions' => ['refund'], 'labels' => ['refund' => 'Refund orders']], $sections['store']); + // "reports" is nobody's key: a row headlined from its name, in the order declared. + $this->assertSame( + ['key' => 'reports', 'label' => 'Reports', 'actions' => ['export', 'archive', 'quiet'], 'labels' => ['export' => 'Export reports', 'archive' => 'atrium::menu']], + $sections['reports'], + ); + $this->assertContains('reports.quiet', $this->app->make(Permissions::class)->all()); + } + + /** + * Installed before the app boots, so its routes are there. + */ + protected function installShop($app): void + { + $app['config']->set('atrium.modules', ['acme/atrium-shop']); + } + /** * Installed before the app boots, so its routes are there. */ diff --git a/packages/admin/tests/Feature/ModuleSettingsTest.php b/packages/admin/tests/Feature/ModuleSettingsTest.php index 63d6e518..a74df9d8 100644 --- a/packages/admin/tests/Feature/ModuleSettingsTest.php +++ b/packages/admin/tests/Feature/ModuleSettingsTest.php @@ -81,6 +81,34 @@ public function test_a_value_nobody_saved_is_the_fields_default(): void $this->assertSame(['color' => 'red', 'per_page' => null, 'show_count' => null], Setting::all('labels')); } + public function test_a_key_is_the_module_then_the_field_and_nothing_else_names_a_value(): void + { + $this->install(); + + $this->assertSame('red', Setting::get('labels.color')); + $this->assertSame('fallback', Setting::get('labels.color.extra', 'fallback'), 'Everything after the first dot is the field.'); + $this->assertSame('fallback', Setting::get('labels', 'fallback')); + $this->assertSame('fallback', Setting::get('', 'fallback')); + } + + public function test_a_value_saved_empty_is_the_default_but_zero_and_false_are_values(): void + { + $this->install(); + $settings = $this->app->make(Settings::class); + + $settings->save('labels', ['color' => '', 'per_page' => 0, 'show_count' => false]); + $settings->flush(); + $this->assertSame(['color' => 'red', 'per_page' => 0, 'show_count' => false], Setting::all('labels')); + + $settings->save('labels', ['color' => null]); + $settings->flush(); + $this->assertSame('red', Setting::get('labels.color')); + + $settings->save('labels', ['color' => 'blue']); + $settings->flush(); + $this->assertSame('blue', Setting::get('labels.color')); + } + public function test_a_superadmin_sets_up_a_module(): void { $this->install(); @@ -150,6 +178,10 @@ public function test_settings_need_their_permission(): void ->where('modules.0.name', 'acme/atrium-labels') ->where('modules.0.settings', true)); $this->assertContains('admin.modules.index', array_column($this->app->make(Menu::class)->items($setter), 'route')); + $this->assertSame( + ['label' => __('atrium::menu.modules'), 'route' => 'admin.modules.index', 'icon' => 'settings'], + collect($this->app->make(Menu::class)->items($setter))->firstWhere('route', 'admin.modules.index'), + ); } #[DefineEnvironment('installLabels')] diff --git a/packages/admin/tests/Feature/ModulesScreenTest.php b/packages/admin/tests/Feature/ModulesScreenTest.php index 2cbd1ea0..80e8a9aa 100644 --- a/packages/admin/tests/Feature/ModulesScreenTest.php +++ b/packages/admin/tests/Feature/ModulesScreenTest.php @@ -17,6 +17,7 @@ use Atrium\Admin\Modules\Module; use Atrium\Admin\Modules\Modules; use Atrium\Admin\Resources\ResourceRegistry; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Modules\Label; use Atrium\Admin\Tests\TestCase; use Illuminate\Contracts\Console\Kernel as ConsoleKernel; @@ -37,6 +38,8 @@ */ final class ModulesScreenTest extends TestCase { + use PinsExtensionSurface; + private string $root; protected function defineEnvironment($app): void @@ -363,12 +366,13 @@ public function test_the_catalogue_follows_the_pages_and_cleans_up_what_packagis ['name' => 'someone/atrium-gone', 'downloads' => 100, 'abandoned' => 'someone/atrium-new'], ['name' => 'Someone/Atrium-Upper', 'description' => 'Upper', 'url' => 'https://example.com/upper', 'downloads' => '12'], ['name' => 'someone/atrium-bare'], + ['name' => 'someone/atrium-numeric', 'url' => 7], ], 'next' => 'https://packagist.org/search.json?type=atrium-module&page=2']), 'https://packagist.org/search.json?type=atrium-module&page=2' => Http::response(['results' => [ ['name' => 'someone/atrium-second', 'description' => 42, 'downloads' => 1], ], 'next' => '']), 'https://packagist.org/search.json?tags=atrium-module&per_page=100' => Http::response(['results' => [ - ['name' => 'someone/atrium-upper', 'description' => 'Upper', 'url' => 'https://example.com/upper', 'downloads' => 12], + ['name' => 'someone/atrium-upper', 'description' => 'Upper', 'url' => 'https://example.com/upper', 'downloads' => '12'], ]]), default => Http::response('', 404), }; @@ -378,10 +382,26 @@ public function test_the_catalogue_follows_the_pages_and_cleans_up_what_packagis ['name' => 'someone/atrium-upper', 'description' => 'Upper', 'url' => 'https://example.com/upper', 'downloads' => 12], ['name' => 'someone/atrium-second', 'description' => '42', 'url' => 'https://packagist.org/packages/someone/atrium-second', 'downloads' => 1], ['name' => 'someone/atrium-bare', 'description' => '', 'url' => 'https://packagist.org/packages/someone/atrium-bare', 'downloads' => 0], + ['name' => 'someone/atrium-numeric', 'description' => '', 'url' => '7', 'downloads' => 0], ], $this->app->make(Catalogue::class)->packages()); Http::assertSentCount(3); } + public function test_packagist_is_given_five_seconds_to_answer(): void + { + Cache::forget('atrium.modules.catalogue'); + $timeouts = []; + Http::fake(function (Request $request, array $options) use (&$timeouts) { + $timeouts[] = $options['timeout']; + + return Http::response(['results' => []]); + }); + + $this->app->make(Catalogue::class)->packages(); + + $this->assertSame([5, 5], $timeouts); + } + public function test_the_catalogue_asks_for_five_pages_at_most(): void { Cache::forget('atrium.modules.catalogue'); diff --git a/packages/admin/tests/Feature/PageTimingTest.php b/packages/admin/tests/Feature/PageTimingTest.php index ead8f47a..3bca0db0 100644 --- a/packages/admin/tests/Feature/PageTimingTest.php +++ b/packages/admin/tests/Feature/PageTimingTest.php @@ -116,6 +116,15 @@ public function test_a_long_address_is_cut_to_the_column(): void $this->assertSame('/'.str_repeat('a', 254), PageTiming::query()->value('path')); } + public function test_a_long_address_is_cut_by_characters_not_bytes(): void + { + // A server may hand over the address as raw UTF-8 bytes. + $request = new Request(server: ['REQUEST_URI' => '/'.str_repeat('я', 300), 'REQUEST_METHOD' => 'GET', 'REQUEST_TIME_FLOAT' => microtime(true)]); + (new RecordPageTiming)->terminate($request, new Response('

News

', 200, ['Content-Type' => 'text/html'])); + + $this->assertSame('/'.str_repeat('я', 254), PageTiming::query()->value('path')); + } + public function test_a_failed_write_goes_unnoticed(): void { $default = config('database.default'); @@ -140,13 +149,37 @@ public function test_handle_passes_the_response_through_untouched(): void $this->assertSame($response, (new RecordPageTiming)->handle(Request::create('/news'), fn () => $response)); } - public function test_the_duration_is_counted_from_the_start_of_the_request(): void + /** + * @return array + */ + public static function durations(): array + { + return [ + 'a second and a half' => [1.5, 1500], + 'rounded down' => [1.2344, 1234], + 'rounded up' => [1.2346, 1235], + 'nothing' => [0.0, 0], + ]; + } + + #[DataProvider('durations')] + public function test_the_duration_is_counted_from_the_start_of_the_request_in_milliseconds(float $seconds, int $milliseconds): void { - $this->terminate(microtime(true) - 1.5); + $this->travelTo('2026-11-17 12:00:00'); - $duration = PageTiming::query()->value('duration_ms'); - $this->assertGreaterThanOrEqual(1500, $duration); - $this->assertLessThan(4500, $duration, 'A second and a half, not seconds or microseconds.'); + $this->terminate(now()->getTimestamp() - $seconds); + + $this->assertSame($milliseconds, PageTiming::query()->value('duration_ms')); + } + + public function test_a_request_without_a_start_time_counts_as_zero(): void + { + $request = Request::create('/news'); + $request->server->remove('REQUEST_TIME_FLOAT'); + + (new RecordPageTiming)->terminate($request, new Response('

News

', 200, ['Content-Type' => 'text/html'])); + + $this->assertSame(0, PageTiming::query()->value('duration_ms')); } public function test_a_hung_request_is_capped_at_ten_minutes(): void @@ -172,6 +205,28 @@ public function test_a_sample_rate_of_zero_measures_nothing(): void $this->assertSame(0, PageTiming::query()->count()); } + public function test_without_a_sample_rate_every_page_is_measured(): void + { + config(['atrium.dashboard.timings' => ['enabled' => true]]); + mt_srand($this->seedWhere(fn (): bool => mt_rand() / mt_getrandmax() > 0.001)); + + $this->terminate(microtime(true)); + + $this->assertSame(1, PageTiming::query()->count()); + } + + public function test_a_draw_equal_to_the_sample_rate_is_kept(): void + { + mt_srand(7); + $draw = mt_rand() / mt_getrandmax(); + config(['atrium.dashboard.timings.sample_rate' => $draw]); + + mt_srand(7); + $this->terminate(microtime(true)); + + $this->assertSame(1, PageTiming::query()->count()); + } + public function test_a_sample_rate_keeps_the_draws_at_or_under_it(): void { config(['atrium.dashboard.timings.sample_rate' => 0.5]); @@ -206,6 +261,22 @@ public function test_one_write_in_a_hundred_prunes_old_measurements(): void $this->assertSame(['/recent', '/news', '/news'], PageTiming::query()->orderBy('id')->pluck('path')->all()); } + public function test_without_a_setting_measurements_are_kept_for_thirty_days(): void + { + config(['atrium.dashboard.timings' => ['enabled' => true, 'sample_rate' => 1.0]]); + $this->travelTo(now()->subHours(30 * 24 + 12)); + PageTiming::query()->create(['path' => '/too-old', 'duration_ms' => 10]); + $this->travelBack(); + $this->travelTo(now()->subHours(30 * 24 - 12)); + PageTiming::query()->create(['path' => '/still-kept', 'duration_ms' => 10]); + $this->travelBack(); + + mt_srand($this->seedWhere(fn (): bool => mt_rand(1, 100) === 1)); + $this->terminate(microtime(true)); + + $this->assertSame(['/still-kept', '/news'], PageTiming::query()->orderBy('id')->pluck('path')->all()); + } + public function test_pruning_keeps_at_least_a_day(): void { config(['atrium.dashboard.timings.keep_days' => 0]); diff --git a/packages/admin/tests/Feature/PermissionsTest.php b/packages/admin/tests/Feature/PermissionsTest.php index f43061c5..4f82a617 100644 --- a/packages/admin/tests/Feature/PermissionsTest.php +++ b/packages/admin/tests/Feature/PermissionsTest.php @@ -12,6 +12,7 @@ use Atrium\Admin\Auth\Permissions; use Atrium\Admin\Models\AdminRole; use Atrium\Admin\Models\AdminUser; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; use Illuminate\Support\Arr; @@ -25,6 +26,8 @@ final class PermissionsTest extends TestCase { + use PinsExtensionSurface; + protected function defineDatabaseMigrations(): void { parent::defineDatabaseMigrations(); @@ -129,6 +132,39 @@ public function test_roles_are_managed_by_superadmins_only(): void $this->assertFalse(AdminRole::query()->where('name', 'Mine')->exists()); } + public function test_a_role_holding_the_routers_own_markers_gets_nothing_from_them(): void + { + $permissions = app(Permissions::class); + $user = $this->editor(['*superadmin', '*write', '*settings']); + + $this->assertFalse($permissions->allowsRoute($user, 'admin.roles.index')); + $this->assertFalse($permissions->allowsRoute($user, 'admin.upload')); + $this->assertFalse($permissions->canWriteAnything($user)); + } + + /** + * @return array + */ + public static function writeEndings(): array + { + return [ + 'create' => ['posts.create', true], + 'update' => ['posts.update', true], + 'settings' => ['labels.settings', true], + 'view' => ['posts.view', false], + 'delete' => ['posts.delete', false], + 'create without a dot' => ['postscreate', false], + 'update without a dot' => ['postsupdate', false], + 'settings without a dot' => ['labelssettings', false], + ]; + } + + #[DataProvider('writeEndings')] + public function test_writing_anything_needs_a_permission_to_create_update_or_set_up_something(string $permission, bool $can): void + { + $this->assertSame($can, app(Permissions::class)->canWriteAnything($this->editor([$permission]))); + } + public function test_a_module_keeps_its_screens_for_superadmins(): void { // Empty and non-string prefixes are skipped: '' would close every screen. @@ -495,4 +531,59 @@ private function menuRoutes(TestResponse $response): array $menu, )))); } + + public function test_only_the_exact_admin_route_names_of_a_module_need_its_permission(): void + { + $nobody = $this->editor([]); + $permissions = app(Permissions::class); + + // Another route that merely ends in the name of a module route, or starts with it. + $this->assertTrue($permissions->allowsRoute($nobody, 'admin.nested.admin.posts.index')); + $this->assertTrue($permissions->allowsRoute($nobody, 'admin.posts.index.extra')); + $this->assertTrue($permissions->allowsRoute($nobody, 'admin.posts.index1')); + $this->assertFalse($permissions->allowsRoute($nobody, 'admin.posts.index')); + } + + public function test_the_settings_of_any_module_open_the_modules_screen_to_a_role_with_exactly_that_permission(): void + { + $permissions = app(Permissions::class); + + $this->assertTrue($permissions->canSetUpAnything($this->editor(['labels.settings']))); + $this->assertTrue($permissions->canSetUpAnything($this->admin())); + $this->assertFalse($permissions->canSetUpAnything($this->editor(['labelsettings', 'posts.view'], 'other@example.com'))); + $this->assertFalse($permissions->canSetUpAnything($this->editor([], 'none@example.com'))); + $this->assertTrue($permissions->canSetUp($this->editor(['labels.settings'], 'third@example.com'), 'labels')); + } + + public function test_a_token_may_read_what_the_owner_may_view_and_write_what_the_owner_may_change(): void + { + $permissions = app(Permissions::class); + + $this->assertSame( + ['posts' => ['read' => true, 'write' => false]], + Arr::only($permissions->tokenModes($this->editor(['posts.view'])), ['posts']), + ); + $this->assertSame( + ['posts' => ['read' => true, 'write' => true]], + Arr::only($permissions->tokenModes($this->editor(['posts.view', 'posts.delete'], 'b@example.com')), ['posts']), + ); + $this->assertArrayNotHasKey('posts', $permissions->tokenModes($this->editor(['posts.update'], 'c@example.com'))); + } + + public function test_the_sections_of_the_role_form_are_in_alphabetical_order_and_end_with_the_api_tokens(): void + { + $sections = app(Permissions::class)->sections(); + $labels = array_column($sections, 'label'); + $own = array_slice($labels, 0, -1); + $sorted = $own; + usort($sorted, strnatcasecmp(...)); + + $this->assertSame($sorted, $own); + $this->assertNotSame('Posts', $own[0]); + $this->assertSame( + ['key' => 'api-tokens', 'label' => __('atrium::menu.api_tokens'), 'actions' => ['use']], + end($sections), + ); + $this->assertSame(array_keys($sections), range(0, count($sections) - 1)); + } } diff --git a/packages/admin/tests/Feature/ProfileTest.php b/packages/admin/tests/Feature/ProfileTest.php index 6bc01f06..4a1d259f 100644 --- a/packages/admin/tests/Feature/ProfileTest.php +++ b/packages/admin/tests/Feature/ProfileTest.php @@ -10,6 +10,7 @@ namespace Atrium\Admin\Tests\Feature; use Atrium\Admin\Models\AdminUser; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\TestCase; use Illuminate\Support\Facades\Hash; use Inertia\Testing\AssertableInertia; @@ -20,6 +21,8 @@ */ final class ProfileTest extends TestCase { + use PinsExtensionSurface; + public function test_the_profile_shows_the_administrator_without_secrets(): void { $admin = $this->admin(); diff --git a/packages/admin/tests/Feature/RecordActionsTest.php b/packages/admin/tests/Feature/RecordActionsTest.php index 2ab49a7c..0c61225b 100644 --- a/packages/admin/tests/Feature/RecordActionsTest.php +++ b/packages/admin/tests/Feature/RecordActionsTest.php @@ -12,8 +12,10 @@ use Atrium\Admin\Actions\CreateFromRecord; use Atrium\Admin\Models\AdminRole; use Atrium\Admin\Models\AdminUser; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Chapter; use Atrium\Admin\Tests\Fixtures\Ledger; +use Atrium\Admin\Tests\Fixtures\PanelAccount; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; use Illuminate\Support\Arr; @@ -26,6 +28,8 @@ */ final class RecordActionsTest extends TestCase { + use PinsExtensionSurface; + protected function defineEnvironment($app): void { parent::defineEnvironment($app); @@ -131,6 +135,18 @@ public function test_a_read_only_module_is_listed_and_deleted_but_not_created_or $this->assertSame(0, Ledger::query()->count()); } + public function test_an_account_that_is_not_an_administrator_model_gets_every_button_of_a_writable_module(): void + { + $this->admin(); + config(['auth.providers.admin_users.model' => PanelAccount::class]); + $this->actingAs(PanelAccount::query()->sole(), 'admin'); + + $this->get('/admin/posts')->assertOk()->assertInertia(fn (AssertableInertia $p) => $p + ->where('can', ['view' => true, 'create' => true, 'update' => true, 'delete' => true])); + $this->get('/admin/ledgers')->assertOk()->assertInertia(fn (AssertableInertia $p) => $p + ->where('can', ['view' => true, 'create' => false, 'update' => false, 'delete' => true])); + } + private function default(TestResponse $response, string $field, string $where = 'fieldsByTab'): mixed { $props = $response->assertOk()->viewData('page')['props']; diff --git a/packages/admin/tests/Feature/RoleControllerExactnessTest.php b/packages/admin/tests/Feature/RoleControllerExactnessTest.php new file mode 100644 index 00000000..38c2aeff --- /dev/null +++ b/packages/admin/tests/Feature/RoleControllerExactnessTest.php @@ -0,0 +1,80 @@ +actingAs($this->admin(), 'admin'); + $role = AdminRole::query()->create(['name' => 'Writer', 'permissions' => ['posts.view', 'posts.fly', 'posts.update']]); + $role->users()->attach([ + AdminUser::query()->create(['name' => 'Ann', 'email' => 'ann@example.com', 'password' => 'long-enough-1'])->id, + AdminUser::query()->create(['name' => 'Bob', 'email' => 'bob@example.com', 'password' => 'long-enough-1'])->id, + ]); + + $this->get('/admin/roles')->assertInertia(fn (AssertableInertia $page) => $page + ->where('roles', fn ($roles) => json_decode((string) json_encode($roles), true) === [ + ['id' => $role->id, 'name' => 'Writer', 'users_count' => 2, 'permissions_count' => 2], + ]) + ->where('title', 'Roles')); + } + + public function test_the_list_is_sorted_by_name(): void + { + $this->actingAs($this->admin(), 'admin'); + AdminRole::query()->create(['name' => 'Beta', 'permissions' => []]); + AdminRole::query()->create(['name' => 'Alpha', 'permissions' => []]); + + $this->get('/admin/roles')->assertInertia(fn (AssertableInertia $page) => $page + ->where('roles.0.name', 'Alpha') + ->where('roles.1.name', 'Beta')); + } + + public function test_a_role_needs_a_name_and_a_list_of_permissions_named_for_the_admin(): void + { + $this->actingAs($this->admin(), 'admin'); + + $this->from('/admin/roles/create')->post('/admin/roles', ['permissions' => []]) + ->assertSessionHasErrors(['name' => 'The Name field is required.']); + $this->from('/admin/roles/create')->post('/admin/roles', ['name' => 'Editor']) + ->assertSessionHasErrors(['permissions' => 'The permissions field must be present.']); + $this->assertSame(0, AdminRole::query()->count()); + } + + public function test_a_permission_is_a_string_that_exists(): void + { + $this->actingAs($this->admin(), 'admin'); + + $this->from('/admin/roles/create')->post('/admin/roles', ['name' => 'Editor', 'permissions' => [5]]) + ->assertSessionHasErrors(['permissions.0' => 'The permissions.0 field must be a string.']); + $this->assertSame(0, AdminRole::query()->count()); + } + + public function test_a_permission_named_twice_is_kept_once_and_the_list_stays_a_list(): void + { + $this->actingAs($this->admin(), 'admin'); + + $this->post('/admin/roles', ['name' => 'Editor', 'permissions' => ['posts.view', 'posts.view', 'posts.update']])->assertRedirect(); + + // Decoded: MySQL writes its JSON with spaces after the commas. + $this->assertSame(['posts.view', 'posts.update'], json_decode((string) DB::table('admin_roles')->value('permissions'), true)); + } +} diff --git a/packages/admin/tests/Feature/SeoFilesTest.php b/packages/admin/tests/Feature/SeoFilesTest.php index d09ac3be..d6825012 100644 --- a/packages/admin/tests/Feature/SeoFilesTest.php +++ b/packages/admin/tests/Feature/SeoFilesTest.php @@ -11,15 +11,22 @@ use Atrium\Admin\Models\Language; use Atrium\Admin\Models\Site; +use Atrium\Admin\Support\Sitemap; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\Fixtures\Story; use Atrium\Admin\Tests\TestCase; +use Illuminate\Support\Arr; +use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Route; use Orchestra\Testbench\Attributes\DefineEnvironment; use SimpleXMLElement; final class SeoFilesTest extends TestCase { + use PinsExtensionSurface; + protected function defineEnvironment($app): void { parent::defineEnvironment($app); @@ -130,6 +137,112 @@ public function test_a_large_sitemap_becomes_an_index_of_parts(): void $this->get('http://main.test/sitemap-0.xml')->assertNotFound(); } + public function test_the_sitemap_is_indented_xml_in_the_sitemaps_namespace_with_the_update_time_of_a_record(): void + { + $story = Story::query()->create(['name' => ['en' => 'Hello'], 'code' => ['en' => 'hello']]); + $story->forceFill(['updated_at' => '2026-03-04 05:06:07'])->saveQuietly(); + $updated = Story::query()->sole()->updated_at->format(DATE_ATOM); + + $xml = $this->get('http://main.test/sitemap.xml')->assertOk()->getContent(); + + $this->assertStringStartsWith(''."\n".''."\n", $xml); + // The configured path has no record behind it: no lastmod. + $this->assertStringContainsString(" \n http://main.test\n \n", $xml); + $this->assertStringContainsString(" \n http://main.test/stories/hello\n {$updated}\n \n", $xml); + $this->assertSame(1, substr_count($xml, '')); + } + + public function test_the_index_of_a_large_sitemap_is_indented_xml_in_the_sitemaps_namespace(): void + { + config(['atrium.sitemap.per_file' => 1]); + Story::query()->create(['name' => ['en' => 'a'], 'code' => ['en' => 'a']]); + + $this->assertSame( + ''."\n" + .''."\n" + ." \n http://main.test/sitemap-1.xml\n \n" + ." \n http://main.test/sitemap-2.xml\n \n" + ."\n", + $this->get('http://main.test/sitemap.xml')->assertOk()->getContent(), + ); + } + + public function test_a_file_takes_as_many_addresses_as_the_config_says_and_at_least_one(): void + { + foreach (['a', 'b', 'c'] as $code) { + Story::query()->create(['name' => ['en' => $code], 'code' => ['en' => $code]]); + } + $sitemap = fn (): Sitemap => app(Sitemap::class); + + // Four addresses, three to a file: two files, not one and not "1.33". + config(['atrium.sitemap.per_file' => 3]); + $this->assertSame(2, $sitemap()->parts()); + + config(['atrium.sitemap.per_file' => 4]); + $this->assertSame(1, $sitemap()->parts()); + + // One to a file is one to a file; nothing below one makes sense. + config(['atrium.sitemap.per_file' => 1]); + $this->assertSame(4, $sitemap()->parts()); + + config(['atrium.sitemap.per_file' => 0]); + $this->assertSame(4, $sitemap()->parts()); + + config(['atrium.sitemap.per_file' => -5]); + $this->assertSame(4, $sitemap()->parts()); + } + + public function test_a_sitemap_with_no_configured_path_lists_the_root_and_one_path_may_be_a_string(): void + { + $this->app['config']->set('atrium', Arr::except(config('atrium'), 'sitemap')); + $this->assertSame(['http://main.test'], $this->locs($this->get('http://main.test/sitemap.xml')->getContent())); + + config(['atrium.sitemap.paths' => '/about']); + app(Sitemap::class)->flush(); + $this->assertSame(['http://main.test/about'], $this->locs($this->get('http://main.test/sitemap.xml')->getContent())); + } + + public function test_the_built_sitemap_is_kept_under_the_site_the_host_and_the_version(): void + { + $sitemap = app(Sitemap::class); + $site = $this->main(); + + $sitemap->entries(); + $this->assertTrue(Cache::has('atrium.sitemap.'.$site->getKey().'.'.md5(url('/')).'.0')); + + $sitemap->flush(); + $version = (string) Cache::get('atrium.sitemap.version'); + $this->assertNotSame('', $version); + + $sitemap->entries(); + $this->assertTrue(Cache::has('atrium.sitemap.'.$site->getKey().'.'.md5(url('/')).'.'.$version)); + } + + public function test_the_records_of_a_module_are_read_in_chunks_of_five_hundred(): void + { + $queries = function (int $records): int { + Story::query()->delete(); + Story::query()->insert(array_map( + static fn (int $n): array => ['name' => json_encode(['en' => "s{$n}"]), 'code' => json_encode(['en' => "s{$n}"]), 'active' => true, 'created_at' => now(), 'updated_at' => now()], + range(1, $records), + )); + app(Sitemap::class)->flush(); + + DB::flushQueryLog(); + DB::enableQueryLog(); + app(Sitemap::class)->entries(); + $reads = count(array_filter(DB::getQueryLog(), static fn (array $query): bool => str_contains((string) $query['query'], 'from "stories"') || str_contains((string) $query['query'], 'from `stories`'))); + DB::disableQueryLog(); + + return $reads; + }; + + // A full chunk is followed by one more query to learn that it was the last. + $this->assertSame(1, $queries(499)); + $this->assertSame(2, $queries(500)); + $this->assertSame(2, $queries(501)); + } + public function test_robots_txt_off_production_turns_every_robot_away(): void { $this->main()->update(['robots_txt' => "User-agent: *\nDisallow: /search"]); diff --git a/packages/admin/tests/Feature/ServiceProviderTest.php b/packages/admin/tests/Feature/ServiceProviderTest.php index 3d0e979e..bf50bfbe 100644 --- a/packages/admin/tests/Feature/ServiceProviderTest.php +++ b/packages/admin/tests/Feature/ServiceProviderTest.php @@ -30,7 +30,11 @@ protected function defineEnvironment($app): void $app['config']->set('atrium.dashboard.timings.enabled', true); } - if ($this->name() === 'test_the_app_routes_file_adds_pages_inside_the_panel') { + if ($this->name() === 'test_the_app_routes_file_takes_every_middleware_the_app_configures') { + $app['config']->set('atrium.middleware', ['web', 'throttle:60,1']); + } + + if (in_array($this->name(), ['test_the_app_routes_file_adds_pages_inside_the_panel', 'test_the_app_routes_file_takes_every_middleware_the_app_configures'], true)) { file_put_contents($app->basePath('routes/atrium.php'), " 'Reports')->name('admin.reports');\n"); } } @@ -89,6 +93,14 @@ public function test_the_app_routes_file_adds_pages_inside_the_panel(): void $this->actingAs($this->admin(), 'admin')->get('/admin/reports')->assertOk()->assertSee('Reports'); } + public function test_the_app_routes_file_takes_every_middleware_the_app_configures(): void + { + $route = $this->app['router']->getRoutes()->getByName('admin.reports'); + + $this->assertNotNull($route); + $this->assertSame(['web', 'throttle:60,1', 'atrium.inertia', 'admin.auth', 'admin.can'], $route->middleware()); + } + public function test_the_console_publishes_every_part_of_the_panel(): void { $src = realpath(__DIR__.'/../../src'); diff --git a/packages/admin/tests/Feature/SharedPropsExactTest.php b/packages/admin/tests/Feature/SharedPropsExactTest.php new file mode 100644 index 00000000..764e655e --- /dev/null +++ b/packages/admin/tests/Feature/SharedPropsExactTest.php @@ -0,0 +1,87 @@ +admin(); + $response = $this->actingAs($admin, 'admin')->get('/admin/posts')->assertOk(); + + $this->assertSame( + ['user' => ['id' => $admin->id, 'name' => 'Admin', 'email' => 'admin@example.com', 'is_superadmin' => true]], + $response->inertiaProps('auth'), + ); + + $plain = AdminUser::query()->create(['name' => 'Plain', 'email' => 'plain@example.com', 'password' => 'secret-password', 'is_active' => true]); + $this->assertSame( + ['user' => ['id' => $plain->id, 'name' => 'Plain', 'email' => 'plain@example.com', 'is_superadmin' => false]], + $this->actingAs($plain, 'admin')->get('/admin/profile')->inertiaProps('auth'), + ); + } + + public function test_nobody_is_shared_on_the_sign_in_page(): void + { + $this->assertSame(['user' => null], $this->get('/admin/login')->inertiaProps('auth')); + } + + public function test_the_site_and_the_site_switch_carry_ids_and_names(): void + { + $main = Site::query()->where('code', 'main')->sole(); + $other = Site::query()->create(['code' => 'de', 'name' => 'Deutschland', 'domains' => ['example.de']]); + $response = $this->actingAs($this->admin(), 'admin')->get('/admin/posts'); + + $this->assertSame([['id' => $main->id, 'name' => $main->name], ['id' => $other->id, 'name' => 'Deutschland']], $response->inertiaProps('sites')); + $this->assertSame(['id' => $main->id, 'name' => $main->name, 'url' => $main->url()], $response->inertiaProps('currentSite')); + } + + public function test_every_kind_of_flash_message_is_shared(): void + { + $admin = $this->admin(); + $response = $this->actingAs($admin, 'admin') + ->withSession(['success' => 'Done', 'error' => 'Broken', 'warning' => 'Careful', 'info' => 'FYI']) + ->get('/admin/posts'); + + $this->assertSame(['success' => 'Done', 'error' => 'Broken', 'warning' => 'Careful', 'info' => 'FYI'], $response->inertiaProps('flash')); + + $this->flushSession(); + $this->assertSame(['success' => null, 'error' => null, 'warning' => null, 'info' => null], $this->actingAs($admin, 'admin')->get('/admin/posts')->inertiaProps('flash')); + } + + public function test_the_dictionary_is_sent_once_per_language_under_its_own_name(): void + { + $response = $this->actingAs($this->admin(), 'admin')->get('/admin/posts', ['X-Inertia' => 'true', 'X-Inertia-Version' => '']); + + $this->assertSame(['atrium.translations.en'], array_keys((array) $response->json('onceProps'))); + } + + public function test_the_asset_version_follows_the_manifest(): void + { + $file = public_path('vendor/atrium/manifest.json'); + @mkdir(dirname($file), 0777, true); + $existed = is_file($file); + $backup = $existed ? (string) file_get_contents($file) : null; + file_put_contents($file, '{"a":1}'); + + try { + $this->assertSame(md5('{"a":1}'), $this->get('/admin/login')->viewData('page')['version']); + } finally { + $backup === null ? unlink($file) : file_put_contents($file, $backup); + } + } +} diff --git a/packages/admin/tests/Feature/SiteCodesTest.php b/packages/admin/tests/Feature/SiteCodesTest.php index 8fa5b1bb..caf6d0c6 100644 --- a/packages/admin/tests/Feature/SiteCodesTest.php +++ b/packages/admin/tests/Feature/SiteCodesTest.php @@ -53,6 +53,22 @@ private function withCodes(array $codes = []): Site return $site; } + public function test_the_tidying_trims_the_ids_and_the_tokens_inside_a_tag_whatever_its_case(): void + { + $site = $this->withCodes([ + 'google_tag_id' => ' g-abc123xyz ', + 'google_verification' => '', + 'yandex_verification' => "", + ]); + + $this->assertSame('G-ABC123XYZ', $site->google_tag_id); + $this->assertSame('loud-token', $site->google_verification); + $this->assertSame('quiet-token', $site->yandex_verification); + + $site = $this->withCodes(['google_tag_id' => ' ']); + $this->assertNull($site->google_tag_id); + } + public function test_codes_are_tidied_on_save(): void { $site = $this->withCodes(['bing_verification' => ' ', 'head_code' => " \n"]); diff --git a/packages/admin/tests/Feature/SiteExactnessTest.php b/packages/admin/tests/Feature/SiteExactnessTest.php new file mode 100644 index 00000000..53095371 --- /dev/null +++ b/packages/admin/tests/Feature/SiteExactnessTest.php @@ -0,0 +1,420 @@ +set('app.url', 'http://main.test'); + } + + private function main(): Site + { + return Site::query()->where('code', 'main')->sole(); + } + + /** + * @param array $attributes + */ + private function site(string $code, array $attributes = []): Site + { + return Site::query()->create(['code' => $code, 'name' => ucfirst($code), ...$attributes]); + } + + /** + * @return array + */ + private function fields(): array + { + $fields = []; + + foreach (Site::getAdministrationFields() as $field) { + $fields[$field->getName().($field->shouldShowOnCreate() && ! $field->shouldShowOnEdit() ? ':create' : '')] = $field; + } + + return $fields; + } + + public function test_the_tabs_come_in_this_order_with_these_numbers(): void + { + $this->assertSame([ + ['name' => 'params', 'label' => __('atrium::sites.tabs.site'), 'icon' => null, 'order' => 0, 'visible' => true, 'badge' => null], + ['name' => 'codes', 'label' => __('atrium::sites.tabs.codes'), 'icon' => null, 'order' => 10, 'visible' => true, 'badge' => null], + ['name' => 'robots', 'label' => 'robots.txt', 'icon' => null, 'order' => 20, 'visible' => true, 'badge' => null], + ], array_map(fn ($tab) => $tab->toArray(), Site::getAdminTabs())); + } + + public function test_the_fields_come_in_this_order(): void + { + $this->assertSame([ + 'name', 'code:create', 'code', 'domains', 'folder', 'languages', 'default_language', 'active', 'is_default', 'sort', + 'google_tag_id', 'yandex_metrika_id', 'yandex_webvisor', 'counters_skip_admins', + 'google_verification', 'yandex_verification', 'bing_verification', + 'head_code', 'body_start_code', 'body_end_code', 'robots_txt', + ], array_keys($this->fields())); + } + + public function test_the_site_fields_hold_their_limits_and_defaults(): void + { + $fields = $this->fields(); + + $this->assertInstanceOf(TextField::class, $fields['name']); + $this->assertTrue($fields['name']->isRequired()); + $this->assertSame(255, $fields['name']->getMaxLength()); + $this->assertSame(255, $fields['folder']->getMaxLength()); + $this->assertSame('site2', $fields['folder']->toArray()['placeholder']); + + $this->assertTrue($fields['active']->getDefault()); + $this->assertFalse($fields['is_default']->getDefault()); + $this->assertSame(500, $fields['sort']->getDefault()); + + $rules = $fields['code:create']->getValidationRules(); + $this->assertContains('string', $rules); + $this->assertContains('max:32', $rules); + $this->assertContains('regex:/^'.Site::CODE_PATTERN.'$/', $rules); + } + + public function test_every_field_of_the_codes_tab_sits_on_it_and_the_rest_on_params(): void + { + foreach ($this->fields() as $name => $field) { + $expected = match (true) { + in_array($name, ['google_tag_id', 'yandex_metrika_id', 'yandex_webvisor', 'counters_skip_admins', 'google_verification', 'yandex_verification', 'bing_verification', 'head_code', 'body_start_code', 'body_end_code'], true) => 'codes', + $name === 'robots_txt' => 'robots', + default => 'params', + }; + + $this->assertSame($expected, $field->getTab(), $name); + } + } + + public function test_the_code_fields_have_their_defaults_rows_and_rules(): void + { + $fields = $this->fields(); + + $this->assertFalse($fields['yandex_webvisor']->getDefault()); + $this->assertTrue($fields['counters_skip_admins']->getDefault()); + + foreach (['head_code', 'body_start_code', 'body_end_code'] as $name) { + $this->assertInstanceOf(TextareaField::class, $fields[$name]); + $this->assertSame(6, $fields[$name]->toArray()['rows'], $name); + } + + foreach (['google_tag_id' => 32, 'yandex_metrika_id' => 20, 'google_verification' => 1000, 'yandex_verification' => 1000, 'bing_verification' => 1000] as $name => $max) { + $rules = $fields[$name]->getValidationRules(); + $this->assertContains('string', $rules, $name); + $this->assertContains('max:'.$max, $rules, $name); + } + } + + public function test_the_verification_hints_name_the_meta_tag(): void + { + foreach (['google_verification' => 'google-site-verification', 'yandex_verification' => 'yandex-verification', 'bing_verification' => 'msvalidate.01'] as $name => $meta) { + $this->assertSame(__('atrium::sites.hints.verification', ['name' => $meta]), $this->fields()[$name]->toArray()['hint']); + $this->assertStringContainsString($meta, $this->fields()[$name]->toArray()['hint']); + } + } + + public function test_the_robots_field_is_there_only_when_the_option_is_on(): void + { + $this->assertSame('robots_txt', array_key_last($this->fields())); + + config(['atrium.robots' => false]); + + $this->assertArrayNotHasKey('robots_txt', $this->fields()); + $this->assertSame('body_end_code', array_key_last($this->fields())); + } + + public function test_the_robots_hint_says_what_stops_the_text_from_being_served(): void + { + $file = public_path('robots.txt'); + $environment = $this->app['env']; + @unlink($file); + + try { + $this->app['env'] = 'production'; + $plain = $this->fields()['robots_txt']->toArray(); + $this->assertSame(__('atrium::sites.hints.robots_txt'), $plain['hint']); + $this->assertSame(12, $plain['rows']); + + $this->app['env'] = 'staging'; + $this->assertSame( + __('atrium::sites.hints.robots_txt').' '.__('atrium::sites.hints.robots_not_production', ['env' => 'staging']), + $this->fields()['robots_txt']->toArray()['hint'], + ); + + $this->app['env'] = 'production'; + file_put_contents($file, "User-agent: *\n"); + $this->assertSame( + __('atrium::sites.hints.robots_txt').' '.__('atrium::sites.hints.robots_file_exists'), + $this->fields()['robots_txt']->toArray()['hint'], + ); + } finally { + $this->app['env'] = $environment; + @unlink($file); + } + } + + /** + * Fill the three caches, change what they hold behind the model's back, + * and see what each of them answers after $change. + * + * @return array{sites:string,languages:string,sitemap:string} + */ + private function afterChange(callable $change): array + { + app(Sites::class)->all(); + app(ContentLanguages::class)->all(); + $before = Cache::get('atrium.sitemap.version'); + DB::table('admin_sites')->where('code', 'main')->update(['name' => 'Changed']); + DB::table('admin_languages')->where('code', 'en')->update(['name' => 'Changed']); + + $change(); + + return [ + 'sites' => (string) app(Sites::class)->all()->firstWhere('code', 'main')?->name, + 'languages' => (string) app(ContentLanguages::class)->all()->first()?->name, + 'sitemap' => $before === Cache::get('atrium.sitemap.version') ? 'stale' : 'fresh', + ]; + } + + public function test_saving_a_site_flushes_the_three_caches(): void + { + $this->assertSame( + ['sites' => 'Changed', 'languages' => 'Changed', 'sitemap' => 'fresh'], + $this->afterChange(fn () => $this->site('other')), + ); + } + + public function test_deleting_a_site_flushes_the_three_caches(): void + { + $site = $this->site('other'); + + $this->assertSame( + ['sites' => 'Changed', 'languages' => 'Changed', 'sitemap' => 'fresh'], + $this->afterChange(fn () => $site->delete()), + ); + } + + public function test_the_code_of_a_saved_site_cannot_be_changed(): void + { + $site = $this->site('other'); + $site->code = 'renamed'; + $site->save(); + + $this->assertSame('other', $site->fresh()->code); + $this->assertSame('other', $site->code); + } + + /** + * @return array + */ + public static function addresses(): array + { + return [ + 'https on 443' => ['https', 443, 'https://example.de'], + 'http on 80' => ['http', 80, 'http://example.de'], + 'https on 8443' => ['https', 8443, 'https://example.de:8443'], + 'http on 8080' => ['http', 8080, 'http://example.de:8080'], + 'http on 443' => ['http', 443, 'http://example.de:443'], + 'https on 80' => ['https', 80, 'https://example.de:80'], + 'no port at all' => ['http', null, 'http://example.de'], + ]; + } + + #[DataProvider('addresses')] + public function test_a_site_of_another_domain_is_opened_on_the_port_of_the_request(string $scheme, ?int $port, string $root): void + { + $site = $this->site('de', ['domains' => ['example.de']]); + + $server = ['SERVER_NAME' => 'panel.test', 'HTTPS' => $scheme === 'https' ? 'on' : 'off']; + + if ($port !== null) { + $server['SERVER_PORT'] = $port; + $server['HTTP_HOST'] = 'panel.test:'.$port; + } + + $this->app->instance('request', new Request([], [], [], [], [], $server)); + + $this->assertSame($root, $site->url()); + $this->assertSame($root.'/blog/post', $site->url('/blog/post/')); + } + + public function test_the_address_of_a_page_sits_inside_the_folder_of_the_site(): void + { + $this->app->instance('request', Request::create('http://main.test/')); + $site = $this->site('folder', ['folder' => 'f']); + + $this->assertSame('http://main.test/f', $site->url()); + $this->assertSame('http://main.test/f/blog', $site->url('/blog/')); + $this->assertSame('http://main.test/f/a/b', $site->url('a/b')); + $this->assertSame('http://main.test/blog', $this->main()->url('/blog/')); + $this->assertSame('http://main.test', $this->main()->url()); + } + + public function test_the_site_of_this_domain_uses_the_root_of_the_request(): void + { + $this->app->instance('request', Request::create('http://example.de:8080/')); + $site = $this->site('de', ['domains' => ['example.de']]); + + $this->assertSame('http://example.de:8080/x', $site->url('x')); + } + + public function test_robots_txt_is_trimmed_and_gets_the_sitemap_when_it_has_none(): void + { + $this->app['env'] = 'production'; + $site = $this->main(); + + $site->update(['robots_txt' => "\r\n User-agent: *\r\nDisallow: /x\r\n\r\n"]); + $this->assertSame("User-agent: *\nDisallow: /x\n\nSitemap: ".url('sitemap.xml')."\n", $site->robotsTxt()); + + // "sitemap:" in the middle of a line is not a Sitemap line. + $site->update(['robots_txt' => 'Disallow: /sitemap: x']); + $this->assertSame("Disallow: /sitemap: x\n\nSitemap: ".url('sitemap.xml')."\n", $site->robotsTxt()); + + $site->update(['robots_txt' => "User-agent: *\n SITEMAP: https://cdn.test/map.xml"]); + $this->assertSame("User-agent: *\n SITEMAP: https://cdn.test/map.xml\n", $site->robotsTxt()); + + // The sites in folders of this domain add their own sitemaps. + $site->update(['robots_txt' => 'Disallow: /sitemap: x']); + $this->assertSame("Disallow: /sitemap: x\n\nSitemap: ".url('sitemap.xml')."\nSitemap: ".url('f/sitemap.xml')."\n", $site->robotsTxt([new Site(['folder' => 'f'])])); + } + + public function test_robots_txt_that_was_never_saved_is_trimmed_too(): void + { + $environment = $this->app['env']; + $this->app['env'] = 'production'; + + try { + $this->assertSame("User-agent: *\nDisallow: /x\n\nSitemap: ".url('sitemap.xml')."\n", (new Site(['robots_txt' => "\r\n User-agent: *\r\nDisallow: /x\r\n\r\n"]))->robotsTxt()); + $this->assertSame("User-agent: *\nDisallow:\n\nSitemap: ".url('sitemap.xml')."\n", (new Site(['robots_txt' => " \r\n "]))->robotsTxt()); + } finally { + $this->app['env'] = $environment; + } + } + + public function test_a_host_is_matched_without_regard_to_case_and_trailing_dot(): void + { + $site = $this->site('de', ['domains' => ['example.de']]); + + $this->assertTrue($site->hasDomain('EXAMPLE.DE')); + $this->assertTrue($site->hasDomain('Example.de.')); + $this->assertFalse($site->hasDomain('example.com')); + } + + public function test_domains_are_cleaned_of_scheme_path_port_case_and_the_trailing_dot(): void + { + $site = $this->site('de', ['domains' => [' HTTPS://Example.DE:8080/path?x=1 ', 'example.de.', 'Other.test.', 'a.test/b', 'c.test?x', 'd.test#frag', '']]); + + $this->assertSame(['example.de', 'other.test', 'a.test', 'c.test', 'd.test'], $site->domains); + } + + public function test_a_folder_is_cleaned_of_scheme_host_query_and_surplus_slashes(): void + { + $this->assertSame('a/b', Site::normalizeFolder(' HTTP://Host.test//a///b/?x=1#frag ')); + $this->assertSame('a', Site::normalizeFolder('a#frag')); + $this->assertSame('a', Site::normalizeFolder('/a?x')); + $this->assertNull(Site::normalizeFolder('https://host.test')); + $this->assertNull(Site::normalizeFolder(null)); + $this->assertNull(Site::normalizeFolder(' / ')); + } + + public function test_the_panel_prefixes_are_reserved_whatever_their_slashes_and_case(): void + { + $site = $this->site('other'); + + foreach (['atrium.prefix' => ['/Panel/x/', 'panel'], 'atrium.api.prefix' => ['/Rest/v2/', 'rest'], 'atrium.mcp.path' => ['/Tools/', 'tools']] as $key => [$configured, $folder]) { + config([$key => $configured]); + + foreach ([$folder, strtoupper($folder).'/sub'] as $try) { + try { + $site->update(['folder' => $try]); + $this->fail("The folder [{$try}] was accepted."); + } catch (ValidationException $e) { + $this->assertSame([__('atrium::sites.errors.folder_reserved', ['folder' => strtolower(strtok($try, '/'))])], $e->errors()['folder'], $try); + } + } + } + + // And a folder that is nobody's prefix passes. + $site->update(['folder' => 'plain']); + $this->assertSame('plain', $site->fresh()->folder); + } + + public function test_the_message_for_a_bad_domain_names_it(): void + { + try { + $this->site('bad', ['domains' => ['bad domain']]); + $this->fail('A bad domain was accepted.'); + } catch (ValidationException $e) { + $this->assertSame(['domains' => [__('atrium::sites.errors.domain_invalid', ['domain' => 'bad domain'])]], $e->errors()); + } + } + + public function test_the_message_for_a_taken_domain_names_the_domain_and_the_site(): void + { + $this->site('de', ['domains' => ['example.de'], 'name' => 'Deutschland']); + + try { + $this->site('again', ['domains' => ['other.test', 'example.de']]); + $this->fail('A taken domain was accepted.'); + } catch (ValidationException $e) { + $this->assertSame(['domains' => [__('atrium::sites.errors.domain_taken', ['domain' => 'example.de', 'site' => 'Deutschland'])]], $e->errors()); + } + } + + public function test_the_message_for_a_taken_folder_gives_the_address_and_the_site(): void + { + $this->site('a', ['domains' => ['example.de'], 'folder' => 'f', 'name' => 'Alpha']); + $this->site('b', ['folder' => 'g', 'name' => 'Beta']); + + try { + $this->site('again', ['domains' => ['example.de'], 'folder' => 'f']); + $this->fail('A taken address was accepted.'); + } catch (ValidationException $e) { + $this->assertSame(['folder' => [__('atrium::sites.errors.folder_taken', ['address' => 'example.de/f/', 'site' => 'Alpha'])]], $e->errors()); + } + + // Two sites without domains share every domain, so a folder is theirs alone. + try { + $this->site('third', ['folder' => 'g']); + $this->fail('A taken folder was accepted.'); + } catch (ValidationException $e) { + $this->assertSame(['folder' => [__('atrium::sites.errors.folder_taken', ['address' => '/g/', 'site' => 'Beta'])]], $e->errors()); + } + } + + public function test_a_row_with_no_domains_at_all_still_takes_its_folder(): void + { + DB::table('admin_sites')->insert(['code' => 'raw', 'name' => 'Raw', 'folder' => 'r', 'domains' => null, 'active' => true, 'is_default' => false, 'sort' => 500, 'created_at' => now(), 'updated_at' => now()]); + + $this->expectException(ValidationException::class); + $this->site('again', ['folder' => 'r']); + } +} diff --git a/packages/admin/tests/Feature/SitesTest.php b/packages/admin/tests/Feature/SitesTest.php index 97398215..ae5da35f 100644 --- a/packages/admin/tests/Feature/SitesTest.php +++ b/packages/admin/tests/Feature/SitesTest.php @@ -229,6 +229,34 @@ public function test_switching_the_site_from_a_form_goes_to_the_list(): void ->assertRedirect(route('admin.notes.index')); } + public function test_nobody_signed_in_may_not_switch_the_site(): void + { + $this->withoutMiddleware(); + + $this->post('/admin/site', ['site_id' => $this->main()->id])->assertForbidden(); + } + + public function test_switching_the_site_names_the_site(): void + { + $this->actingAs($this->admin(), 'admin') + ->from('/admin/notes') + ->post('/admin/site', []) + ->assertSessionHasErrors(['site_id' => 'The site id field is required.']); + } + + public function test_switching_the_site_goes_back_to_a_page_that_is_not_a_form_of_a_module(): void + { + $second = $this->addSecondSite(); + Route::get('/elsewhere/{note}', static fn (): string => 'x')->name('other.admin.notes.edit'); + Route::get('/elsewhere/copy/{note}', static fn (): string => 'x')->name('admin.notes.edit.copy'); + + $this->actingAs($this->admin(), 'admin'); + + foreach (['/nowhere-at-all', '/elsewhere/1', '/elsewhere/copy/1'] as $page) { + $this->from($page)->post('/admin/site', ['site_id' => $second->id])->assertRedirect(url($page)); + } + } + public function test_a_code_is_unique_within_its_site(): void { $second = $this->addSecondSite(); diff --git a/packages/admin/tests/Feature/SlugModelsTest.php b/packages/admin/tests/Feature/SlugModelsTest.php index 59abe6c8..cfaefccd 100644 --- a/packages/admin/tests/Feature/SlugModelsTest.php +++ b/packages/admin/tests/Feature/SlugModelsTest.php @@ -11,6 +11,7 @@ use Atrium\Admin\Models\Slug; use Atrium\Admin\Models\SlugHistory; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Handbook; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; @@ -18,6 +19,8 @@ final class SlugModelsTest extends TestCase { + use PinsExtensionSurface; + public function test_a_slug_is_found_by_its_code_and_type(): void { $article = Handbook::query()->create(['name' => 'Chair', 'code' => 'chair']); diff --git a/packages/admin/tests/Feature/SlugRedirectTest.php b/packages/admin/tests/Feature/SlugRedirectTest.php index 08e97a4d..b340dabe 100644 --- a/packages/admin/tests/Feature/SlugRedirectTest.php +++ b/packages/admin/tests/Feature/SlugRedirectTest.php @@ -127,6 +127,23 @@ public function test_a_hidden_page_does_not_redirect_to_itself(): void $this->get('/draft')->assertNotFound(); } + public function test_the_root_is_never_redirected_whatever_the_history_says(): void + { + $guide = $this->guide('setup', 'guides'); + $this->history($guide, 'root', '/'); + $this->history($guide, '', ''); + + $this->get('/')->assertNotFound(); + } + + public function test_a_page_that_is_served_stays_served_although_its_address_is_in_the_history(): void + { + $this->guide('setup', 'guides'); + $this->history($this->guide('fresh', 'news'), 'setup', 'guides/setup'); + + $this->get('/guides/setup')->assertOk()->assertSeeText('Guide setup'); + } + public function test_only_a_404_is_redirected(): void { $this->history($this->guide('setup', 'guides'), 'install', 'manuals/install'); diff --git a/packages/admin/tests/Feature/SlugRegenerateTest.php b/packages/admin/tests/Feature/SlugRegenerateTest.php index a2633df4..17cc4488 100644 --- a/packages/admin/tests/Feature/SlugRegenerateTest.php +++ b/packages/admin/tests/Feature/SlugRegenerateTest.php @@ -17,11 +17,13 @@ use Atrium\Admin\Models\Slug; use Atrium\Admin\Models\SlugHistory; use Atrium\Admin\Services\SlugService; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Leaflet; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; use Illuminate\Database\Eloquent\Model; use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Facades\Artisan; /** * atrium:slug:regenerate: cached addresses built again, for one model or @@ -29,6 +31,8 @@ */ final class SlugRegenerateTest extends TestCase { + use PinsExtensionSurface; + private string $appPath; protected function setUp(): void @@ -155,13 +159,14 @@ public function test_all_finds_the_models_with_addresses_in_app_models(): void $this->model('RegenFlyer', 'namespace App\\Models; class RegenFlyer extends \\Atrium\\Admin\\Tests\\Fixtures\\Leaflet {}'); $this->model('Blog/RegenBooklet', 'namespace App\\Models\\Blog; class RegenBooklet extends \\Atrium\\Admin\\Tests\\Fixtures\\Leaflet {}'); $this->model('RegenPlain', 'namespace App\\Models; class RegenPlain extends \\Illuminate\\Database\\Eloquent\\Model {}'); - file_put_contents($this->appPath.'/Models/helpers.php', "appPath.'/Models/Aardvark.php', "create(['name' => 'Flyer', 'code' => 'flyer']); RegenBooklet::query()->create(['name' => 'Booklet', 'code' => 'booklet']); Slug::query()->delete(); $this->artisan('atrium:slug:regenerate', ['--all' => true]) + ->expectsOutput('Scanning for models with HasSlug...') ->expectsOutput('Found 2 model(s)') ->expectsOutput('Processing App\\Models\\Blog\\RegenBooklet...') ->expectsOutput(' - Regenerated 2 slugs') @@ -174,12 +179,23 @@ public function test_all_finds_the_models_with_addresses_in_app_models(): void $this->assertSame(4, Slug::query()->count()); } + public function test_all_leaves_a_blank_line_before_the_total(): void + { + $this->model('RegenFlyer', 'namespace App\\Models; class RegenFlyer extends \\Atrium\\Admin\\Tests\\Fixtures\\Leaflet {}'); + RegenFlyer::query()->create(['name' => 'Flyer', 'code' => 'flyer']); + + Artisan::call('atrium:slug:regenerate', ['--all' => true]); + + $this->assertStringContainsString("slugs\n\nTotal: regenerated", Artisan::output()); + } + public function test_all_without_app_models_finds_nothing(): void { (new Filesystem)->deleteDirectory($this->appPath.'/Models'); $this->artisan('atrium:slug:regenerate', ['--all' => true]) ->expectsOutput('No models found with HasSlug trait') + ->doesntExpectOutputToContain('Found 0') ->assertSuccessful(); } diff --git a/packages/admin/tests/Feature/SlugServiceTest.php b/packages/admin/tests/Feature/SlugServiceTest.php index 84c477b4..6bb77296 100644 --- a/packages/admin/tests/Feature/SlugServiceTest.php +++ b/packages/admin/tests/Feature/SlugServiceTest.php @@ -13,9 +13,11 @@ use Atrium\Admin\Models\SlugHistory; use Atrium\Admin\Services\SlugService; use Atrium\Admin\Tests\Fixtures\Handbook; +use Atrium\Admin\Tests\Fixtures\Leaflet; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\DB; use PHPUnit\Framework\Attributes\DataProvider; final class SlugServiceTest extends TestCase @@ -71,6 +73,71 @@ public function test_a_unique_slug_counts_up_past_taken_codes(): void $this->assertSame('chair-1', $this->service()->generateUnique('Chair', Handbook::class, $taken->id)); } + public function test_a_unique_slug_of_a_record_that_is_not_saved_yet_is_not_blocked_by_an_id_of_zero(): void + { + Handbook::query()->insert(['id' => 0, 'name' => 'Zero', 'code' => 'zero']); + + $this->assertSame('zero-1', (new Handbook(['name' => 'Zero']))->generateSlug()); + $this->assertSame('zero-1', $this->service()->generateUnique('Zero', Handbook::class)); + } + + public function test_a_unique_slug_starts_without_a_counter_and_counts_from_one(): void + { + $this->assertSame('free', $this->service()->ensureUnique('free', Handbook::class)); + + Handbook::query()->create(['name' => 'Free', 'code' => 'free']); + Handbook::query()->create(['name' => 'Free', 'code' => 'free-1']); + Handbook::query()->create(['name' => 'Free', 'code' => 'free--1']); + Handbook::query()->create(['name' => 'Free', 'code' => 'free-0']); + + $this->assertSame('free-2', $this->service()->ensureUnique('free', Handbook::class)); + } + + public function test_syncing_a_slug_leaves_the_slug_of_another_model_with_the_same_id_alone(): void + { + $handbook = Handbook::query()->create(['name' => 'Handbook', 'code' => 'handbook']); + $leaflet = Leaflet::query()->create(['name' => 'Leaflet', 'code' => 'leaflet']); + $this->assertSame($handbook->id, $leaflet->id); + + $handbook->code = 'manual'; + $this->service()->syncSlug($handbook); + + $this->assertSame( + ['leaflet', 'manual'], + Slug::query()->orderBy('slug')->pluck('slug')->all(), + ); + } + + /** + * @return array + */ + public static function chunks(): array + { + return [ + 'one short of a page' => [99, 1], + 'exactly a page, then an empty one' => [100, 2], + ]; + } + + #[DataProvider('chunks')] + public function test_regenerating_reads_the_records_a_hundred_at_a_time(int $records, int $reads): void + { + Leaflet::query()->insert(array_map( + fn (int $number): array => ['name' => "Leaflet {$number}", 'code' => "leaflet-{$number}"], + range(1, $records), + )); + + $selects = 0; + DB::listen(function ($query) use (&$selects): void { + if (str_starts_with($query->sql, 'select') && preg_match('/["`]leaflets["`]/', $query->sql) === 1) { + $selects++; + } + }); + + $this->assertSame($records, $this->service()->regenerateAll(Leaflet::class)); + $this->assertSame($reads, $selects); + } + public function test_find_by_slug_reads_the_database_then_the_cache(): void { $article = Handbook::query()->create(['name' => 'Chair', 'code' => 'chair']); diff --git a/packages/admin/tests/Feature/SoftRelationsTest.php b/packages/admin/tests/Feature/SoftRelationsTest.php index 6d6d30be..4a34d1b6 100644 --- a/packages/admin/tests/Feature/SoftRelationsTest.php +++ b/packages/admin/tests/Feature/SoftRelationsTest.php @@ -15,6 +15,7 @@ use Atrium\Admin\Modules\Modules; use Atrium\Admin\Modules\Soft; use Atrium\Admin\Resources\ResourceRegistry; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Gadget; use Atrium\Admin\Tests\Fixtures\Modules\Label; use Atrium\Admin\Tests\Fixtures\Post; @@ -33,6 +34,8 @@ */ final class SoftRelationsTest extends TestCase { + use PinsExtensionSurface; + protected function defineEnvironment($app): void { parent::defineEnvironment($app); @@ -153,6 +156,57 @@ public function test_a_record_attached_to_a_missing_module_reads_as_null(): void $this->assertSame([null, $post->id, null], $remarks->map(static fn (Remark $remark) => $remark->subject?->getKey())->all()); } + public function test_a_relation_is_named_after_the_method_that_declares_it_unless_it_is_given_a_name(): void + { + [, $gadget] = $this->gadget(); + $remark = Remark::query()->make(); + + foreach ([true, false] as $installed) { + if (! $installed) { + $this->withoutLabels(); + } + + $this->assertSame('label', $gadget->label()->getRelationName(), 'installed: '.json_encode($installed)); + $this->assertSame('tags', $gadget->tags()->getRelationName()); + $this->assertSame('chosen', $gadget->named()->getRelationName()); + $this->assertSame('chosen', $gadget->namedTags()->getRelationName()); + $this->assertSame('subject', $remark->subject()->getRelationName()); + $this->assertSame('subject', $remark->other()->getRelationName()); + } + } + + public function test_the_link_keys_come_from_the_names_unless_they_are_given(): void + { + [, $gadget] = $this->gadget(); + + foreach ([true, false] as $installed) { + if (! $installed) { + $this->withoutLabels(); + } + + $why = 'installed: '.json_encode($installed); + $this->assertSame('label_id', $gadget->label()->getForeignKeyName(), $why); + $this->assertSame('label2_id', $gadget->label2()->getForeignKeyName(), $why); + $this->assertSame('label_id', $gadget->named()->getForeignKeyName(), $why); + $this->assertSame('shade_id', $gadget->namedTags()->getRelatedPivotKeyName(), $why); + $this->assertSame(['gadget_id', 'label_id'], [$gadget->tags()->getForeignPivotKeyName(), $gadget->tags()->getRelatedPivotKeyName()], $why); + $this->assertSame(['gadget_id', 'label_id'], [$gadget->tags2()->getForeignPivotKeyName(), $gadget->tags2()->getRelatedPivotKeyName()], $why); + } + } + + public function test_a_record_of_a_missing_module_is_kept_out_by_the_query_itself(): void + { + $onGone = Remark::query()->create(['text' => 'Gone', 'subject_type' => 'Acme\\Gone\\Thing', 'subject_id' => 1]); + [$label] = $this->gadget(); + $onLabel = Remark::query()->create(['text' => 'Nice', 'subject_type' => Label::class, 'subject_id' => $label->id]); + + $this->assertStringContainsString('1 = 0', $onGone->subject()->toSql()); + $this->assertStringNotContainsString('1 = 0', $onLabel->subject()->toSql()); + + $this->withoutLabels(); + $this->assertStringContainsString('1 = 0', $onLabel->fresh()->subject()->toSql()); + } + public function test_the_list_shows_an_attribute_of_the_linked_record(): void { $this->gadget(); diff --git a/packages/admin/tests/Feature/SupportEdgesTest.php b/packages/admin/tests/Feature/SupportEdgesTest.php index fbe69e48..d139966c 100644 --- a/packages/admin/tests/Feature/SupportEdgesTest.php +++ b/packages/admin/tests/Feature/SupportEdgesTest.php @@ -22,6 +22,7 @@ use Atrium\Admin\Support\Menu; use Atrium\Admin\Support\Sitemap; use Atrium\Admin\Support\Sites; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Note; use Atrium\Admin\Tests\TestCase; use DateTimeInterface; @@ -35,6 +36,8 @@ final class SupportEdgesTest extends TestCase { + use PinsExtensionSurface; + private function editor(): AdminUser { return AdminUser::query()->create(['name' => 'Editor', 'email' => 'editor@example.com', 'password' => 'secret-password', 'is_active' => true]); @@ -182,6 +185,15 @@ public function test_before_the_migrations_there_is_one_site_named_after_the_app $this->assertTrue((new Sites)->default()->exists); } + public function test_the_stand_in_site_is_named_after_the_app_even_when_the_name_is_not_text(): void + { + config(['app.name' => 123]); + + $this->withoutTables(function (): void { + $this->assertSame('123', (new Sites)->default()->name); + }); + } + public function test_before_the_migrations_the_content_language_is_the_app_locale(): void { config(['app.locale' => 'pt_BR']); diff --git a/packages/admin/tests/Feature/SupportExactnessTest.php b/packages/admin/tests/Feature/SupportExactnessTest.php new file mode 100644 index 00000000..002025b5 --- /dev/null +++ b/packages/admin/tests/Feature/SupportExactnessTest.php @@ -0,0 +1,303 @@ +withVite(); + $hot = public_path('vendor/atrium/hot'); + File::ensureDirectoryExists(dirname($hot)); + File::put($hot, 'http://localhost:5199'); + + try { + $tags = (string) Assets::tags(); + } finally { + File::delete($hot); + } + + $this->assertStringContainsString('src="http://localhost:5199/@vite/client"', $tags); + $this->assertStringContainsString('src="http://localhost:5199/resources/js/app.js"', $tags); + } + + // ---- ContentLanguages ---------------------------------------------------------------------- + + public function test_the_stand_in_language_of_a_fresh_install_is_active(): void + { + config(['app.locale' => 'de']); + Language::query()->delete(); + + $language = (new ContentLanguages)->all()->sole(); + + $this->assertTrue($language->active); + $this->assertTrue($language->is_default); + $this->assertSame('de', $language->code); + } + + public function test_a_site_default_language_goes_first_and_the_others_keep_their_order(): void + { + Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200]); + Language::query()->create(['code' => 'fr', 'name' => 'Français', 'sort' => 300]); + Language::query()->create(['code' => 'pl', 'name' => 'Polski', 'sort' => 400]); + Site::query()->where('code', 'main')->update(['default_language' => 'fr']); + app(Sites::class)->flush(); + + $this->assertSame(['fr', 'en', 'de', 'pl'], app(ContentLanguages::class)->codes()); + $this->assertSame('fr', app(ContentLanguages::class)->default()); + } + + public function test_with_no_default_language_named_the_panel_default_goes_first(): void + { + Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200]); + Language::query()->create(['code' => 'fr', 'name' => 'Français', 'sort' => 300]); + + $this->assertSame(['en', 'de', 'fr'], app(ContentLanguages::class)->codes()); + + // The site shows only two of them, the panel default is not among them: the first by order. + Site::query()->where('code', 'main')->update(['languages' => ['fr', 'de']]); + app(Sites::class)->flush(); + + $this->assertSame(['de', 'fr'], (new ContentLanguages)->codes()); + } + + // ---- Locales ------------------------------------------------------------------------------- + + public function test_without_a_locale_list_in_the_config_the_panel_is_english_only(): void + { + $this->app['config']->set('atrium', Arr::except(config('atrium'), 'locales')); + $locales = new Locales; + + $this->assertSame(['en' => 'English'], $locales->available()); + $this->assertTrue($locales->isAvailable('en')); + } + + public function test_a_locale_is_available_only_when_it_is_listed(): void + { + $locales = new Locales; + + $this->assertTrue($locales->isAvailable('ru')); + $this->assertFalse($locales->isAvailable('zz')); + $this->assertFalse($locales->isAvailable(null)); + $this->assertFalse($locales->isAvailable('')); + } + + public function test_a_default_locale_that_is_not_a_string_in_the_config_is_not_taken(): void + { + config(['atrium.locale' => 7]); + + $this->assertSame('en', (new Locales)->resolve(Request::create('/'), null)); + } + + public function test_the_dictionary_skips_validation_and_fills_the_gaps_of_a_language_from_english(): void + { + $dictionary = (new Locales)->dictionary('ru'); + + $this->assertArrayHasKey('common.save', $dictionary); + $this->assertSame([], array_filter(array_keys($dictionary), static fn (string $key): bool => str_starts_with($key, 'validation.'))); + + // A language that has only one line of a file: the rest comes from English. + app('translator')->addLines(['common.save' => 'Speichern'], 'xx', 'atrium'); + $partial = (new Locales)->dictionary('xx'); + + $english = (new Locales)->dictionary('en'); + $this->assertArrayHasKey('common.cancel', $english); + $this->assertSame($english['common.cancel'], $partial['common.cancel']); + $this->assertSame('Speichern', $partial['common.save']); + } + + public function test_a_language_with_no_lang_files_gives_the_english_dictionary_and_nothing_else(): void + { + $this->assertSame((new Locales)->dictionary('en'), (new Locales)->dictionary('qq')); + } + + public function test_the_validation_group_is_not_part_of_the_groups_of_the_dictionary_but_is_a_group(): void + { + $groups = (new Locales)->groups(); + + $this->assertContains('validation', $groups); + $this->assertContains('common', $groups); + } + + public function test_a_regional_browser_language_finds_the_plain_language_of_the_panel(): void + { + config(['atrium.locales' => ['en' => 'English', 'pt' => 'Português']]); + + $this->assertSame('pt', (new Locales)->resolve(Request::create('/', server: ['HTTP_ACCEPT_LANGUAGE' => 'pt-BR']), null)); + $this->assertSame('en', (new Locales)->resolve(Request::create('/', server: ['HTTP_ACCEPT_LANGUAGE' => 'fr-CA']), null)); + } + + // ---- MediaUrl ------------------------------------------------------------------------------ + + public function test_only_an_address_that_starts_with_a_scheme_or_slashes_is_taken_as_is(): void + { + $this->assertSame('http://localhost/storage/a//b.jpg', MediaUrl::to('a//b.jpg')); + $this->assertSame('http://localhost/storage/see-https://x.jpg', MediaUrl::to('see-https://x.jpg')); + $this->assertSame('HTTPS://CDN.example.com/a.jpg', MediaUrl::to('HTTPS://CDN.example.com/a.jpg')); + $this->assertSame('Http://cdn.example.com/a.jpg', MediaUrl::to('Http://cdn.example.com/a.jpg')); + } + + // ---- Menu ---------------------------------------------------------------------------------- + + public function test_a_menu_that_is_not_an_array_in_the_config_is_an_empty_menu(): void + { + config(['atrium.menu' => null]); + + $routes = array_column(app(Menu::class)->items(), 'route'); + + $this->assertContains('admin.posts.index', $routes); + } + + // ---- PublicUrl ------------------------------------------------------------------------------ + + public function test_a_parent_column_from_the_config_is_kept_as_text(): void + { + config()->set('atrium.public_urls.'.Post::class, ['prefix' => 'a', 'tree' => Handbook::class, 'parent' => 'x', 'parent_column' => 123]); + + $this->assertSame('123', PublicUrl::ruleFor(Post::class)['parent_column']); + } + + public function test_the_paths_of_two_trees_and_two_parent_columns_are_kept_apart(): void + { + PublicUrl::forgetPaths(); + $tours = Handbook::query()->create(['name' => 'Tours', 'code' => 'tours']); + Handbook::query()->create(['name' => 'Italy', 'code' => 'italy', 'parent_id' => $tours->id]); + $root = Section::query()->create(['name' => 'Root']); + DB::table('sections')->where('id', $root->id)->update(['parent_id' => null]); + + $handbook = PublicUrl::sectionPaths(Handbook::class); + $other = PublicUrl::sectionPaths(Section::class); + + $this->assertSame(['tours', 'tours/italy'], array_values($handbook)); + $this->assertNotSame($handbook, $other); + $this->assertCount(1, $other); + + // The same tree read by another column is another answer, not the cached one. + $this->assertSame(['tours', 'italy'], array_values(PublicUrl::sectionPaths(Handbook::class, 'section_parent'))); + $this->assertSame(['tours', 'tours/italy'], array_values(PublicUrl::sectionPaths(Handbook::class))); + PublicUrl::forgetPaths(); + } + + public function test_a_section_without_a_code_adds_nothing_to_the_path_of_its_children(): void + { + PublicUrl::forgetPaths(); + $tours = Handbook::query()->create(['name' => 'Tours', 'code' => 'tours']); + $hidden = Handbook::query()->create(['name' => 'Hidden', 'parent_id' => $tours->id]); + $hidden->forceFill(['code' => null])->saveQuietly(); + $deep = Handbook::query()->create(['name' => 'Deep', 'code' => 'deep', 'parent_id' => $hidden->id]); + + $paths = PublicUrl::sectionPaths(Handbook::class); + + $this->assertSame('tours', $paths[$hidden->id]); + $this->assertSame('tours/deep', $paths[$deep->id]); + PublicUrl::forgetPaths(); + } + + // ---- Sites --------------------------------------------------------------------------------- + + public function test_the_sites_are_read_once_and_the_default_one_is_the_first(): void + { + $sites = new Sites; + + $this->assertSame($sites->all(), $sites->all()); + $this->assertSame('main', $sites->default()->code); + } + + public function test_a_site_in_a_folder_with_no_domains_at_all_is_open_to_every_host(): void + { + $shop = Site::query()->create(['code' => 'shop', 'name' => 'Shop', 'folder' => 'shop']); + DB::table('admin_sites')->where('id', $shop->id)->update(['domains' => null]); + app(Sites::class)->flush(); + + $this->assertSame(['shop'], app(Sites::class)->folderSites('anything.test')->pluck('code')->all()); + } + + public function test_the_site_that_names_the_host_wins_in_the_same_folder(): void + { + Site::query()->create(['code' => 'any', 'name' => 'Any', 'folder' => 'shop']); + Site::query()->create(['code' => 'named', 'name' => 'Named', 'folder' => 'shop', 'domains' => ['b.test']]); + + $this->assertSame(['named'], app(Sites::class)->folderSites('b.test')->pluck('code')->all()); + $this->assertSame(['any'], app(Sites::class)->folderSites('a.test')->pluck('code')->all()); + } + + public function test_the_root_address_is_cut_only_at_a_folder_not_at_the_end_of_a_host_name(): void + { + $request = Request::create('http://myshop/catalog', server: [ + 'SCRIPT_NAME' => '/index.php', + 'SCRIPT_FILENAME' => '/var/www/index.php', + 'PHP_SELF' => '/index.php', + ]); + $request->attributes->set(EnterSiteFolder::FOLDER, 'shop'); + + $this->assertSame('http://myshop', Sites::rootUrl($request)); + } + + public function test_picking_a_site_and_forgetting_it_changes_the_content_languages_at_once(): void + { + Language::query()->create(['code' => 'fr', 'name' => 'Français', 'sort' => 300]); + $fr = Site::query()->create(['code' => 'fr', 'name' => 'France', 'languages' => ['fr']]); + $sites = app(Sites::class); + $sites->flush(); + $languages = app(ContentLanguages::class); + + $this->assertSame(['en', 'fr'], $languages->codes()); + + $sites->setCurrent($fr); + $this->assertSame(['fr'], $languages->codes()); + + $sites->forgetCurrent(); + $this->assertSame(['en', 'fr'], $languages->codes()); + } + + // ---- Themes -------------------------------------------------------------------------------- + + public function test_a_theme_of_the_account_is_taken_only_when_it_is_one_of_the_choices(): void + { + $themes = new Themes; + $user = new AdminUser; + + $this->assertSame($themes->default(), $themes->choiceFor(null)); + $this->assertSame($themes->default(), $themes->choiceFor($user)); + + $user->theme = 'system'; + $this->assertSame('system', $themes->choiceFor($user)); + + $user->theme = 'nonsense'; + $this->assertSame($themes->default(), $themes->choiceFor($user)); + } +} diff --git a/packages/admin/tests/Feature/ThemeTest.php b/packages/admin/tests/Feature/ThemeTest.php index 0bfb9dce..65fe7944 100644 --- a/packages/admin/tests/Feature/ThemeTest.php +++ b/packages/admin/tests/Feature/ThemeTest.php @@ -9,10 +9,13 @@ namespace Atrium\Admin\Tests\Feature; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\TestCase; final class ThemeTest extends TestCase { + use PinsExtensionSurface; + public function test_the_page_is_rendered_in_the_configured_theme(): void { config(['atrium.admin.theme' => 'sand']); @@ -68,6 +71,13 @@ public function test_an_unknown_theme_is_refused(): void $this->assertNull($admin->fresh()->theme); } + public function test_a_theme_is_required(): void + { + $this->actingAs($this->admin(), 'admin') + ->put('/admin/profile/theme', []) + ->assertSessionHasErrors('theme'); + } + public function test_a_guest_cannot_save_a_theme(): void { $this->put('/admin/profile/theme', ['theme' => 'night'])->assertRedirect('/admin/login'); diff --git a/packages/admin/tests/Feature/TranslationLikeTest.php b/packages/admin/tests/Feature/TranslationLikeTest.php new file mode 100644 index 00000000..d60a773d --- /dev/null +++ b/packages/admin/tests/Feature/TranslationLikeTest.php @@ -0,0 +1,33 @@ +create(['name' => ['en' => 'Alpha', 'de' => 'Beta']]); + + $find = fn (string $text, ?array $locales = null): int => Notice::query()->whereTranslationLike('name', $text, $locales)->count(); + + $this->assertSame(1, $find('alp')); + $this->assertSame(0, $find('bet')); + $this->assertSame(1, $find('bet', ['de'])); + $this->assertSame(0, $find('alp', ['de'])); + $this->assertSame(1, $find('alp', ['en', 'de'])); + $this->assertSame(1, $find('bet', ['en', 'de'])); + } +} diff --git a/packages/admin/tests/Fixtures/ApiEdges.php b/packages/admin/tests/Fixtures/ApiEdges.php new file mode 100644 index 00000000..e25b05ac --- /dev/null +++ b/packages/admin/tests/Fixtures/ApiEdges.php @@ -0,0 +1,55 @@ +label('Never in a form')->hideOnCreate()->hideOnEdit(), + TextField::make('name')->label('Name')->required(), + CheckboxField::make('agree')->label('Agree')->checkedValue('Y')->onlyOnCreate(), + MultiSelectField::make('tags')->label('Tags')->options(['a' => 'A'])->onlyOnEdit(), + TreeSelectField::make('section_id')->label('Section')->model(ApiAisle::class)->onlyOnCreate(), + NumberField::make('limit')->label('Limit')->onlyOnCreate(), + DateField::make('starts')->label('Starts')->onlyOnEdit(), + ]; + } + + public static function getAdministrationListColumns(): array + { + return [TextColumn::make('name')->label('Name')]; + } +} diff --git a/packages/admin/tests/Fixtures/Bare.php b/packages/admin/tests/Fixtures/Bare.php new file mode 100644 index 00000000..97029d09 --- /dev/null +++ b/packages/admin/tests/Fixtures/Bare.php @@ -0,0 +1,115 @@ +label('Name')]; + } + + public static function getAdministrationListColumns(): array + { + return [TextColumn::make('name')->label('Name')]; + } + + public static function getAdministrationFilters(): array + { + return []; + } + + public static function getAdminRoutePrefix(): string + { + return 'bares'; + } + + public static function getAdminRouteName(): string + { + return 'admin.bares'; + } + + public static function getAdminCreateLabel(): string + { + return 'Add bare'; + } + + public static function getDefaultSortColumn(): string + { + return 'id'; + } + + public static function getDefaultSortDirection(): string + { + return 'asc'; + } + + public static function getAdminPerPage(): int + { + return 20; + } + + public static function getCreateValidationRules(): array + { + return []; + } + + public static function getUpdateValidationRules(): array + { + return []; + } + + public function scopeAdminList(Builder $query): Builder + { + return $query; + } + + public function canDelete(): bool + { + return true; + } + + public function beforeAdminDelete(): bool + { + return true; + } + + public function transformAdminData(array $data): array + { + return $data; + } + + public function afterAdminSave(array $data): void {} + + public function getAdminTitle(): string + { + return (string) $this->name; + } +} diff --git a/packages/admin/tests/Fixtures/Brochure.php b/packages/admin/tests/Fixtures/Brochure.php new file mode 100644 index 00000000..7b51f641 --- /dev/null +++ b/packages/admin/tests/Fixtures/Brochure.php @@ -0,0 +1,49 @@ +label('Name')->required()]; + } + + public static function getAdminFieldsWithTabs(): array + { + return [...self::getAdministrationFields(), TextField::make('cover')->label('Cover')]; + } + + public static function getAdministrationListColumns(): array + { + return [TextColumn::make('name')->label('Name')]; + } +} diff --git a/packages/admin/tests/Fixtures/Bundle.php b/packages/admin/tests/Fixtures/Bundle.php new file mode 100644 index 00000000..7244e9e0 --- /dev/null +++ b/packages/admin/tests/Fixtures/Bundle.php @@ -0,0 +1,67 @@ +label('Name')->required(), + BelongsToManyField::make('extras')->label('Extras')->model(Post::class), + BelongsToManyField::make('posts')->label('Posts')->model(Post::class), + BelongsToManyField::make('topics')->label('Topics')->model(Topic::class), + ]; + } + + public static function getAdministrationListColumns(): array + { + return [TextColumn::make('name')->label('Name')]; + } + + /** + * @return BelongsToMany + */ + public function posts(): BelongsToMany + { + return $this->belongsToMany(Post::class, 'bundle_post'); + } + + /** + * @return BelongsToMany + */ + public function topics(): BelongsToMany + { + return $this->belongsToMany(Topic::class, 'bundle_topic'); + } +} diff --git a/packages/admin/tests/Fixtures/Dossier.php b/packages/admin/tests/Fixtures/Dossier.php new file mode 100644 index 00000000..3d6c726f --- /dev/null +++ b/packages/admin/tests/Fixtures/Dossier.php @@ -0,0 +1,48 @@ +label('Name')->required()]; + } + + public static function getAdministrationListColumns(): array + { + return [TextColumn::make('name')->label('Name')]; + } + + public static function isCreatableInAdmin(): bool + { + return false; + } +} diff --git a/packages/admin/tests/Fixtures/Gadget.php b/packages/admin/tests/Fixtures/Gadget.php index a6490eb4..c8b442a4 100644 --- a/packages/admin/tests/Fixtures/Gadget.php +++ b/packages/admin/tests/Fixtures/Gadget.php @@ -66,6 +66,40 @@ public function labelsWithMyId(): HasMany return $this->softHasMany(Label::class, 'id', 'label_id'); } + /** + * Keys left to their defaults. + * + * @return BelongsTo + */ + public function label2(): BelongsTo + { + return $this->softBelongsTo(Label::class); + } + + /** + * @return BelongsTo + */ + public function named(): BelongsTo + { + return $this->softBelongsTo(Label::class, 'label_id', null, 'chosen'); + } + + /** + * @return BelongsToMany + */ + public function tags2(): BelongsToMany + { + return $this->softBelongsToMany(Label::class, 'gadget_label', 'gadget_id'); + } + + /** + * @return BelongsToMany + */ + public function namedTags(): BelongsToMany + { + return $this->softBelongsToMany(Label::class, 'gadget_label', 'gadget_id', 'shade_id', 'chosen'); + } + public static function getAdminLabel(): string { return 'Gadgets'; diff --git a/packages/admin/tests/Fixtures/Memo.php b/packages/admin/tests/Fixtures/Memo.php new file mode 100644 index 00000000..7a4af2a9 --- /dev/null +++ b/packages/admin/tests/Fixtures/Memo.php @@ -0,0 +1,48 @@ +label('Name')->required()]; + } + + public static function getAdministrationListColumns(): array + { + return [TextColumn::make('name')->label('Name')]; + } + + public static function isEditableInAdmin(): bool + { + return false; + } +} diff --git a/packages/admin/tests/Fixtures/Modules/NoteSettings.php b/packages/admin/tests/Fixtures/Modules/NoteSettings.php new file mode 100644 index 00000000..c0d3aaeb --- /dev/null +++ b/packages/admin/tests/Fixtures/Modules/NoteSettings.php @@ -0,0 +1,30 @@ +required(), + ImageField::make('badge')->label('Badge'), + ]; + } +} diff --git a/packages/admin/tests/Fixtures/OpcacheSpy.php b/packages/admin/tests/Fixtures/OpcacheSpy.php new file mode 100644 index 00000000..a0869be5 --- /dev/null +++ b/packages/admin/tests/Fixtures/OpcacheSpy.php @@ -0,0 +1,31 @@ + */ + public static array $calls = []; +} diff --git a/packages/admin/tests/Fixtures/Remark.php b/packages/admin/tests/Fixtures/Remark.php index 7e3b7ea0..78b41b3e 100644 --- a/packages/admin/tests/Fixtures/Remark.php +++ b/packages/admin/tests/Fixtures/Remark.php @@ -35,4 +35,12 @@ public function subject(): MorphTo { return $this->softMorphTo(); } + + /** + * @return MorphTo + */ + public function other(): MorphTo + { + return $this->softMorphTo('subject'); + } } diff --git a/packages/admin/tests/Fixtures/Untimed.php b/packages/admin/tests/Fixtures/Untimed.php new file mode 100644 index 00000000..e6050d38 --- /dev/null +++ b/packages/admin/tests/Fixtures/Untimed.php @@ -0,0 +1,30 @@ + 'integer']; + } +} diff --git a/packages/admin/tests/Support/ExtensionSurface.php b/packages/admin/tests/Support/ExtensionSurface.php new file mode 100644 index 00000000..2de498aa --- /dev/null +++ b/packages/admin/tests/Support/ExtensionSurface.php @@ -0,0 +1,217 @@ + + */ + public static function methods(): array + { + return [ + 'Auth\Permissions::canSetUpAnything' => [Permissions::class, 'canSetUpAnything', 'public'], + 'Console\Commands\SlugRegenerateCommand::cleanupHistory' => [SlugRegenerateCommand::class, 'cleanupHistory', 'protected'], + 'Console\Commands\SlugRegenerateCommand::findModelsWithSlug' => [SlugRegenerateCommand::class, 'findModelsWithSlug', 'protected'], + 'Console\Commands\SlugRegenerateCommand::regenerateAll' => [SlugRegenerateCommand::class, 'regenerateAll', 'protected'], + 'Console\Commands\SlugRegenerateCommand::regenerateModel' => [SlugRegenerateCommand::class, 'regenerateModel', 'protected'], + 'Fields\Field::getFieldProps' => [Field::class, 'getFieldProps', 'protected'], + 'Fields\TreeSelectField::buildTree' => [TreeSelectField::class, 'buildTree', 'protected'], + 'Fields\TreeSelectField::defaultRootLabel' => [TreeSelectField::class, 'defaultRootLabel', 'protected'], + 'Fields\TreeSelectField::notItsOwnAncestorRule' => [TreeSelectField::class, 'notItsOwnAncestorRule', 'protected'], + 'Http\Controllers\AdminController::abilities' => [AdminController::class, 'abilities', 'protected'], + 'Http\Controllers\AdminController::allAdminFields' => [AdminController::class, 'allAdminFields', 'protected'], + 'Http\Controllers\AdminController::contextFields' => [AdminController::class, 'contextFields', 'protected'], + 'Http\Controllers\AdminController::create' => [AdminController::class, 'create', 'public'], + 'Http\Controllers\AdminController::createActions' => [AdminController::class, 'createActions', 'protected'], + 'Http\Controllers\AdminController::edit' => [AdminController::class, 'edit', 'public'], + 'Http\Controllers\AdminController::extractRelationValues' => [AdminController::class, 'extractRelationValues', 'protected'], + 'Http\Controllers\AdminController::extractSeoValues' => [AdminController::class, 'extractSeoValues', 'protected'], + 'Http\Controllers\AdminController::getPagePrefix' => [AdminController::class, 'getPagePrefix', 'protected'], + 'Http\Controllers\AdminController::ignoreCurrentRecord' => [AdminController::class, 'ignoreCurrentRecord', 'protected'], + 'Http\Controllers\AdminController::isPerSite' => [AdminController::class, 'isPerSite', 'protected'], + 'Http\Controllers\AdminController::listRow' => [AdminController::class, 'listRow', 'protected'], + 'Http\Controllers\AdminController::moduleAllows' => [AdminController::class, 'moduleAllows', 'protected'], + 'Http\Controllers\AdminController::normalizeTranslatableInput' => [AdminController::class, 'normalizeTranslatableInput', 'protected'], + 'Http\Controllers\AdminController::persistSeoValues' => [AdminController::class, 'persistSeoValues', 'protected'], + 'Http\Controllers\AdminController::prefillFromActions' => [AdminController::class, 'prefillFromActions', 'protected'], + 'Http\Controllers\AdminController::prepareFormData' => [AdminController::class, 'prepareFormData', 'protected'], + 'Http\Controllers\AdminController::preselectSection' => [AdminController::class, 'preselectSection', 'protected'], + 'Http\Controllers\AdminController::relatedColumns' => [AdminController::class, 'relatedColumns', 'protected'], + 'Http\Controllers\AdminController::resourceProps' => [AdminController::class, 'resourceProps', 'protected'], + 'Http\Controllers\AdminController::runValidation' => [AdminController::class, 'runValidation', 'protected'], + 'Http\Controllers\AdminController::sectionExists' => [AdminController::class, 'sectionExists', 'protected'], + 'Http\Controllers\AdminController::seoFieldMap' => [AdminController::class, 'seoFieldMap', 'protected'], + 'Http\Controllers\AdminController::serializeColumns' => [AdminController::class, 'serializeColumns', 'protected'], + 'Http\Controllers\AdminController::serializeFields' => [AdminController::class, 'serializeFields', 'protected'], + 'Http\Controllers\AdminController::serializeFieldsByTab' => [AdminController::class, 'serializeFieldsByTab', 'protected'], + 'Http\Controllers\AdminController::store' => [AdminController::class, 'store', 'public'], + 'Http\Controllers\AdminController::submittedData' => [AdminController::class, 'submittedData', 'protected'], + 'Http\Controllers\AdminController::syncRelations' => [AdminController::class, 'syncRelations', 'protected'], + 'Http\Controllers\AdminController::translatableAttributes' => [AdminController::class, 'translatableAttributes', 'protected'], + 'Http\Controllers\AdminController::translatableRules' => [AdminController::class, 'translatableRules', 'protected'], + 'Http\Controllers\AdminController::uniqueRule' => [AdminController::class, 'uniqueRule', 'protected'], + 'Http\Controllers\AdminController::update' => [AdminController::class, 'update', 'public'], + 'Http\Controllers\AdminController::validationAttributes' => [AdminController::class, 'validationAttributes', 'protected'], + 'Http\Controllers\ApiTokenController::destroy' => [ApiTokenController::class, 'destroy', 'public'], + 'Http\Controllers\ApiTokenController::index' => [ApiTokenController::class, 'index', 'public'], + 'Http\Controllers\ApiTokenController::store' => [ApiTokenController::class, 'store', 'public'], + 'Http\Controllers\Api\DocsController::markdown' => [DocsController::class, 'markdown', 'public'], + 'Http\Controllers\Api\DocsController::openApi' => [DocsController::class, 'openApi', 'public'], + 'Http\Controllers\Api\ResourceController::showItem' => [ResourceController::class, 'showItem', 'public'], + 'Http\Controllers\Api\ResourceController::storeItem' => [ResourceController::class, 'storeItem', 'public'], + 'Http\Controllers\Api\ResourceController::updateItem' => [ResourceController::class, 'updateItem', 'public'], + 'Http\Controllers\Api\ResourceController::upload' => [ResourceController::class, 'upload', 'public'], + 'Http\Controllers\Auth\LoginController::login' => [LoginController::class, 'login', 'public'], + 'Http\Controllers\Auth\LoginController::logout' => [LoginController::class, 'logout', 'public'], + 'Http\Controllers\CaptchaController::image' => [CaptchaController::class, 'image', 'public'], + 'Http\Controllers\DashboardController::gadgets' => [DashboardController::class, 'gadgets', 'protected'], + 'Http\Controllers\DashboardController::index' => [DashboardController::class, 'index', 'public'], + 'Http\Controllers\FileManagerController::index' => [FileManagerController::class, 'index', 'public'], + 'Http\Controllers\LocaleController::update' => [LocaleController::class, 'update', 'public'], + 'Http\Controllers\ModuleController::disable' => [ModuleController::class, 'disable', 'public'], + 'Http\Controllers\ModuleController::enable' => [ModuleController::class, 'enable', 'public'], + 'Http\Controllers\ModuleController::settings' => [ModuleController::class, 'settings', 'public'], + 'Http\Controllers\ModuleController::update' => [ModuleController::class, 'update', 'public'], + 'Http\Controllers\ProfileController::update' => [ProfileController::class, 'update', 'public'], + 'Http\Controllers\ProfileController::updatePassword' => [ProfileController::class, 'updatePassword', 'public'], + 'Http\Controllers\RoleController::create' => [RoleController::class, 'create', 'public'], + 'Http\Controllers\RoleController::destroy' => [RoleController::class, 'destroy', 'public'], + 'Http\Controllers\RoleController::edit' => [RoleController::class, 'edit', 'public'], + 'Http\Controllers\RoleController::index' => [RoleController::class, 'index', 'public'], + 'Http\Controllers\RoleController::store' => [RoleController::class, 'store', 'public'], + 'Http\Controllers\RoleController::update' => [RoleController::class, 'update', 'public'], + 'Http\Controllers\SeoFilesController::robots' => [SeoFilesController::class, 'robots', 'public'], + 'Http\Controllers\SeoFilesController::sitemap' => [SeoFilesController::class, 'sitemap', 'public'], + 'Http\Controllers\SeoFilesController::sitemapPart' => [SeoFilesController::class, 'sitemapPart', 'public'], + 'Http\Controllers\SiteController::update' => [SiteController::class, 'update', 'public'], + 'Http\Controllers\ThemeController::update' => [ThemeController::class, 'update', 'public'], + 'Http\Requests\Auth\LoginRequest::ensureIsNotRateLimited' => [LoginRequest::class, 'ensureIsNotRateLimited', 'public'], + 'Http\Requests\Auth\LoginRequest::throttleKey' => [LoginRequest::class, 'throttleKey', 'public'], + 'Mcp\Tools\ApiTool::owner' => [ApiTool::class, 'owner', 'protected'], + 'Models\AdminUser::actingSuperadmin' => [AdminUser::class, 'actingSuperadmin', 'protected'], + 'Models\File::fileable' => [File::class, 'fileable', 'public'], + 'Models\File::getFullPathAttribute' => [File::class, 'getFullPathAttribute', 'public'], + 'Models\File::getHumanSizeAttribute' => [File::class, 'getHumanSizeAttribute', 'public'], + 'Models\File::getUrlAttribute' => [File::class, 'getUrlAttribute', 'public'], + 'Models\MediaCollection::children' => [MediaCollection::class, 'children', 'public'], + 'Models\MediaItem::collection' => [MediaItem::class, 'collection', 'public'], + 'Models\MediaItem::scopeDocuments' => [MediaItem::class, 'scopeDocuments', 'public'], + 'Models\MediaItem::scopeImages' => [MediaItem::class, 'scopeImages', 'public'], + 'Models\SeoMeta::getOgDescriptionAttribute' => [SeoMeta::class, 'getOgDescriptionAttribute', 'public'], + 'Models\SeoMeta::getOgTitleAttribute' => [SeoMeta::class, 'getOgTitleAttribute', 'public'], + 'Models\SeoMeta::seoable' => [SeoMeta::class, 'seoable', 'public'], + 'Models\Site::getAdminTabs' => [Site::class, 'getAdminTabs', 'public'], + 'Models\Site::normalizeFolder' => [Site::class, 'normalizeFolder', 'public'], + 'Models\Slug::findByPath' => [Slug::class, 'findByPath', 'public'], + 'Models\Slug::findBySlug' => [Slug::class, 'findBySlug', 'public'], + 'Models\Slug::resolve' => [Slug::class, 'resolve', 'public'], + 'Models\Slug::resolvePath' => [Slug::class, 'resolvePath', 'public'], + 'Models\Slug::sluggable' => [Slug::class, 'sluggable', 'public'], + 'Models\SlugHistory::cleanup' => [SlugHistory::class, 'cleanup', 'public'], + 'Models\SlugHistory::findRedirect' => [SlugHistory::class, 'findRedirect', 'public'], + 'Models\SlugHistory::findRedirectPath' => [SlugHistory::class, 'findRedirectPath', 'public'], + 'Models\SlugHistory::sluggable' => [SlugHistory::class, 'sluggable', 'public'], + 'Services\SlugService::cachePathSlug' => [SlugService::class, 'cachePathSlug', 'protected'], + 'Services\SlugService::cacheSlug' => [SlugService::class, 'cacheSlug', 'protected'], + 'Services\SlugService::getCacheKey' => [SlugService::class, 'getCacheKey', 'protected'], + 'Services\SlugService::getPathCacheKey' => [SlugService::class, 'getPathCacheKey', 'protected'], + 'Support\Locales::groups' => [Locales::class, 'groups', 'public'], + 'Support\Locales::isAvailable' => [Locales::class, 'isAvailable', 'public'], + 'Support\Sites::forHost' => [Sites::class, 'forHost', 'public'], + 'Support\Themes::isChoice' => [Themes::class, 'isChoice', 'public'], + 'Traits\BelongsToSite::bootBelongsToSite' => [BelongsToSite::class, 'bootBelongsToSite', 'public'], + 'Traits\BelongsToSite::site' => [BelongsToSite::class, 'site', 'public'], + 'Traits\HasAdminFiles::bootHasAdminFiles' => [HasAdminFiles::class, 'bootHasAdminFiles', 'public'], + 'Traits\HasAdminSeo::bootHasAdminSeo' => [HasAdminSeo::class, 'bootHasAdminSeo', 'public'], + 'Traits\HasAdminSeo::getDefaultSeoDescription' => [HasAdminSeo::class, 'getDefaultSeoDescription', 'protected'], + 'Traits\HasAdminSeo::getDefaultSeoTitle' => [HasAdminSeo::class, 'getDefaultSeoTitle', 'protected'], + 'Traits\HasAdminSeo::getSeoAdminFields' => [HasAdminSeo::class, 'getSeoAdminFields', 'public'], + 'Traits\HasAdminSeo::getSeoDescriptionTemplate' => [HasAdminSeo::class, 'getSeoDescriptionTemplate', 'protected'], + 'Traits\HasAdminSeo::getSeoTitleTemplate' => [HasAdminSeo::class, 'getSeoTitleTemplate', 'protected'], + 'Traits\HasAdminSeo::processSeoTemplate' => [HasAdminSeo::class, 'processSeoTemplate', 'protected'], + 'Traits\HasAdminSeo::seoFieldMap' => [HasAdminSeo::class, 'seoFieldMap', 'public'], + 'Traits\HasAdminSlug::bootHasAdminSlug' => [HasAdminSlug::class, 'bootHasAdminSlug', 'public'], + 'Traits\HasAdminSlug::cacheSlug' => [HasAdminSlug::class, 'cacheSlug', 'protected'], + 'Traits\HasAdminSlug::clearSlugCache' => [HasAdminSlug::class, 'clearSlugCache', 'protected'], + 'Traits\HasAdminSlug::createSlugRecord' => [HasAdminSlug::class, 'createSlugRecord', 'protected'], + 'Traits\HasAdminSlug::ensureUniqueSlug' => [HasAdminSlug::class, 'ensureUniqueSlug', 'protected'], + 'Traits\HasAdminSlug::findByFullPath' => [HasAdminSlug::class, 'findByFullPath', 'public'], + 'Traits\HasAdminSlug::findBySlug' => [HasAdminSlug::class, 'findBySlug', 'public'], + 'Traits\HasAdminSlug::findRedirect' => [HasAdminSlug::class, 'findRedirect', 'public'], + 'Traits\HasAdminSlug::getSlugCacheKey' => [HasAdminSlug::class, 'getSlugCacheKey', 'protected'], + 'Traits\HasAdminSlug::saveSlugToHistory' => [HasAdminSlug::class, 'saveSlugToHistory', 'protected'], + 'Traits\HasAdminSlug::transliterate' => [HasAdminSlug::class, 'transliterate', 'protected'], + 'Traits\HasAdminSlug::updateSlugRecord' => [HasAdminSlug::class, 'updateSlugRecord', 'protected'], + 'Traits\HasAdminTabs::getAdminFieldsWithTabs' => [HasAdminTabs::class, 'getAdminFieldsWithTabs', 'public'], + 'Traits\HasAdminTabs::getAdminTabs' => [HasAdminTabs::class, 'getAdminTabs', 'public'], + 'Traits\HasAdminTabs::getFieldsGroupedByTabs' => [HasAdminTabs::class, 'getFieldsGroupedByTabs', 'public'], + 'Traits\HasAdminTabs::usesTabs' => [HasAdminTabs::class, 'usesTabs', 'public'], + 'Traits\HasSoftRelations::softBelongsTo' => [HasSoftRelations::class, 'softBelongsTo', 'protected'], + 'Traits\HasSoftRelations::softBelongsToMany' => [HasSoftRelations::class, 'softBelongsToMany', 'protected'], + 'Traits\HasSoftRelations::softHasMany' => [HasSoftRelations::class, 'softHasMany', 'protected'], + 'Traits\HasSoftRelations::softMorphTo' => [HasSoftRelations::class, 'softMorphTo', 'protected'], + 'Traits\InteractsWithAdmin::getAdministrationActions' => [InteractsWithAdmin::class, 'getAdministrationActions', 'public'], + 'Traits\InteractsWithAdmin::getAdministrationFilters' => [InteractsWithAdmin::class, 'getAdministrationFilters', 'public'], + 'Traits\InteractsWithAdmin::isCreatableInAdmin' => [InteractsWithAdmin::class, 'isCreatableInAdmin', 'public'], + 'Traits\InteractsWithAdmin::isEditableInAdmin' => [InteractsWithAdmin::class, 'isEditableInAdmin', 'public'], + 'Traits\Translatable::getFallbackLocale' => [Translatable::class, 'getFallbackLocale', 'public'], + ]; + } +} diff --git a/packages/admin/tests/TestCase.php b/packages/admin/tests/TestCase.php index 49e9d739..6b892303 100644 --- a/packages/admin/tests/TestCase.php +++ b/packages/admin/tests/TestCase.php @@ -12,13 +12,17 @@ use Atrium\Admin\AtriumServiceProvider; use Atrium\Admin\Models\AdminUser; use Atrium\Admin\Tests\Fixtures\Post; +use Closure; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabaseState; +use Illuminate\Http\Request; use Illuminate\Routing\Route; +use Illuminate\Routing\Router; use Inertia\ServiceProvider as InertiaServiceProvider; use Laravel\Mcp\Server\McpServiceProvider; use Orchestra\Testbench\TestCase as Orchestra; use ReflectionMethod; +use Symfony\Component\HttpFoundation\Response; use Tighten\Ziggy\ZiggyServiceProvider; abstract class TestCase extends Orchestra @@ -116,4 +120,30 @@ protected function assertRouteActionsArePublic(): array return $actions; } + + /** + * A router that dispatches nothing: it keeps the request it was given in + * ->seen and answers with whatever the closure returns. + * + * @param Closure(Request):Response $answer + */ + protected function recordingRouter(Closure $answer): Router + { + return new class($this->app['events'], $answer) extends Router + { + public ?Request $seen = null; + + public function __construct($events, private readonly Closure $answer) + { + parent::__construct($events); + } + + public function dispatch(Request $request) + { + $this->seen = $request; + + return ($this->answer)($request); + } + }; + } } diff --git a/packages/admin/tests/Unit/ConfigWriterTest.php b/packages/admin/tests/Unit/ConfigWriterTest.php index c551df63..d9606f1f 100644 --- a/packages/admin/tests/Unit/ConfigWriterTest.php +++ b/packages/admin/tests/Unit/ConfigWriterTest.php @@ -10,8 +10,12 @@ namespace Atrium\Admin\Tests\Unit; use Atrium\Admin\Support\ConfigWriter; +use Atrium\Admin\Tests\Fixtures\OpcacheSpy; use PHPUnit\Framework\TestCase; +// Loaded with the test: a call is looked up once, so the stand-in must be there before the first write. +require_once dirname(__DIR__).'/Fixtures/OpcacheSpy.php'; + final class ConfigWriterTest extends TestCase { private string $path; @@ -132,4 +136,46 @@ public function test_a_missing_config_is_reported_for_every_change(): void $this->assertFalse(ConfigWriter::enableModule('acme/one', $missing)); $this->assertFileDoesNotExist($missing); } + + public function test_a_resource_is_written_as_a_fully_qualified_class_name(): void + { + $this->config(" 'resources' => [\n ],\n"); + + $this->assertTrue(ConfigWriter::addResource('App\\Models\\Article', $this->path)); + $this->assertTrue(ConfigWriter::addResource('\\App\\Models\\Page', $this->path)); + + $this->assertStringContainsString(" \\App\\Models\\Article::class,\n", (string) file_get_contents($this->path)); + $this->assertStringContainsString(" \\App\\Models\\Page::class,\n", (string) file_get_contents($this->path)); + $this->assertStringNotContainsString('\\\\', (string) file_get_contents($this->path)); + } + + public function test_an_entry_in_the_list_is_not_added_twice_and_one_named_like_the_list_is_added(): void + { + $this->config(" 'resources' => [\n ],\n\n 'modules' => [\n 'acme/one',\n ],\n"); + + $this->assertTrue(ConfigWriter::addModule('modules', $this->path)); + $this->assertTrue(ConfigWriter::addModule('acme/one', $this->path)); + + $this->assertSame(['acme/one', 'modules'], $this->read()['modules']); + } + + public function test_the_file_is_dropped_from_the_opcache_after_every_write(): void + { + if (! function_exists('opcache_invalidate')) { + $this->markTestSkipped('The opcache extension is not loaded.'); + } + + OpcacheSpy::$calls = []; + $this->config(" 'resources' => [\n ],\n\n 'modules' => [\n ],\n"); + + ConfigWriter::addModule('acme/one', $this->path); + $this->assertSame([[$this->path, true]], OpcacheSpy::$calls); + + ConfigWriter::removeModule('acme/one', $this->path); + $this->assertSame([[$this->path, true], [$this->path, true]], OpcacheSpy::$calls); + + // Nothing written, nothing to drop. + ConfigWriter::addResource('App\\Models\\Page', $this->path.'.missing'); + $this->assertCount(2, OpcacheSpy::$calls); + } } diff --git a/packages/admin/tests/Unit/ExtensionSurfaceTest.php b/packages/admin/tests/Unit/ExtensionSurfaceTest.php new file mode 100644 index 00000000..197e5c7d --- /dev/null +++ b/packages/admin/tests/Unit/ExtensionSurfaceTest.php @@ -0,0 +1,40 @@ + + */ + public static function methods(): array + { + return ExtensionSurface::methods(); + } + + #[DataProvider('methods')] + public function test_a_method_is_as_visible_as_the_extension_api_says(string $class, string $method, string $visibility): void + { + $reflection = new ReflectionMethod($class, $method); + + $this->assertSame($visibility === 'public', $reflection->isPublic()); + $this->assertSame($visibility === 'protected', $reflection->isProtected()); + } +} diff --git a/packages/admin/tests/Unit/Fields/FieldSwitchesTest.php b/packages/admin/tests/Unit/Fields/FieldSwitchesTest.php new file mode 100644 index 00000000..c220ccee --- /dev/null +++ b/packages/admin/tests/Unit/Fields/FieldSwitchesTest.php @@ -0,0 +1,50 @@ + + */ + public static function switches(): array + { + return [ + 'belongs to: searchable' => [fn (): Field => BelongsToField::make('a'), 'searchable', 'searchable'], + 'belongs to: clearable' => [fn (): Field => BelongsToField::make('a'), 'clearable', 'clearable'], + 'select: clearable' => [fn (): Field => SelectField::make('a'), 'clearable', 'clearable'], + 'gallery: sortable' => [fn (): Field => GalleryField::make('a'), 'sortable', 'sortable'], + 'image: preview' => [fn (): Field => ImageField::make('a'), 'showPreview', 'showPreview'], + 'map: address search' => [fn (): Field => MapField::make('a'), 'searchEnabled', 'searchEnabled'], + 'slug: auto-generation' => [fn (): Field => SlugField::make('a')->baseUrl('https://x.example'), 'autoGenerate', 'autoGenerate'], + 'slug: preview' => [fn (): Field => SlugField::make('a')->baseUrl('https://x.example'), 'showPreview', 'showPreview'], + ]; + } + + #[DataProvider('switches')] + public function test_a_switch_called_without_an_argument_turns_the_option_on(\Closure $make, string $method, string $prop): void + { + $this->assertTrue($make()->{$method}(false)->{$method}()->toArray()[$prop]); + $this->assertFalse($make()->{$method}(true)->{$method}(false)->toArray()[$prop]); + } +} diff --git a/packages/admin/tests/Unit/Fields/FileFieldsTest.php b/packages/admin/tests/Unit/Fields/FileFieldsTest.php index 03efc773..ce16a35f 100644 --- a/packages/admin/tests/Unit/Fields/FileFieldsTest.php +++ b/packages/admin/tests/Unit/Fields/FileFieldsTest.php @@ -59,6 +59,13 @@ public function test_a_file_field_takes_any_file_up_to_ten_megabytes(): void $this->assertSame(['disk' => 'public', 'directory' => 'uploads', 'maxSize' => 10240, 'acceptedTypes' => [], 'accept' => null], array_intersect_key($field->toArray(), array_flip(['disk', 'directory', 'maxSize', 'acceptedTypes', 'accept']))); } + public function test_a_file_field_is_checked_without_a_context_as_a_plain_value(): void + { + $this->assertNotContains('file', FileField::make('document')->getValidationRules()); + $this->assertNotContains('file', FileField::make('document')->getValidationRules(FieldContext::create('uploads/a.pdf'))); + $this->assertContains('file', FileField::make('document')->getValidationRules(FieldContext::create(UploadedFile::fake()->create('a.pdf', 1)))); + } + public function test_a_file_field_takes_its_storage_and_limits(): void { $array = FileField::make('document')->disk('s3')->directory('docs/2026')->maxSize(500)->acceptedTypes(['text/csv'])->accept('.csv')->toArray(); diff --git a/packages/admin/tests/Unit/Fields/RelationFieldsTest.php b/packages/admin/tests/Unit/Fields/RelationFieldsTest.php index d915d0fb..032aa699 100644 --- a/packages/admin/tests/Unit/Fields/RelationFieldsTest.php +++ b/packages/admin/tests/Unit/Fields/RelationFieldsTest.php @@ -13,6 +13,7 @@ use Atrium\Admin\Fields\BelongsToManyField; use Atrium\Admin\Fields\FieldContext; use Atrium\Admin\Fields\TreeSelectField; +use Atrium\Admin\Tests\Concerns\PinsExtensionSurface; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\Fixtures\Section; use Illuminate\Database\Eloquent\Builder; @@ -24,6 +25,8 @@ */ final class RelationFieldsTest extends FieldTestCase { + use PinsExtensionSurface; + public function test_a_belongs_to_field_without_a_model_offers_nothing(): void { $field = BelongsToField::make('post_id'); @@ -236,6 +239,8 @@ public function test_a_tree_select_takes_its_display_settings(): void $this->assertFalse($array['clearable']); $this->assertTrue($array['multiple']); $this->assertTrue($array['expandAll']); + $this->assertTrue(TreeSelectField::make('a')->searchable(false)->searchable()->toArray()['searchable']); + $this->assertTrue(TreeSelectField::make('a')->clearable(false)->clearable()->toArray()['clearable']); $this->assertFalse(TreeSelectField::make('a')->expandAll()->expandAll(false)->toArray()['expandAll']); $this->assertFalse(TreeSelectField::make('a')->multiple()->multiple(false)->toArray()['multiple']); } @@ -442,6 +447,9 @@ public function test_the_cycle_check_is_added_when_editing_the_parent_of_a_saved $rules[2]('parent_id', '0', $fail); $this->assertSame([], $failures, 'no parent is never a cycle'); + $rules[2]('parent_id', [$section->id], $fail); + $this->assertSame([], $failures, 'a list is not one section; there is nothing to walk and nothing to fail on'); + $rules[2]('parent_id', (string) $section->id, $fail); $this->assertSame([__('atrium::fields.validation.own_ancestor')], $failures); diff --git a/packages/admin/tests/Unit/ResourceRegistryTest.php b/packages/admin/tests/Unit/ResourceRegistryTest.php index 106c51b8..283fcc58 100644 --- a/packages/admin/tests/Unit/ResourceRegistryTest.php +++ b/packages/admin/tests/Unit/ResourceRegistryTest.php @@ -9,9 +9,12 @@ namespace Atrium\Admin\Tests\Unit; +use Atrium\Admin\Contracts\Administrable; use Atrium\Admin\Models\Language; use Atrium\Admin\Models\Site; +use Atrium\Admin\Modules\Modules; use Atrium\Admin\Resources\ResourceRegistry; +use Atrium\Admin\Tests\Fixtures\Modules\Label; use Atrium\Admin\Tests\Fixtures\NotAdministrable; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; @@ -28,6 +31,36 @@ public function test_a_configured_model_becomes_a_module_keyed_by_its_route_pref $this->assertSame(Post::class, $registry->modelForRoute('admin.posts.edit')); } + public function test_a_module_of_a_package_that_is_not_installed_is_left_out_without_stopping_the_list(): void + { + $this->app->make(Modules::class)->add(Label::module()); + config(['atrium.resources' => [Label::class, Post::class]]); + + $this->assertSame(['sites' => Site::class, 'languages' => Language::class, 'posts' => Post::class], (new ResourceRegistry)->all()); + } + + public function test_the_list_is_built_once_until_it_is_flushed(): void + { + $registry = new ResourceRegistry; + $this->assertArrayHasKey('posts', $registry->all()); + + config(['atrium.resources' => []]); + $this->assertArrayHasKey('posts', $registry->all(), 'Kept from the first time.'); + + $registry->flush(); + $this->assertArrayNotHasKey('posts', $registry->all()); + } + + public function test_only_a_route_of_the_panel_with_a_module_and_an_action_names_a_module(): void + { + $registry = new ResourceRegistry; + + $this->assertNull($registry->modelForRoute('other.admin.posts.edit')); + $this->assertNull($registry->modelForRoute('admin.posts.edit.copy')); + $this->assertNull($registry->modelForRoute('admin.posts.Edit')); + $this->assertSame(Post::class, $registry->modelForRoute('admin.posts.index')); + } + public function test_unknown_routes_resolve_to_nothing(): void { $registry = new ResourceRegistry; @@ -42,7 +75,7 @@ public function test_a_model_without_the_contract_is_rejected_with_a_clear_messa config(['atrium.resources' => [NotAdministrable::class]]); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('must be an Eloquent model that implements'); + $this->expectExceptionMessage('Atrium resource ['.NotAdministrable::class.'] must be an Eloquent model that implements '.Administrable::class.'.'); (new ResourceRegistry)->all(); } diff --git a/packages/admin/tests/Unit/Tabs/TabRegistryTest.php b/packages/admin/tests/Unit/Tabs/TabRegistryTest.php index 793c9729..4a984afe 100644 --- a/packages/admin/tests/Unit/Tabs/TabRegistryTest.php +++ b/packages/admin/tests/Unit/Tabs/TabRegistryTest.php @@ -115,6 +115,17 @@ public function test_tabs_are_sorted_by_order_whether_objects_or_arrays(): void $this->assertSame([], TabRegistry::sortTabs([])); } + public function test_a_tab_without_an_order_counts_as_zero_on_either_side_of_a_comparison(): void + { + $names = static fn (array $tabs): array => array_map(static fn (array $tab): string => $tab['name'], TabRegistry::sortTabs($tabs)); + + $this->assertSame(['unordered', 'zero'], $names([['name' => 'unordered'], ['name' => 'zero', 'order' => 0]])); + $this->assertSame(['zero', 'unordered'], $names([['name' => 'zero', 'order' => 0], ['name' => 'unordered']])); + $this->assertSame(['negative', 'unordered', 'one'], $names([['name' => 'one', 'order' => 1], ['name' => 'unordered'], ['name' => 'negative', 'order' => -1]])); + $this->assertSame(['negative', 'unordered', 'one'], $names([['name' => 'unordered'], ['name' => 'one', 'order' => 1], ['name' => 'negative', 'order' => -1]])); + $this->assertSame(['negative', 'unordered', 'one'], $names([['name' => 'negative', 'order' => -1], ['name' => 'one', 'order' => 1], ['name' => 'unordered']])); + } + public function test_a_tab_is_found_by_its_name(): void { $tabs = [['name' => 'seo'], Tab::make('main'), Tab::make('seo')->label('Found')]; diff --git a/packages/admin/tests/Unit/WebpCopyTest.php b/packages/admin/tests/Unit/WebpCopyTest.php index adc5980c..9dadcd5f 100644 --- a/packages/admin/tests/Unit/WebpCopyTest.php +++ b/packages/admin/tests/Unit/WebpCopyTest.php @@ -119,6 +119,15 @@ public function test_a_wide_picture_is_scaled_down_to_the_width_keeping_its_shap $this->assertSame([100, 51], array_slice((array) getimagesize($source.'.webp'), 0, 2)); } + public function test_a_strip_so_wide_that_it_scales_to_under_half_a_pixel_keeps_one_pixel_of_height(): void + { + // 1 * 100 / 300 = 0.33: no picture is zero pixels high. + $source = $this->photo('strip.png', 300, 1); + + $this->assertSame('made', WebpCopy::make($source, 82, 100)['status']); + $this->assertSame([100, 1], array_slice((array) getimagesize($source.'.webp'), 0, 2)); + } + public function test_a_picture_at_the_width_or_with_no_limit_keeps_its_size(): void { $exact = $this->photo('exact.png', 100, 40); @@ -242,4 +251,193 @@ public function test_transparency_survives_the_copy(): void $this->assertSame(127, (imagecolorat($copy, 5, 5) >> 24) & 0x7F); $this->assertSame(0, (imagecolorat($copy, 50, 5) >> 24) & 0x7F); } + + /** + * Garbage after the PNG's last chunk: decoders stop at IEND, so the + * picture stays the same and the file weighs exactly $size bytes. + */ + private function weighing(string $path, int $size): string + { + $current = (int) filesize($path); + $this->assertLessThanOrEqual($size, $current); + file_put_contents($path, str_repeat("\0", $size - $current), FILE_APPEND); + + return $path; + } + + /** + * The gradient webp cannot beat: a few hundred bytes in PNG. + */ + private function badge(string $name): string + { + $image = imagecreatetruecolor(16, 16); + for ($x = 0; $x < 16; $x++) { + for ($y = 0; $y < 16; $y++) { + imagesetpixel($image, $x, $y, ($x * 16 << 16) | ($y * 16 << 8)); + } + } + $path = "{$this->dir}/{$name}"; + imagepng($image, $path, 9); + + return $path; + } + + /** + * A $width x $height PNG, solid, padded to weigh far more than its copy. + */ + private function heavy(string $name, int $width, int $height): string + { + $image = imagecreatetruecolor($width, $height); + $path = "{$this->dir}/{$name}"; + imagepng($image, $path); + + return $this->weighing($path, 100_000); + } + + /** + * @return array{int,int} width and height of the copy + */ + private function sizeOfCopy(string $source): array + { + $info = (array) getimagesize($source.'.webp'); + + return [$info[0], $info[1]]; + } + + public function test_the_default_quality_is_82(): void + { + $default = $this->photo('default.png', 96, 96); + $lower = $this->photo('lower.png', 96, 96); + $same = $this->photo('same.png', 96, 96); + $higher = $this->photo('higher.png', 96, 96); + + WebpCopy::make($default); + WebpCopy::make($lower, 81); + WebpCopy::make($same, 82); + WebpCopy::make($higher, 83); + + $this->assertFileEquals($default.'.webp', $same.'.webp'); + $this->assertFileNotEquals($default.'.webp', $lower.'.webp'); + $this->assertFileNotEquals($default.'.webp', $higher.'.webp'); + } + + public function test_the_default_width_limit_is_1920_pixels(): void + { + $exact = $this->heavy('exact.png', 1920, 2); + $over = $this->heavy('over.png', 1921, 2); + $under = $this->heavy('under.png', 1919, 2); + + foreach ([$exact, $over, $under] as $source) { + $this->assertSame('made', WebpCopy::make($source)['status']); + } + + $this->assertSame([1920, 2], $this->sizeOfCopy($exact)); + $this->assertSame([1920, 2], $this->sizeOfCopy($over)); + $this->assertSame([1919, 2], $this->sizeOfCopy($under)); + } + + public function test_a_copy_exactly_as_heavy_as_the_source_is_thrown_away_and_one_byte_lighter_kept(): void + { + $probe = WebpCopy::make($this->weighing($this->badge('probe.png'), 5000), 100); + $this->assertSame('made', $probe['status']); + $copy = $probe['after']; + + $this->assertSame(['status' => 'rejected'], WebpCopy::make($this->weighing($this->badge('lighter.png'), $copy - 1), 100)); + $this->assertSame(['status' => 'rejected'], WebpCopy::make($this->weighing($this->badge('equal.png'), $copy), 100)); + $this->assertFileDoesNotExist("{$this->dir}/equal.png.webp"); + $this->assertSame( + ['status' => 'made', 'before' => $copy + 1, 'after' => $copy], + WebpCopy::make($this->weighing($this->badge('heavier.png'), $copy + 1), 100), + ); + } + + public function test_a_copy_whose_source_is_gone_is_not_a_copy_to_skip(): void + { + file_put_contents("{$this->dir}/orphan.png.webp", 'left behind'); + + $this->assertSame(['status' => 'failed'], WebpCopy::make("{$this->dir}/orphan.png")); + } + + public function test_the_pixel_limit_counts_width_times_height_and_stops_above_it(): void + { + $source = $this->heavy('ten.png', 10, 10); + + $this->assertSame('made', WebpCopy::make($source, maxPixels: 100)['status']); + $this->assertSame(['status' => 'failed'], WebpCopy::make($source, force: true, maxPixels: 99)); + // 20 x 5 is 100 pixels too, though 20 / 5 is 4. + $this->assertSame('made', WebpCopy::make($this->heavy('wide.png', 20, 5), maxPixels: 100)['status']); + } + + public function test_the_height_of_a_scaled_picture_is_rounded_to_the_nearest_pixel(): void + { + $down = $this->heavy('down.png', 1000, 3); + $up = $this->heavy('up.png', 1000, 3); + + WebpCopy::make($down, 82, 410); + WebpCopy::make($up, 82, 590); + + // 3 * 410 / 1000 = 1.23 and 3 * 590 / 1000 = 1.77. + $this->assertSame([410, 1], $this->sizeOfCopy($down)); + $this->assertSame([590, 2], $this->sizeOfCopy($up)); + } + + public function test_scaling_keeps_every_part_of_the_picture_in_its_place(): void + { + $image = imagecreatetruecolor(16, 16); + imagefill($image, 0, 0, 0x0000FF); + imagefilledrectangle($image, 0, 0, 7, 7, 0xFF0000); + $source = "{$this->dir}/quarters.png"; + imagepng($image, $source); + $this->weighing($source, 100_000); + + $this->assertSame('made', WebpCopy::make($source, 101, 8)['status']); + + $copy = imagecreatefromwebp($source.'.webp'); + $this->assertNotFalse($copy); + foreach ([[0, 0], [3, 0], [0, 3], [3, 3]] as [$x, $y]) { + $this->assertSame(0xFF0000, imagecolorat($copy, $x, $y) & 0xFFFFFF, "red at {$x},{$y}"); + } + foreach ([[4, 0], [0, 4], [4, 4], [7, 7], [7, 0], [0, 7]] as [$x, $y]) { + $this->assertSame(0x0000FF, imagecolorat($copy, $x, $y) & 0xFFFFFF, "blue at {$x},{$y}"); + } + } + + public function test_transparency_survives_scaling_too(): void + { + $image = imagecreatetruecolor(64, 8); + imagealphablending($image, false); + imagesavealpha($image, true); + imagefill($image, 0, 0, (int) imagecolorallocatealpha($image, 200, 10, 10, 127)); + imagefilledrectangle($image, 32, 0, 63, 7, (int) imagecolorallocatealpha($image, 10, 10, 200, 0)); + $source = "{$this->dir}/scaled-transparent.png"; + imagepng($image, $source); + $this->weighing($source, 100_000); + + $this->assertSame('made', WebpCopy::make($source, 101, 32)['status']); + + $copy = imagecreatefromwebp($source.'.webp'); + $this->assertNotFalse($copy); + $this->assertSame(127, (imagecolorat($copy, 5, 2) >> 24) & 0x7F); + $this->assertSame(0, (imagecolorat($copy, 25, 2) >> 24) & 0x7F); + } + + public function test_a_palette_png_with_a_transparent_colour_keeps_it(): void + { + $image = imagecreate(32, 8); + $clear = (int) imagecolorallocate($image, 0, 0, 0); + imagecolortransparent($image, $clear); + $red = (int) imagecolorallocate($image, 255, 0, 0); + imagefilledrectangle($image, 16, 0, 31, 7, $red); + $source = "{$this->dir}/palette.png"; + imagepng($image, $source); + $this->weighing($source, 100_000); + + $this->assertSame('made', WebpCopy::make($source, 101)['status']); + + $copy = imagecreatefromwebp($source.'.webp'); + $this->assertNotFalse($copy); + $this->assertSame(127, (imagecolorat($copy, 5, 2) >> 24) & 0x7F); + $this->assertSame(0, (imagecolorat($copy, 25, 2) >> 24) & 0x7F); + $this->assertSame(0xFF0000, imagecolorat($copy, 25, 2) & 0xFFFFFF); + } } diff --git a/packages/admin/tests/database/migrations/2026_01_01_000000_create_admin_fixture_tables.php b/packages/admin/tests/database/migrations/2026_01_01_000000_create_admin_fixture_tables.php index 83d90370..893bbacf 100644 --- a/packages/admin/tests/database/migrations/2026_01_01_000000_create_admin_fixture_tables.php +++ b/packages/admin/tests/database/migrations/2026_01_01_000000_create_admin_fixture_tables.php @@ -66,6 +66,7 @@ public function up(): void Schema::create('articles', function (Blueprint $table): void { $table->id(); $table->foreignId('parent_id')->nullable(); + $table->unsignedBigInteger('section_parent')->nullable(); $table->string('name')->nullable(); $table->string('title')->nullable(); $table->string('code')->nullable(); @@ -118,6 +119,22 @@ public function up(): void $table->timestamps(); }); + Schema::create('bundles', function (Blueprint $table): void { + $table->id(); + $table->string('name'); + $table->timestamps(); + }); + + Schema::create('bundle_post', function (Blueprint $table): void { + $table->foreignId('bundle_id'); + $table->foreignId('post_id'); + }); + + Schema::create('bundle_topic', function (Blueprint $table): void { + $table->foreignId('bundle_id'); + $table->foreignId('topic_id'); + }); + Schema::create('leaflets', function (Blueprint $table): void { $table->id(); $table->string('name'); @@ -129,6 +146,7 @@ public function up(): void $table->id(); $table->string('name'); $table->string('title')->nullable(); + $table->string('code')->nullable(); $table->integer('sort')->default(500); $table->unsignedBigInteger('parent_id')->nullable(); $table->unsignedBigInteger('group_id')->nullable(); @@ -138,7 +156,7 @@ public function up(): void public function down(): void { - foreach (['sections', 'leaflets', 'topics', 'guides', 'chapters', 'api_aisles', 'remarks', 'articles', 'gadget_label', 'gadgets', 'pages', 'notes', 'stories', 'posts'] as $table) { + foreach (['sections', 'bundle_topic', 'bundle_post', 'bundles', 'leaflets', 'topics', 'guides', 'chapters', 'api_aisles', 'remarks', 'articles', 'gadget_label', 'gadgets', 'pages', 'notes', 'stories', 'posts'] as $table) { Schema::dropIfExists($table); } }