diff --git a/app/Actions/Tags/CreateTag.php b/app/Actions/Tags/CreateTag.php new file mode 100644 index 00000000..89152292 --- /dev/null +++ b/app/Actions/Tags/CreateTag.php @@ -0,0 +1,34 @@ + + */ +final class CreateTag implements Action +{ + /** + * @param \App\Actions\Tags\CreateTagInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): Tag + { + Assert::isInstanceOf($input, CreateTagInput::class); + + $tag = new Tag(); + $tag->fill([ + 'label' => $input->label, + 'status' => $input->status, + ]); + $tag->saveOrFail(); + + return $tag; + } +} diff --git a/app/Actions/Tags/CreateTagInput.php b/app/Actions/Tags/CreateTagInput.php new file mode 100644 index 00000000..a333f1a1 --- /dev/null +++ b/app/Actions/Tags/CreateTagInput.php @@ -0,0 +1,19 @@ +label), 'Tag label cannot be empty.'); + Assert::maxLength($this->label, 255); + } +} diff --git a/app/Actions/Tags/DeleteTag.php b/app/Actions/Tags/DeleteTag.php new file mode 100644 index 00000000..33b80771 --- /dev/null +++ b/app/Actions/Tags/DeleteTag.php @@ -0,0 +1,26 @@ + + */ +final class DeleteTag implements Action +{ + /** + * @param \App\Actions\Tags\DeleteTagInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): void + { + Assert::isInstanceOf($input, DeleteTagInput::class); + + $input->tag->deleteOrFail(); + } +} diff --git a/app/Actions/Tags/DeleteTagInput.php b/app/Actions/Tags/DeleteTagInput.php new file mode 100644 index 00000000..500d8083 --- /dev/null +++ b/app/Actions/Tags/DeleteTagInput.php @@ -0,0 +1,16 @@ + + */ +final class UpdateTag implements Action +{ + /** + * @param \App\Actions\Tags\UpdateTagInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): Tag + { + Assert::isInstanceOf($input, UpdateTagInput::class); + + $tag = $input->tag; + $tag->fill([ + 'label' => $input->label, + 'status' => $input->status, + ]); + $tag->saveOrFail(); + + return $tag; + } +} diff --git a/app/Actions/Tags/UpdateTagInput.php b/app/Actions/Tags/UpdateTagInput.php new file mode 100644 index 00000000..e5cc0786 --- /dev/null +++ b/app/Actions/Tags/UpdateTagInput.php @@ -0,0 +1,21 @@ +label), 'Tag label cannot be empty.'); + Assert::maxLength($this->label, 255); + } +} diff --git a/app/Contracts/Action.php b/app/Contracts/Action.php new file mode 100644 index 00000000..0d9f1436 --- /dev/null +++ b/app/Contracts/Action.php @@ -0,0 +1,18 @@ + $action + * @param TInput $input + * @return TResult + */ + public function execute(Action $action, ActionInput $input): mixed; +} diff --git a/app/Contracts/ActionInput.php b/app/Contracts/ActionInput.php new file mode 100644 index 00000000..e962b37c --- /dev/null +++ b/app/Contracts/ActionInput.php @@ -0,0 +1,9 @@ +id, + label: $tag->label, + slug: $tag->slug, + order: $tag->order, + status: $tag->status, + ); + } + + #[\Override] + public function getRouteKey(): mixed + { + return $this->id; + } + + #[\Override] + public function getRouteKeyName(): string + { + return 'id'; + } + + #[\Override] + public function resolveRouteBinding($value, $field = null): mixed + { + return null; + } + + #[\Override] + public function resolveChildRouteBinding($childType, $value, $field): mixed + { + return null; + } +} diff --git a/app/Http/Controllers/Bo/TagsController.php b/app/Http/Controllers/Bo/TagsController.php index 93fc2e30..b2ade334 100644 --- a/app/Http/Controllers/Bo/TagsController.php +++ b/app/Http/Controllers/Bo/TagsController.php @@ -4,16 +4,22 @@ declare(strict_types=1); namespace App\Http\Controllers\Bo; +use App\Actions\Tags\CreateTag; +use App\Actions\Tags\CreateTagInput; +use App\Actions\Tags\DeleteTag; +use App\Actions\Tags\DeleteTagInput; +use App\Actions\Tags\UpdateTag; +use App\Actions\Tags\UpdateTagInput; +use App\Contracts\ActionExecutor; use App\Http\Controllers\Controller; use App\Http\Requests\Bo\Tags\StoreTagRequest; use App\Http\Requests\Bo\Tags\UpdateTagRequest; use App\Models\Tag; -use App\Services\DataTableService; +use App\Queries\Tags\GetPaginatedTagsQuery; use App\Traits\Controllers\ChangesModelOrder; use App\Traits\Controllers\TogglesModelStatus; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; -use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class TagsController extends Controller @@ -21,15 +27,16 @@ class TagsController extends Controller use ChangesModelOrder; use TogglesModelStatus; - public function index(DataTableService $dataTable): View + public function __construct( + private readonly ActionExecutor $executor, + ) { + } + + public function index(GetPaginatedTagsQuery $query): View { $this->authorize('viewAny', Tag::class); - $query = Tag::query()->with('products.range'); - - $dataTable->sortQuery(Tag::class, $query); - - $tags = $dataTable->paginateQuery($query); + $tags = $query->execute(); return view('bo.tags.index', compact('tags')); } @@ -41,27 +48,22 @@ class TagsController extends Controller return view('bo.tags.create'); } - public function store(StoreTagRequest $request): RedirectResponse + public function store(StoreTagRequest $request, CreateTag $action): RedirectResponse { $this->authorize('create', Tag::class); - return DB::transaction(function () use ($request) { - $tag = new Tag(); - $tag->fill($request->only( - $tag->getFillable() - )); - if ($tag->saveOrFail()) { - return to_route('bo.tags.edit', $tag) - ->with('success', trans('crud.messages.has_been_created', [ - 'model' => Str::ucfirst(trans_choice('models.classes.tags', 1)), - ])); - } + $tag = $this->executor->execute( + $action, + new CreateTagInput( + label: $request->string('label')->value(), + status: $request->boolean('status'), + ), + ); - return to_route('bo.tags.create') - ->with('error', trans('crud.messages.cannot_be_created', [ - 'model' => Str::ucfirst(trans_choice('models.classes.tags', 1)), - ])); - }); + return to_route('bo.tags.edit', $tag) + ->with('success', trans('crud.messages.has_been_created', [ + 'model' => Str::ucfirst(trans_choice('models.classes.tags', 1)), + ])); } public function edit(Tag $tag): View @@ -71,43 +73,34 @@ class TagsController extends Controller return view('bo.tags.edit', compact('tag')); } - public function update(UpdateTagRequest $request, Tag $tag): RedirectResponse + public function update(UpdateTagRequest $request, Tag $tag, UpdateTag $action): RedirectResponse { $this->authorize('update', $tag); - return DB::transaction(function () use ($request, $tag) { - $tag->fill($request->only( - $tag->getFillable() - )); + $this->executor->execute( + $action, + new UpdateTagInput( + tag: $tag, + label: $request->string('label')->value(), + status: $request->boolean('status'), + ), + ); - if ($tag->saveOrFail()) { - return to_route('bo.tags.edit', $tag) - ->with('success', trans('crud.messages.has_been_updated', [ - 'model' => Str::ucfirst(trans_choice('models.classes.tags', 1)), - ])); - } - - return to_route('bo.tags.edit', $tag) - ->with('error', trans('crud.messages.cannot_be_updated', [ - 'model' => Str::ucfirst(trans_choice('models.classes.tags', 1)), - ])); - }); + return to_route('bo.tags.edit', $tag) + ->with('success', trans('crud.messages.has_been_updated', [ + 'model' => Str::ucfirst(trans_choice('models.classes.tags', 1)), + ])); } - public function destroy(Tag $tag): RedirectResponse + public function destroy(Tag $tag, DeleteTag $action): RedirectResponse { $this->authorize('delete', $tag); - return DB::transaction(function () use ($tag) { - if ($tag->deleteOrFail()) { - return to_route('bo.tags.index') - ->with('warning', trans('crud.messages.has_been_deleted', ['model' => Str::ucfirst(trans_choice('models.classes.tags', 1))])); - } + $this->executor->execute($action, new DeleteTagInput(tag: $tag)); - return to_route('bo.tags.edit', $tag) - ->with('error', trans('crud.messages.cannot_be_deleted', [ - 'model' => Str::ucfirst(trans_choice('models.classes.tags', 1)), - ])); - }); + return to_route('bo.tags.index') + ->with('warning', trans('crud.messages.has_been_deleted', [ + 'model' => Str::ucfirst(trans_choice('models.classes.tags', 1)), + ])); } } diff --git a/app/Policies/Backend/TagPolicy.php b/app/Policies/Backend/TagPolicy.php index 053d6290..fb6683b3 100644 --- a/app/Policies/Backend/TagPolicy.php +++ b/app/Policies/Backend/TagPolicy.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Policies\Backend; +use App\Dto\TagDto; use App\Models\Customer; use App\Models\Tag; use App\Models\User; @@ -20,7 +21,7 @@ class TagPolicy return $user->role->isAtLeastEqualsTo(UserRole::Admin); } - public function view(User | Customer $user, Tag $_): bool + public function view(User | Customer $user, Tag | TagDto $_): bool { if ($user instanceof Customer) { return false; @@ -38,7 +39,7 @@ class TagPolicy return $user->role->isAtLeastEqualsTo(UserRole::Admin); } - public function update(User | Customer $user, Tag $_): bool + public function update(User | Customer $user, Tag | TagDto $_): bool { if ($user instanceof Customer) { return false; @@ -47,7 +48,7 @@ class TagPolicy return $user->role->isAtLeastEqualsTo(UserRole::Admin); } - public function delete(User | Customer $user, Tag $_): bool + public function delete(User | Customer $user, Tag | TagDto $_): bool { if ($user instanceof Customer) { return false; diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 8ce5977c..96e7a9c4 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Providers; +use App\Contracts\ActionExecutor; use App\Contracts\Directories\CustomerDirectory; use App\Contracts\Directories\EmployeeDirectory; use App\Contracts\Directories\OrderDirectory; @@ -18,6 +19,7 @@ use App\Directories\EloquentProductDirectory; use App\Repositories\EloquentEmployeeRepository; use App\Repositories\EloquentOrderRepository; use App\Repositories\EloquentUserRepository; +use App\Services\ActionExecutorService; use Domain\Models\ValueObjects\Pagination; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; @@ -56,6 +58,7 @@ class AppServiceProvider extends ServiceProvider $this->app->bind(EmployeeDirectory::class, EloquentEmployeeDirectory::class); $this->app->bind(OrderDirectory::class, EloquentOrderDirectory::class); $this->app->bind(ProductDirectory::class, EloquentProductDirectory::class); + $this->app->bind(ActionExecutor::class, ActionExecutorService::class); } /** diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 2e12d248..0e695a12 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -4,7 +4,9 @@ declare(strict_types=1); namespace App\Providers; +use App\Dto\TagDto; use App\Models\Customer; +use App\Policies\Backend\TagPolicy; use App\Policies\Frontend\BasketPolicy; use App\Services\CrmService; use Domain\Models\ValueObjects\BasketProduct; @@ -28,6 +30,7 @@ class AuthServiceProvider extends ServiceProvider protected $policies = [ // * Policies Exceptions BasketProduct::class => BasketPolicy::class, + TagDto::class => TagPolicy::class, ]; /** diff --git a/app/Queries/Tags/GetPaginatedTagsQuery.php b/app/Queries/Tags/GetPaginatedTagsQuery.php new file mode 100644 index 00000000..e36e1d2f --- /dev/null +++ b/app/Queries/Tags/GetPaginatedTagsQuery.php @@ -0,0 +1,36 @@ +> + */ +final readonly class GetPaginatedTagsQuery implements Query +{ + public function __construct( + private DataTableService $dataTable, + ) { + } + + /** + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator + */ + public function execute(): LengthAwarePaginator + { + $query = Tag::query()->with('products.range'); + + $this->dataTable->sortQuery(Tag::class, $query); + + $paginator = $this->dataTable->paginateQuery($query); + + return $paginator->through(fn (Tag $tag): TagDto => TagDto::fromModel($tag)); + } +} diff --git a/app/Services/ActionExecutorService.php b/app/Services/ActionExecutorService.php new file mode 100644 index 00000000..f769c2d8 --- /dev/null +++ b/app/Services/ActionExecutorService.php @@ -0,0 +1,59 @@ + $action + * @param TInput $input + * @return TResult + */ + #[\Override] + public function execute(Action $action, ActionInput $input): mixed + { + $actionClass = $action::class; + $actionName = class_basename($actionClass); + + $this->logger?->info("[Action] Executing {$actionName}", [ + 'action' => $actionClass, + 'input' => $input::class, + ]); + + try { + /** @var TResult */ + return DB::transaction(function () use ($action, $input, $actionName): mixed { + $result = $action($input); + + $this->logger?->info("[Action] Succeeded {$actionName}"); + + return $result; + }); + } catch (\Throwable $e) { + $this->logger?->error("[Action] Failed {$actionName}: {$e->getMessage()}", [ + 'action' => $actionClass, + 'input' => $input::class, + 'message' => $e->getMessage(), + 'exception' => $e, + ]); + + throw $e; + } + } +} diff --git a/tests/Architecture/ApplicationTest.php b/tests/Architecture/ApplicationTest.php index b08e8f71..b3a9c995 100644 --- a/tests/Architecture/ApplicationTest.php +++ b/tests/Architecture/ApplicationTest.php @@ -1,6 +1,9 @@ classes() ->toBeFinal() ->toBeReadonly(); + + arch('App Actions implement App\Contracts\Action and Inputs implement ActionInput', function (): void { + $path = __DIR__ . '/../../app/Actions'; + $files = (new Finder())->files()->in($path)->name('*.php'); + + foreach ($files as $file) { + $subPath = $file->getRelativePathname(); + $className = 'App\\Actions\\' . str_replace(['/', '.php'], ['\\', ''], $subPath); + $reflection = new \ReflectionClass($className); + + if (str_ends_with($className, 'Input')) { + expect($reflection->implementsInterface(ActionInput::class)) + ->toBeTrue("{$className} must implement App\Contracts\ActionInput"); + } else { + expect($reflection->implementsInterface(Action::class)) + ->toBeTrue("{$className} must implement App\Contracts\Action"); + } + } + }); + + arch('App Queries implement App\Contracts\Query') + ->expect('App\Queries') + ->toImplement('App\Contracts\Query'); }); diff --git a/tests/Architecture/NamingConventionsTest.php b/tests/Architecture/NamingConventionsTest.php index c30e6a5b..ed7235f2 100644 --- a/tests/Architecture/NamingConventionsTest.php +++ b/tests/Architecture/NamingConventionsTest.php @@ -48,6 +48,10 @@ describe('naming conventions in app', function (): void { arch('services have Service suffix') ->expect("App\Services") ->toHaveSuffix('Service'); + + arch('queries have Query suffix') + ->expect("App\Queries") + ->toHaveSuffix('Query'); }); describe('naming conventions in domain', function (): void { diff --git a/tests/Integration/WithApp/App/Actions/Tags/CreateTagTest.php b/tests/Integration/WithApp/App/Actions/Tags/CreateTagTest.php new file mode 100644 index 00000000..81f6d107 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Tags/CreateTagTest.php @@ -0,0 +1,46 @@ +toBeInstanceOf(Tag::class) + ->and($tag->id)->toBeInt() + ->and($tag->label)->toBe('Offre Spéciale') + ->and($tag->status)->toBeTrue(); + + $fresh = Tag::query()->find($tag->id); + expect($fresh)->not->toBeNull() + ->and($fresh?->label)->toBe('Offre Spéciale') + ->and($fresh?->status)->toBeTrue(); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new CreateTag(); + $invalidInput = new class () implements ActionInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Tags/DeleteTagTest.php b/tests/Integration/WithApp/App/Actions/Tags/DeleteTagTest.php new file mode 100644 index 00000000..480ecc87 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Tags/DeleteTagTest.php @@ -0,0 +1,39 @@ +create(); + $action = new DeleteTag(); + $input = new DeleteTagInput(tag: $tag); + + // WHEN + $action($input); + + // THEN + expect(Tag::query()->find($tag->id))->toBeNull(); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new DeleteTag(); + $invalidInput = new class () implements ActionInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Tags/UpdateTagTest.php b/tests/Integration/WithApp/App/Actions/Tags/UpdateTagTest.php new file mode 100644 index 00000000..78c99082 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Tags/UpdateTagTest.php @@ -0,0 +1,46 @@ +create(['label' => 'Ancien Label', 'status' => false]); + $action = new UpdateTag(); + $input = new UpdateTagInput(tag: $tag, label: 'Nouveau Label', status: true); + + // WHEN + $updatedTag = $action($input); + + // THEN + expect($updatedTag->id)->toBe($tag->id) + ->and($updatedTag->label)->toBe('Nouveau Label') + ->and($updatedTag->status)->toBeTrue(); + + $fresh = Tag::query()->find($tag->id); + expect($fresh)->not->toBeNull() + ->and($fresh?->label)->toBe('Nouveau Label') + ->and($fresh?->status)->toBeTrue(); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new UpdateTag(); + $invalidInput = new class () implements ActionInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php new file mode 100644 index 00000000..a4808de7 --- /dev/null +++ b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php @@ -0,0 +1,86 @@ + */ + public array $logs = []; + + #[\Override] + public function log($level, string | \Stringable $message, array $context = []): void + { + $this->logs[] = (string) $message; + } + }; + + $action = new class () implements Action + { + #[\Override] + public function __invoke(ActionInput $input): string + { + return 'done'; + } + }; + + $input = new class () implements ActionInput + { + }; + $executor = new ActionExecutorService($logger); + + // WHEN + $result = $executor->execute($action, $input); + + // THEN + expect($result)->toBe('done') + ->and($logger->logs)->toHaveCount(2) + ->and($logger->logs[0])->toContain('Executing') + ->and($logger->logs[1])->toContain('Succeeded'); + }); + + it('logs error and rethrows when action fails', function (): void { + // GIVEN + $logger = new class () extends AbstractLogger + { + /** @var array */ + public array $logs = []; + + #[\Override] + public function log($level, string | \Stringable $message, array $context = []): void + { + $this->logs[] = (string) $message; + } + }; + + $action = new class () implements Action + { + #[\Override] + public function __invoke(ActionInput $input): never + { + throw new \RuntimeException('Database failure'); + } + }; + + $input = new class () implements ActionInput + { + }; + $executor = new ActionExecutorService($logger); + + // WHEN + expect(fn () => $executor->execute($action, $input)) + // THEN + ->toThrow(\RuntimeException::class, 'Database failure'); + + expect($logger->logs)->toHaveCount(2) + ->and($logger->logs[0])->toContain('Executing') + ->and($logger->logs[1])->toContain('Failed'); + }); +}); diff --git a/tests/Unit/App/Actions/Tags/CreateTagInputTest.php b/tests/Unit/App/Actions/Tags/CreateTagInputTest.php new file mode 100644 index 00000000..7323ebe1 --- /dev/null +++ b/tests/Unit/App/Actions/Tags/CreateTagInputTest.php @@ -0,0 +1,44 @@ +label)->toBe($label) + ->and($input->status)->toBe($status); + }); +}); + +describe('CreateTagInput validation rules', function (): void { + it('throws when label is empty or whitespace only', function (string $invalidLabel): void { + // GIVEN + $status = true; + $label = $invalidLabel; + + // WHEN + expect(fn () => new CreateTagInput(label: $label, status: $status)) + // THEN + ->toThrow(\InvalidArgumentException::class); + })->with(['', ' ', "\t\n"]); + + it('throws when label exceeds 255 characters', function (): void { + // GIVEN + $status = true; + $label = str_repeat('a', 256); + + // WHEN + expect(fn () => new CreateTagInput(label: $label, status: $status)) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Unit/App/Actions/Tags/DeleteTagInputTest.php b/tests/Unit/App/Actions/Tags/DeleteTagInputTest.php new file mode 100644 index 00000000..6431d855 --- /dev/null +++ b/tests/Unit/App/Actions/Tags/DeleteTagInputTest.php @@ -0,0 +1,19 @@ +tag)->toBe($tag); + }); +}); diff --git a/tests/Unit/App/Actions/Tags/UpdateTagInputTest.php b/tests/Unit/App/Actions/Tags/UpdateTagInputTest.php new file mode 100644 index 00000000..b104861e --- /dev/null +++ b/tests/Unit/App/Actions/Tags/UpdateTagInputTest.php @@ -0,0 +1,49 @@ +tag)->toBe($tag) + ->and($input->label)->toBe($label) + ->and($input->status)->toBe($status); + }); +}); + +describe('UpdateTagInput validation rules', function (): void { + it('throws when label is empty or whitespace only', function (string $invalidLabel): void { + // GIVEN + $tag = new Tag(); + $status = true; + $label = $invalidLabel; + + // WHEN + expect(fn () => new UpdateTagInput(tag: $tag, label: $label, status: $status)) + // THEN + ->toThrow(\InvalidArgumentException::class); + })->with(['', ' ', "\t\n"]); + + it('throws when label exceeds 255 characters', function (): void { + // GIVEN + $tag = new Tag(); + $status = true; + $label = str_repeat('a', 256); + + // WHEN + expect(fn () => new UpdateTagInput(tag: $tag, label: $label, status: $status)) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +});