Skip to content

refactor image handling by introducing action classes #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions app/Actions/GetFormattedDateAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace App\Actions;

use Carbon\Carbon;
use DateTime;
use Exception;

class GetFormattedDateAction
{
/**
* @throws Exception
*/
public function __invoke(null|string|Carbon $date): string
{
if ($date === null) {
return '';
}

return is_string($date) ? (new DateTime($date))->format('Y-m-d') : $date->format('Y-m-d');
}
}
25 changes: 25 additions & 0 deletions app/Actions/GetInitialsAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace App\Actions;

class GetInitialsAction
{
public function __invoke(?string $name = ''): string
{
if (empty($name)) {
return '';
}

$parts = explode(' ', $name);

$initials = strtoupper($parts[0][0] ?? '');

if (count($parts) > 1) {
$initials .= strtoupper(end($parts)[0] ?? '');
}

return $initials;
}
}
15 changes: 15 additions & 0 deletions app/Actions/Images/DeleteImageAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace App\Actions\Images;

use Illuminate\Support\Facades\Storage;

class DeleteImageAction
{
public function __invoke(string $path, string $disk = 'public'): void
{
Storage::disk($disk)->delete($path);
}
}
24 changes: 24 additions & 0 deletions app/Actions/Images/ResizeImageAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace App\Actions\Images;

use Illuminate\Http\UploadedFile;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;

class ResizeImageAction
{
public function __invoke(string|TemporaryUploadedFile|UploadedFile $image, int $width = 800, ?int $height = null): string
{
$manager = new ImageManager(new Driver);

return $manager
->read($image)
->scale(width: $width, height: $height)
->encode()
->toString();
}
}
24 changes: 24 additions & 0 deletions app/Actions/Images/StoreUploadedImageAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace App\Actions\Images;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;

class StoreUploadedImageAction
{
public function __invoke(TemporaryUploadedFile|UploadedFile $image, string $destinationFolder, string $disk = 'public', int $width = 800, ?int $height = null): string
{
$name = md5(random_int(1, 10).microtime()).'.jpg';
$img = app(ResizeImageAction::class)($image, $width, $height);

$destinationFolder = rtrim($destinationFolder, DIRECTORY_SEPARATOR);

Storage::disk($disk)->put($destinationFolder.DIRECTORY_SEPARATOR.$name, $img);

return $destinationFolder.DIRECTORY_SEPARATOR.$name;
}
}
19 changes: 4 additions & 15 deletions app/Http/Controllers/Admin/UploadController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@

namespace App\Http\Controllers\Admin;

use App\Actions\Images\StoreUploadedImageAction;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

class UploadController extends Controller
{
Expand All @@ -33,20 +31,11 @@ public function __invoke(Request $request): JsonResponse
return response()->json(['error' => 'Invalid upload'], 400);
}

$originalName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();

$name = Str::slug(date('Y-m-d-h-i-s').'-'.pathinfo($originalName, PATHINFO_FILENAME));
$image = Image::make($file);

$imageString = $image->stream()->__toString();
$name = "$name.$extension";

Storage::disk('images')
->put('uploads/'.$name, $imageString);
/** @var UploadedFile $file */
$image = (new StoreUploadedImageAction)($file, 'images', width: 400);

return response()->json([
'url' => "/images/uploads/$name",
'url' => storage_url($image),
]);
}

Expand Down
7 changes: 3 additions & 4 deletions app/Http/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,11 @@ function get_initials(string $name): string
}

if (! function_exists('create_avatar')) {
function create_avatar(string $name, string $filename, string $path): string
function create_avatar(string $name, string $filename, string $path, string $disk = 'public'): string
{
$avatar = new LasseRafn\InitialAvatarGenerator\InitialAvatar;
$source = $avatar->background('#000')->color('#fff')->name($name)->generate()->stream();
Storage::disk($disk)->makeDirectory($path);

Storage::disk('public')->put($path.$filename, $source);
Avatar::create($name)->save(Storage::disk($disk)->path($path.$filename), 100);

return $path.$filename;
}
Expand Down
37 changes: 9 additions & 28 deletions app/Livewire/Admin/Users/Edit/Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@

namespace App\Livewire\Admin\Users\Edit;

use App\Actions\Images\DeleteImageAction;
use App\Actions\Images\StoreUploadedImageAction;
use App\Models\User;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Intervention\Image\Facades\Image;
use Livewire\Component;
use Livewire\WithFileUploads;

Expand Down Expand Up @@ -68,13 +68,6 @@ protected function rules(): array
];
}

