diff --git a/framework/Console/Commands/MakeCrudCommand.php b/framework/Console/Commands/MakeCrudCommand.php index da1657f..1795329 100644 --- a/framework/Console/Commands/MakeCrudCommand.php +++ b/framework/Console/Commands/MakeCrudCommand.php @@ -21,9 +21,16 @@ use Rsgrinko\Proton\Support\Str; * bool, date, datetime, email. Подпись — то, что увидит человек в форме и в * сообщении об ошибке; без неё берётся имя поля. * + * Флаг --api добавляет седьмой файл — контроллер в app/Controllers/Api/, + * тот же раздел, только под ключ вместо сеанса: список со страницами и + * поиском, карточка, создание, правка (PATCH меняет только присланные поля) + * и удаление. Формат ответа общий для всего API — success: {"data": …}, + * ошибка: {"error": …}, дальше разбираться не нужно. + * * Маршруты, право и пункт меню команда не дописывает, а печатает готовыми - * кусками: routes/web.php и config/menu.php — код приложения, и лезть в них - * автоматической правкой опаснее, чем скопировать три строки. + * кусками: routes/web.php (и routes/api.php с --api) и config/menu.php — + * код приложения, и лезть в них автоматической правкой опаснее, чем + * скопировать несколько строк. */ final class MakeCrudCommand extends Command { @@ -51,7 +58,7 @@ final class MakeCrudCommand extends Command public function usage(): string { - return 'make:crud <Имя> [--fields="имя:тип:подпись,…"] [--no-soft-delete] [--force]'; + return 'make:crud <Имя> [--fields="имя:тип:подпись,…"] [--no-soft-delete] [--api] [--force]'; } public function run(): int @@ -204,6 +211,7 @@ final class MakeCrudCommand extends Command '{{softSchema}}' => $soft ? "\n \$table->softDeletes();" : '', '{{schema}}' => $this->schema($fields), '{{rules}}' => $this->rules($fields), + '{{updateRules}}' => $this->updateRules($fields), '{{labels}}' => $this->labels($fields), '{{before}}' => $this->before($fields), '{{after}}' => $this->after($fields), @@ -218,7 +226,7 @@ final class MakeCrudCommand extends Command $root = APP_ROOT; - return [ + $plan = [ $root . '/app/Models/' . $names['class'] . '.php' => $this->render('crud/model.stub', $replacements), $root . '/app/Controllers/Web/' . Str::plural($names['class']) . 'Controller.php' => $this->render('crud/controller.stub', $replacements), $root . '/migrations/' . date('YmdHis') . '_create_' . $names['table'] . '.php' => $this->render('crud/migration.stub', $replacements), @@ -227,6 +235,13 @@ final class MakeCrudCommand extends Command $root . '/resources/views/' . $names['views'] . '/show.php' => $this->render('crud/show.stub', $replacements), $root . '/tests/' . Str::plural($names['class']) . 'Test.php' => $this->render('crud/test.stub', $replacements), ]; + + if ($this->hasOption('api')) { + $plan[$root . '/app/Controllers/Api/' . Str::plural($names['class']) . 'Controller.php'] + = $this->render('crud/api-controller.stub', $replacements); + } + + return $plan; } /** @@ -295,6 +310,26 @@ final class MakeCrudCommand extends Command return implode("\n", $lines); } + /** + * Правила для правки через API: PATCH меняет то, что прислали, поэтому + * обязательных полей нет вовсе — даже у первого. + * + * @param array $fields + */ + private function updateRules(array $fields): string + { + $lines = []; + $width = $this->width($fields); + + foreach ($fields as $field) { + $rule = self::TYPES[$field['type']]['rule']; + + $lines[] = " '" . $field['name'] . "'" . str_repeat(' ', $width - mb_strlen($field['name'])) . " => '" . $rule . "',"; + } + + return implode("\n", $lines); + } + /** * @param array $fields */ @@ -502,6 +537,20 @@ HTML; $this->line('3. Пункт меню — config/menu.php:'); $this->line(''); $this->line(' [\'title\' => \'' . $title . '\', \'route\' => \'' . $route . '.index\', \'permission\' => \'' . $route . '.view\'],'); + + if ($this->hasOption('api')) { + $this->line(''); + $this->line('4. Маршруты API — routes/api.php, внутрь группы с \'api\':'); + $this->line(''); + $this->line(' $router->get(\'/' . $route . '\', [' . $class . '::class, \'index\'])->name(\'api.' . $route . '.index\');'); + $this->line(' $router->post(\'/' . $route . '\', [' . $class . '::class, \'store\'])->name(\'api.' . $route . '.store\');'); + $this->line(' $router->get(\'/' . $route . '/{id:\d+}\', [' . $class . '::class, \'show\'])->name(\'api.' . $route . '.show\');'); + $this->line(' $router->patch(\'/' . $route . '/{id:\d+}\', [' . $class . '::class, \'update\'])->name(\'api.' . $route . '.update\');'); + $this->line(' $router->delete(\'/' . $route . '/{id:\d+}\', [' . $class . '::class, \'delete\'])->name(\'api.' . $route . '.delete\');'); + $this->line(''); + $this->line(' use App\Controllers\Api\\' . $class . '; — вверху файла'); + } + $this->line(''); $this->line('Потом: php bin/proton migrate и php bin/proton test'); } diff --git a/stubs/crud/api-controller.stub b/stubs/crud/api-controller.stub new file mode 100644 index 0000000..e71c96b --- /dev/null +++ b/stubs/crud/api-controller.stub @@ -0,0 +1,99 @@ +apply({{class}}::query()) + ->when($request->text('q'), static fn ($query, string $needle) => $query->whereLike('{{first}}', $needle)) + ->orderBy('id', 'desc'); + + return $this->paginated( + $query->paginate($this->page($request), $this->perPage()), + static fn ({{class}} ${{variable}}): array => ${{variable}}->toArray() + ); + } + + public function show(int $id, Scope $scope): Response + { + /** @var {{class}}|null ${{variable}} */ + ${{variable}} = $scope->apply({{class}}::query())->where('id', $id)->first(); + + if (${{variable}} === null) { + return Response::error('{{title}}: запись не найдена', 404); + } + + return $this->data(${{variable}}->toArray()); + } + + public function store(Request $request, Viewer $viewer): Response + { + $data = $this->payload($request, [ +{{rules}} + ]); + + ${{variable}} = new {{class}}($data); + + ${{variable}}->setAttribute('user_id', $viewer->id()); + ${{variable}}->save(); + + Audit::created('{{route}}', ${{variable}}->id(), '{{title}} через API: ' . (string) ${{variable}}->raw('{{first}}')); + + return $this->data(${{variable}}->toArray(), 201); + } + + public function update(Request $request, int $id, Scope $scope): Response + { + /** @var {{class}}|null ${{variable}} */ + ${{variable}} = $scope->apply({{class}}::query())->where('id', $id)->first(); + + if (${{variable}} === null) { + return Response::error('{{title}}: запись не найдена', 404); + } + + $data = $this->payload($request, [ +{{updateRules}} + ]); + + // Пустые поля не затираем: PATCH меняет то, что прислали + ${{variable}}->fill(array_filter($data, static fn (mixed $value): bool => $value !== null)); + ${{variable}}->save(); + + Audit::updated('{{route}}', ${{variable}}->id(), '{{title}} через API: ' . (string) ${{variable}}->raw('{{first}}')); + + return $this->data(${{variable}}->toArray()); + } + + public function delete(int $id, Scope $scope): Response + { + /** @var {{class}}|null ${{variable}} */ + ${{variable}} = $scope->apply({{class}}::query())->where('id', $id)->first(); + + if (${{variable}} === null) { + return Response::error('{{title}}: запись не найдена', 404); + } + + ${{variable}}->delete(); + + Audit::deleted('{{route}}', $id, '{{title}} через API'); + + return $this->data(['deleted' => true]); + } +} diff --git a/tests/MakeCrudTest.php b/tests/MakeCrudTest.php new file mode 100644 index 0000000..8571d2e --- /dev/null +++ b/tests/MakeCrudTest.php @@ -0,0 +1,111 @@ +} + */ +function runMakeCrud(array $args, array $options): array +{ + $created = []; + + $status = (new MakeCrudCommand())->withInput($args, $options, static function (string $line) use (&$created): void { + $line = trim($line); + + if (str_starts_with($line, 'Создано: ')) { + $created[] = mb_substr($line, mb_strlen('Создано: ')); + } + })->run(); + + return ['status' => $status, 'created' => $created]; +} + +/** + * Убирает всё, что команда создала, — генератор пишет в настоящие каталоги + * приложения, а не в песочницу. + * + * @param array $created + */ +function cleanupCrud(array $created): void +{ + foreach ($created as $relative) { + @unlink(APP_ROOT . '/' . $relative); + } +} + +test('make:crud: без --api создаёт только веб-раздел', function (): void { + $result = runMakeCrud(['ZzCrudPlain'], ['fields' => 'title:string:Название']); + + try { + assertSame(0, $result['status']); + assertCount(7, $result['created'], 'модель, контроллер, миграция, три вьюхи и тест'); + + foreach ($result['created'] as $path) { + assertNotContains('Controllers/Api', $path, 'без --api никакого API-контроллера'); + } + } finally { + cleanupCrud($result['created']); + } +}); + +test('make:crud: --api добавляет контроллер под ключ, и он рабочий PHP', function (): void { + $result = runMakeCrud(['ZzCrudSmoke'], [ + 'fields' => 'title:string:Название,total:decimal:Сумма', + 'api' => '1', + ]); + + try { + assertSame(0, $result['status']); + + $apiPath = APP_ROOT . '/app/Controllers/Api/ZzCrudSmokesController.php'; + + assertTrue(in_array('app/Controllers/Api/ZzCrudSmokesController.php', $result['created'], true)); + assertTrue(is_file($apiPath)); + + $code = (string) file_get_contents($apiPath); + + assertContains('namespace App\Controllers\Api;', $code); + assertContains('extends ApiController', $code); + assertContains('function index(', $code); + assertContains('function show(', $code); + assertContains('function store(', $code); + assertContains('function update(', $code); + assertContains('function delete(', $code); + assertContains("whereLike('title'", $code, 'поиск идёт по первому полю'); + + // Не просто похоже на PHP — компилируется по-настоящему + exec('php -l ' . escapeshellarg($apiPath) . ' 2>&1', $lint, $exitCode); + + assertSame(0, $exitCode, implode("\n", $lint)); + } finally { + cleanupCrud($result['created']); + } +}); + +test('make:crud: занятое имя без --force не трогает', function (): void { + $first = runMakeCrud(['ZzCrudTaken'], ['fields' => 'title:string:Название']); + + try { + assertSame(0, $first['status']); + + $second = runMakeCrud(['ZzCrudTaken'], ['fields' => 'title:string:Название']); + + assertSame(1, $second['status'], 'повтор без --force отказывает'); + assertSame([], $second['created'], 'второй прогон ничего не создал'); + } finally { + cleanupCrud($first['created']); + } +});