Skip to content

Commit

Permalink
Replace Actions by UseCases
Browse files Browse the repository at this point in the history
  • Loading branch information
eliseekn committed Dec 10, 2023
1 parent 192aa9b commit 0c2e040
Show file tree
Hide file tree
Showing 17 changed files with 48 additions and 60 deletions.
6 changes: 3 additions & 3 deletions app/Http/Controllers/Auth/EmailVerificationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

use App\Database\Models\Token;
use App\Enums\TokenDescription;
use App\Http\Actions\User\UpdateAction;
use App\Http\UseCases\User\UpdateUseCase;
use App\Mails\VerificationMail;
use App\Mails\WelcomeMail;
use Core\Routing\Controller;
Expand Down Expand Up @@ -46,7 +46,7 @@ public function notify(): void
$this->render('auth.login');
}

public function verify(UpdateAction $action): void
public function verify(UpdateUseCase $useCase): void
{
if (!$this->request->hasQuery(['email', 'token'])) {
$this->response(__('bad_request'), 400);
Expand All @@ -63,7 +63,7 @@ public function verify(UpdateAction $action): void
}

$token->delete();
$user = $action->handle(['email_verified' => carbon()->toDateTimeString()], $this->request->queries('email'));
$user = $useCase->handle(['email_verified' => carbon()->toDateTimeString()], $this->request->queries('email'));

if (!$user) {
Alert::default(__('account_not_found'))->error();
Expand Down
6 changes: 3 additions & 3 deletions app/Http/Controllers/Auth/ForgotPasswordController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

use App\Database\Models\Token;
use App\Enums\TokenDescription;
use App\Http\Actions\User\UpdateAction;
use App\Http\UseCases\User\UpdateUseCase;
use App\Http\Validators\Auth\LoginValidator;
use App\Mails\TokenMail;
use Core\Routing\Controller;
Expand Down Expand Up @@ -66,10 +66,10 @@ public function reset(): void
$this->render('auth.password.new', ['email' => $this->request->queries('email')]);
}

public function update(UpdateAction $action): void
public function update(UpdateUseCase $useCase): void
{
$validated = $this->validate(new LoginValidator());
$user = $action->handle(['password' => $validated['password']], $validated['email']);
$user = $useCase->handle(['password' => $validated['password']], $validated['email']);

if (!$user) {
Alert::default(__('password_not_reset'))->error();
Expand Down
6 changes: 3 additions & 3 deletions app/Http/Controllers/Auth/RegisterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
namespace App\Http\Controllers\Auth;

use App\Events\UserRegistered\UserRegisteredEvent;
use App\Http\Actions\User\StoreAction;
use App\Http\UseCases\User\StoreUseCase;
use App\Http\Validators\Auth\RegisterValidator;
use Core\Routing\Controller;
use Core\Support\Alert;
Expand All @@ -26,10 +26,10 @@ public function index(): void
$this->redirectUrl(config('app.home'));
}

public function register(StoreAction $action): void
public function register(StoreUseCase $useCase): void
{
$validated = $this->validate(new RegisterValidator());
$user = $action->handle($validated);
$user = $useCase->handle($validated);

if (config('security.auth.email_verification')) {
$this->redirectUrl('/email/notify' , ['email' => $user->get('email')]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@
* @link https://github.com/eliseekn/tinymvc
*/

namespace App\Http\Actions\User;
namespace App\Http\UseCases\User;

use App\Database\Models\User;
use Core\Database\Model;

class StoreAction
class StoreUseCase
{
public function handle(array $data): Model|false
{
$data['password'] = hash_pwd($data['password']);
return User::factory()->create($data);
return (new User())->create($data);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
* @link https://github.com/eliseekn/tinymvc
*/

namespace App\Http\Actions\User;
namespace App\Http\UseCases\User;

use App\Database\Models\User;
use Core\Database\Model;

class UpdateAction
class UpdateUseCase
{
public function handle(array $data, string $email): Model|false
{
Expand Down
2 changes: 1 addition & 1 deletion config/console.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
new \Core\Console\Make\Password(),
new \Core\Console\Make\Helper(),
new \Core\Console\Make\Test(),
new \Core\Console\Make\Actions(),
new \Core\Console\Make\UseCase(),
new \Core\Console\Make\Exception(),
new \Core\Console\Make\Event(),
new \Core\Console\Make\Listener(),
Expand Down
2 changes: 1 addition & 1 deletion config/storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@
'tests' => absolute_path('tests'),
'console' => absolute_path('app.Console'),
'sqlite' => absolute_path('storage.sqlite'),
'actions' => absolute_path('app.Http.Actions'),
'useCases' => absolute_path('app.Http.UseCases'),
'events' => absolute_path('app.Events')
];
15 changes: 8 additions & 7 deletions core/Console/Make/Maker.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace Core\Console\Make;

use Core\Support\Storage;
use Symfony\Component\Console\Output\OutputInterface;

/**
* Create templates from stubs
Expand Down Expand Up @@ -339,26 +340,26 @@ public static function createConsole(string $console, string $command, string $d
return $storage->writeFile($class . '.php', $data);
}

public static function createAction(string $model, string $type, ?string $namespace = null): bool
public static function createUseCase(string $model, string $type, OutputInterface $output, ?string $namespace = null): bool
{
list($name,) = self::generateClass($model, 'action', true, true);
list($type, $class) = self::generateClass($type, 'action', true, true);
list($name,) = self::generateClass($model, 'use_case', true, true);
list($type, $class) = self::generateClass($type, 'use_case', true, true);

$namespace = is_null($namespace) ? ucfirst($name) : $namespace . '\\' . ucfirst($name);
$class = str_replace(['Index', 'Show'], ['GetCollection', 'GetItem'], $class);

if (in_array($type, ['index', 'show', 'store', 'update', 'destroy'])) {
$data = self::stubs()->addPath('actions')->readFile($type . '.stub');
$data = self::stubs()->addPath('useCases')->readFile($type . '.stub');
} else {
$data = self::stubs()->addPath('actions')->readFile('blank.stub');
$data = self::stubs()->addPath('useCases')->readFile('blank.stub');
}

$data = self::addNamespace($data, 'App\Http\Actions', $namespace);
$data = self::addNamespace($data, 'App\Http\UseCases', $namespace);
$data = str_replace('CLASSNAME', $class, $data);
$data = str_replace('$MODELNAME', '$' . self::fixPlural($name, true), $data);
$data = str_replace('MODELNAME', self::fixPlural(ucfirst($name), true), $data);

$storage = Storage::path(config('storage.actions'));
$storage = Storage::path(config('storage.useCases'));
$storage = $storage->addPath(str_replace('\\', '/', $namespace));

return $storage->writeFile($class . '.php', $data);
Expand Down
20 changes: 10 additions & 10 deletions core/Console/Make/Actions.php → core/Console/Make/UseCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@
use Symfony\Component\Console\Output\OutputInterface;

/**
* Create new actions
* Create new use cases
*/
class Actions extends Command
class UseCase extends Command
{
protected static $defaultName = 'make:action';
protected static $defaultName = 'make:use-case';

protected function configure(): void
{
$this->setDescription('Create new action');
$this->setDescription('Create new use case');
$this->addArgument('model', InputArgument::REQUIRED, 'The name of model');
$this->addOption('type', null, InputOption::VALUE_OPTIONAL|InputOption::VALUE_IS_ARRAY, 'Specify action type (index, show, store, update or destroy)');
$this->addOption('namespace', null, InputOption::VALUE_OPTIONAL, 'Specify namespace (base: App\Http\Actions)');
$this->addOption('type', null, InputOption::VALUE_OPTIONAL|InputOption::VALUE_IS_ARRAY, 'Specify use case type (index, show, store, update or destroy)');
$this->addOption('namespace', null, InputOption::VALUE_OPTIONAL, 'Specify namespace (base: App\Http\UseCases)');
}

protected function execute(InputInterface $input, OutputInterface $output): int
Expand All @@ -40,13 +40,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$types = array_map(fn ($type) => strtolower($type), $types);

foreach ($types as $type) {
list(, $class) = Maker::generateClass($type, 'action', true, true);
list(, $class) = Maker::generateClass($type, 'use_case', true, true);
$class = str_replace(['Index', 'Show'], ['GetCollection', 'GetItem'], $class);

if (!Maker::createAction($input->getArgument('model'), $type, $input->getOption('namespace'))) {
$output->writeln('<error>[ERROR] Failed to create action "' . $class . '"</error>');
if (!Maker::createUseCase($input->getArgument('model'), $type, $output, $input->getOption('namespace'))) {
$output->writeln('<error>[ERROR] Failed to create use case "' . $class . '"</error>');
} else {
$output->writeln('<info>[INFO] Action "' . $class . '" has been created</info>');
$output->writeln('<info>[INFO] Use case "' . $class . '" has been created</info>');
}
}

Expand Down
34 changes: 11 additions & 23 deletions core/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,7 @@ public function raw(): array
return $data;
}

private function getSingleFile(string $input, array $allowed_extensions = []): Uploader|null
{
if (empty($_FILES[$input])) {
return null;
}

return new Uploader([
'name' => $_FILES[$input]['name'],
'tmp_name' => $_FILES[$input]['tmp_name'],
'size' => $_FILES[$input]['size'],
'type' => $_FILES[$input]['type'],
'error' => $_FILES[$input]['error']
], $allowed_extensions);
}

private function getMultipleFiles(string $input, array $allowed_extensions = []): array
private function files(string $input, array $allowed_extensions = []): Uploader|array
{
$files = [];

Expand All @@ -78,6 +63,16 @@ private function getMultipleFiles(string $input, array $allowed_extensions = [])

$count = is_array($_FILES[$input]['tmp_name']) ? count($_FILES[$input]['tmp_name']) : 1;

if ($count === 1) {
return new Uploader([
'name' => $_FILES[$input]['name'],
'tmp_name' => $_FILES[$input]['tmp_name'],
'size' => $_FILES[$input]['size'],
'type' => $_FILES[$input]['type'],
'error' => $_FILES[$input]['error']
], $allowed_extensions);
}

for ($i = 0; $i < $count; $i++) {
$files[] = new Uploader([
'name' => $_FILES[$input]['name'][$i],
Expand All @@ -90,13 +85,6 @@ private function getMultipleFiles(string $input, array $allowed_extensions = [])

return $files;
}

public function files(string $input, bool $multiple = false, array $allowed_extensions = []): array|Uploader|null
{
return $multiple
? $this->getMultipleFiles($input, $allowed_extensions)
: $this->getSingleFile($input, $allowed_extensions);
}

public function method(?string $value = null)
{
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ class CLASSNAME
public function handle(int $id): bool
{
$MODELNAME = (new MODELNAME())->find($id);
return !$MODELNAME ? false : $MODELNAME->delete();
return $MODELNAME && $MODELNAME->delete();
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
4 changes: 2 additions & 2 deletions core/Support/Storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ public function createDir(string $pathname = '', bool $recursive = false, int $m

public function writeFile(string $filename, $content, bool $append = false): bool
{
if (!$this->isDir()) {
if (!$this->createDir(recursive: true)) return false;
if (!$this->isDir() && !$this->createDir(recursive: true)) {
return false;
}

$flag = $append ? FILE_APPEND | LOCK_EX : 0;
Expand Down

0 comments on commit 0c2e040

Please sign in to comment.