/**
* @var array<string, string>
*/
protected array $messages = [
'name.required' => 'Name is required',
];

/**
* @throws ValidationException
*/
Expand All @@ -83,33 +76,21 @@ public function updated(string $propertyName): void
$this->validateOnly($propertyName);
}

public function update(): void
public function update(DeleteImageAction $deleteImageAction, StoreUploadedImageAction $storeUploadedImageAction): void
{
$this->validate();
$validated = $this->validate();

if (! blank($this->image)) {

if ($this->image !== '' && $this->image !== null) {
if ($this->user->image !== null) {
Storage::disk('public')->delete($this->user->image);
$deleteImageAction($this->user->image);
}

$token = md5(random_int(1, 10).microtime());
$name = $token.'.jpg';
$img = Image::make($this->image)->encode('jpg')->resize(100, null, function (object $constraint) {
/** @phpstan-ignore-next-line */
$constraint->aspectRatio();
});
$img->stream();

// @phpstan-ignore-next-line
Storage::disk('public')->put('users/'.$name, $img);

$this->user->image = 'users/'.$name;
$validated['image'] = $storeUploadedImageAction($this->image, 'users', width: 400);
}

$this->user->name = $this->name;
$this->user->slug = Str::slug($this->name);
$this->user->email = $this->email;
$this->user->save();
$this->user->update($validated);

add_user_log([
'title' => 'updated '.$this->name."'s profile",
Expand Down
41 changes: 32 additions & 9 deletions app/Livewire/Admin/Users/Invite.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,59 @@

namespace App\Livewire\Admin\Users;

use App\Actions\GetInitialsAction;
use App\Mail\Users\SendInviteMail;
use App\Models\Role;
use App\Models\User;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Rule;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\WithPagination;

class Invite extends Component
{
use withPagination;

#[Rule('required', message: 'Please enter a name')]
public string $name = '';

#[Rule('required', as: 'email', message: 'Please enter an email address')]
#[Rule('email', message: 'The email must be a valid email address.')]
#[Rule('unique:users,email')]
public string $email = '';

/**
* @var array<int>
*/
#[Validate('required', 'min:1', as: 'role', message: 'Please select at least one role')]
public array $rolesSelected = [];

/**
* @var array<string, array<int, string>>
*/
protected array $rules = [
'name' => [
'required',
'string',
],
'email' => [
'required',
'string',
'email',
'unique:users,email',
],
'rolesSelected' => [
'required',
'min:1',
],
];

/**
* @var array<string, string>
*/
protected array $messages = [
'name.required' => 'Name is required',
'email.required' => 'Email is required',
'rolesSelected.required' => 'A role is required',
];

/**
* @throws ValidationException
*/
Expand All @@ -49,7 +72,7 @@ public function render(): View
return view('livewire.admin.users.invite', compact('roles'));
}

public function store(): void
public function store(GetInitialsAction $getInitialsAction): void
{
$this->validate();

Expand All @@ -65,7 +88,7 @@ public function store(): void
]);

// generate image
$name = get_initials($user->name);
$name = $getInitialsAction($user->name);
$id = $user->id.'.png';
$path = 'users/';
$imagePath = create_avatar($name, $id, $path);
Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@
"php": "^8.2",
"blade-ui-kit/blade-heroicons": "^2.6",
"guzzlehttp/guzzle": "^7.9.3",
"intervention/image": "^2.7.2",
"intervention/image": "^3.7.2",
"laracasts/flash": "^3.2.4",
"laravel/framework": "^12.12.0",
"laravel/sanctum": "^4.1.1",
"laravel/tinker": "^2.10.1",
"lasserafn/php-initial-avatar-generator": "^4.4",
"laravolt/avatar": "^6.2",
"livewire/livewire": "^3.6.3",
"robthree/twofactorauth": "^1.8.2",
"spatie/laravel-permission": "^6.17.0"
Expand Down
Loading