feat: add image upload service
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BattleForge\Application;
|
||||
|
||||
final class ImageUploadService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly string $userToken,
|
||||
private readonly string $uploadsRoot,
|
||||
) {
|
||||
}
|
||||
|
||||
public function store(string $tempPath, string $declaredMime): string
|
||||
{
|
||||
$validated = ImageValidator::validate($tempPath, $declaredMime);
|
||||
|
||||
$namespace = $this->uploadsRoot . '/' . $this->userToken;
|
||||
if (!is_dir($namespace)) {
|
||||
mkdir($namespace, 0700, true);
|
||||
}
|
||||
|
||||
$hash = bin2hex(random_bytes(16));
|
||||
$filename = $hash . '.' . $validated->extension;
|
||||
$destination = $namespace . '/' . $filename;
|
||||
|
||||
if (!rename($tempPath, $destination)) {
|
||||
throw new InvalidImageException("Could not move upload to {$destination}.");
|
||||
}
|
||||
|
||||
// Lock the file down: the namespace is already 0700; tighten the
|
||||
// file itself to 0600 in case the server's umask is permissive.
|
||||
chmod($destination, 0600);
|
||||
|
||||
return '/assets/' . $this->userToken . '/' . $filename;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user