1.0.2 release

This commit is contained in:
Jérémy Munsch 2026-11-04 08:14:16 +01:00
commit bbcc9c6353
Signed by: forge-joniko
GPG key ID: D7EFE2F5CB6CC0E4
8 changed files with 182 additions and 115 deletions

View file

@ -9,5 +9,7 @@ return [
'local',
],
'prefix' => env('STORAGE_SERVICE_PREFIX', 'media'),
'allowedExtensions' => ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt', 'doc', 'docx', 'csv', 'mp4', 'webm'],
];

View file

@ -17,6 +17,8 @@ final class StorageServiceConfig
/** @var DiskName[] */
private array $eligibles;
private ?string $prefix = null;
/**
* @param string[] $eligibleDisks
* @param object{'disk':string,'driver':string}[] $laravelExistingDisks
@ -26,8 +28,61 @@ final class StorageServiceConfig
private string $defaultDisk,
private array $eligibleDisks,
private array $laravelExistingDisks,
private array $allowedExtensions
private array $allowedExtensions,
?string $prefix = null
) {
$this->validateAndSetDisks();
$this->validateExtensions();
$this->prefix = $this->parsePrefix($prefix);
}
private function parsePrefix(?string $prefix): ?string
{
if ($prefix === null) {
return null;
}
$trimmed = mb_trim($prefix);
$clean = trim($trimmed, '/');
if ($clean === '') {
return null;
}
if (str_contains($clean, '..')) {
throw new UnexpectedStorageException('Prefix must not contain "..".');
}
if (str_contains($clean, '\\')) {
throw new UnexpectedStorageException('Prefix must not contain "\\".');
}
if (str_contains($clean, '//')) {
throw new UnexpectedStorageException('Prefix must not contain "//".');
}
return $clean;
}
private function validateExtensions(): void
{
if (empty($this->allowedExtensions)) {
throw new UnexpectedStorageException('Allowed extensions cannot be empty');
}
foreach ($this->allowedExtensions as $extension) {
if (! is_string($extension) || empty(mb_trim($extension))) {
throw new UnexpectedStorageException("Allowed extension {$extension} is not valid");
}
if (in_array(strtolower(ltrim($extension, '.')), self::UNSUPPORTED_EXTENSIONS, true)) {
throw new UnexpectedStorageException("Extension '{$extension}' is forbidden: XML/SVG sanitization is currently not supported.");
}
}
}
private function validateAndSetDisks(): void
{
if (Utils::diskExists($this->defaultDisk) === false) {
throw new UnexpectedStorageException('Default disk does not exist');
}
@ -85,20 +140,11 @@ final class StorageServiceConfig
$disk->disk,
$disk->driver
), $intersectWithDrivers);
}
if (empty($this->allowedExtensions)) {
throw new UnexpectedStorageException('Allowed extensions cannot be empty');
}
foreach ($this->allowedExtensions as $extension) {
if (! is_string($extension) || empty(mb_trim($extension))) {
throw new UnexpectedStorageException("Allowed extension {$extension} is not valid");
}
if (in_array(strtolower(ltrim($extension, '.')), self::UNSUPPORTED_EXTENSIONS, true)) {
throw new UnexpectedStorageException("Extension '{$extension}' is forbidden: XML/SVG sanitization is currently not supported.");
}
}
public function getPrefix(): ?string
{
return $this->prefix;
}
public function getDefaultDisk(): DiskName

View file

@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Uwil\Storage\Lib\PathGenerators;
use Illuminate\Support\Str;
use Uwil\Storage\Config\StorageServiceConfig;
use Uwil\Storage\Contracts\PathGenerator;
use Uwil\Storage\Lib\ValueObjects\DiskName;
use Uwil\Storage\Lib\ValueObjects\SanitizedFile;
@ -12,8 +13,13 @@ use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
class DateHashPathGenerator implements PathGenerator
{
public function __construct(
private ?StorageServiceConfig $config = null
) {
}
#[\Override]
public function generate(DiskName $disk, SanitizedFile $file, ?string $directory = null): StorageFilePath
public function generate(DiskName $disk, SanitizedFile $file): StorageFilePath
{
$extension = pathinfo($file->sanitizedName, PATHINFO_EXTENSION);
$filename = pathinfo($file->sanitizedName, PATHINFO_FILENAME);
@ -30,7 +36,7 @@ class DateHashPathGenerator implements PathGenerator
);
$pathSegments = array_filter([
$directory ? trim($directory, '/') : null,
$this->config?->getPrefix(),
gmdate('Y'),
gmdate('m'),
gmdate('d'),

View file

@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Uwil\Storage\Lib\PathGenerators;
use Illuminate\Support\Str;
use Uwil\Storage\Config\StorageServiceConfig;
use Uwil\Storage\Contracts\PathGenerator;
use Uwil\Storage\Lib\ValueObjects\DiskName;
use Uwil\Storage\Lib\ValueObjects\SanitizedFile;
@ -12,8 +13,13 @@ use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
class UuidPathGenerator implements PathGenerator
{
public function __construct(
private ?StorageServiceConfig $config = null
) {
}
#[\Override]
public function generate(DiskName $disk, SanitizedFile $file, ?string $directory = null): StorageFilePath
public function generate(DiskName $disk, SanitizedFile $file): StorageFilePath
{
$extension = pathinfo($file->sanitizedName, PATHINFO_EXTENSION);
$uuid = Str::uuid()->toString();
@ -21,7 +27,7 @@ class UuidPathGenerator implements PathGenerator
$finalFilename = $uuid . (! empty($extension) ? '.' . $extension : '');
$pathSegments = array_filter([
$directory ? trim($directory, '/') : null,
$this->config?->getPrefix(),
$finalFilename,
]);

View file

@ -51,6 +51,9 @@ class StorageServiceProvider extends ServiceProvider
fn ($ext) => is_string($ext)
);
$rawPrefix = Config::get('storage-service.prefix');
$prefix = is_string($rawPrefix) ? $rawPrefix : null;
$disks = [];
foreach ($rawDisks as $name => $diskConf) {
$disks[] = (object) [
@ -63,7 +66,8 @@ class StorageServiceProvider extends ServiceProvider
Config::string('storage-service.default', 'local'),
$eligibleDisks,
$disks,
$allowedExtensions
$allowedExtensions,
$prefix
);
}
);
@ -71,6 +75,20 @@ class StorageServiceProvider extends ServiceProvider
$this->app->bind(MimeTypeChecker::class, MimeTypeCheckerImpl::class);
$this->app->bind(FileSanitizer::class, FileSanitizerImpl::class);
$this->app->bind(
DateHashPathGenerator::class,
fn (Application $app) => new DateHashPathGenerator(
$app->make(StorageServiceConfig::class)
)
);
$this->app->bind(
UuidPathGenerator::class,
fn (Application $app) => new UuidPathGenerator(
$app->make(StorageServiceConfig::class)
)
);
$this->app->bind(
StorageGateway::class,
fn (Application $app) => new StorageGatewayImpl(

View file

@ -354,3 +354,64 @@ describe('StorageServiceConfig isExtensionAllowed', function (): void {
'.svg' => '.svg',
]);
});
describe('StorageServiceConfig prefix validation and retrieval', function (): void {
it('returns null when prefix is omitted or null', function (?string $prefix): void {
// GIVEN
$config = new StorageServiceConfig(
defaultDisk: 'local',
eligibleDisks: ['local'],
laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']],
allowedExtensions: ['pdf'],
prefix: $prefix
);
// THEN
expect($config->getPrefix())->toBeNull();
})->with([
'null' => null,
'empty' => '',
'spaces' => ' ',
'slashes' => '///',
]);
it('trims leading and trailing slashes and spaces from prefix', function (string $input, string $expected): void {
// GIVEN
$config = new StorageServiceConfig(
defaultDisk: 'local',
eligibleDisks: ['local'],
laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']],
allowedExtensions: ['pdf'],
prefix: $input
);
// THEN
expect($config->getPrefix())->toBe($expected);
})->with([
'simple' => ['media', 'media'],
'leading slash' => ['/media', 'media'],
'trailing slash' => ['media/', 'media'],
'both slashes' => ['/media/', 'media'],
'nested' => ['/uploads/images/', 'uploads/images'],
'with spaces' => [' media ', 'media'],
]);
it('throws exception if prefix contains invalid sequences', function (string $invalidPrefix): void {
// GIVEN
$action = fn () => new StorageServiceConfig(
defaultDisk: 'local',
eligibleDisks: ['local'],
laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']],
allowedExtensions: ['pdf'],
prefix: $invalidPrefix
);
// THEN
expect($action)->toThrow(UnexpectedStorageException::class);
})->with([
'dot dot' => '../media',
'nested dot dot' => 'media/../sub',
'backslash' => 'media\\sub',
'double slash' => 'media//sub',
]);
});

View file

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Uwil\Storage\Tests\Unit\Lib\PathGenerators;
use Uwil\Storage\Config\StorageServiceConfig;
use Uwil\Storage\Lib\PathGenerators\DateHashPathGenerator;
use Uwil\Storage\Lib\ValueObjects\DiskName;
use Uwil\Storage\Lib\ValueObjects\FileStream;
@ -91,20 +92,26 @@ describe('DateHashPathGenerator generation without directory', function (): void
});
});
describe('DateHashPathGenerator generation with directory', function (): void {
it('prepends the given directory to the path', function (): void {
describe('DateHashPathGenerator generation with prefix', function (): void {
it('prepends the configured prefix to the path', function (): void {
// GIVEN
$generator = new DateHashPathGenerator();
$config = new StorageServiceConfig(
defaultDisk: 'local',
eligibleDisks: ['local'],
laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']],
allowedExtensions: ['png'],
prefix: 'avatars/users'
);
$generator = new DateHashPathGenerator($config);
$disk = new DiskName('local', 'local');
$sanitizedFile = new SanitizedFile(
originalName: 'avatar.png',
sanitizedName: 'avatar.png',
contents: FileStream::fromString('image data')
);
$directory = 'avatars/users';
// WHEN
$result = $generator->generate($disk, $sanitizedFile, $directory);
$result = $generator->generate($disk, $sanitizedFile);
// THEN
$expectedHash = substr(hash('sha256', 'avatar.png'), 0, 2);
@ -117,49 +124,6 @@ describe('DateHashPathGenerator generation with directory', function (): void {
);
expect($result->value)->toMatch($pattern);
});
it('trims leading and trailing slashes from the directory', function (string $directory): void {
// GIVEN
$generator = new DateHashPathGenerator();
$disk = new DiskName('local', 'local');
$sanitizedFile = new SanitizedFile(
originalName: 'file.txt',
sanitizedName: 'file.txt',
contents: FileStream::fromString('txt')
);
// WHEN
$result = $generator->generate($disk, $sanitizedFile, $directory);
// THEN
expect($result->value)->toStartWith('uploads/archive/');
})->with([
'leading slash' => '/uploads/archive',
'trailing slash' => 'uploads/archive/',
'both slashes' => '/uploads/archive/',
'multiple outer slashes' => '///uploads/archive///',
]);
it('ignores empty or slash-only directory', function (string $directory): void {
// GIVEN
$generator = new DateHashPathGenerator();
$disk = new DiskName('local', 'local');
$sanitizedFile = new SanitizedFile(
originalName: 'report.pdf',
sanitizedName: 'report.pdf',
contents: FileStream::fromString('pdf')
);
// WHEN
$result = $generator->generate($disk, $sanitizedFile, $directory);
// THEN
expect($result->value)->toStartWith(gmdate('Y') . '/');
})->with([
'empty string' => '',
'single slash' => '/',
'multi slashes' => '///',
]);
});
describe('DateHashPathGenerator filename slugging', function (): void {

View file

@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Uwil\Storage\Tests\Unit\Lib\PathGenerators;
use Illuminate\Support\Str;
use Uwil\Storage\Config\StorageServiceConfig;
use Uwil\Storage\Lib\PathGenerators\UuidPathGenerator;
use Uwil\Storage\Lib\ValueObjects\DiskName;
use Uwil\Storage\Lib\ValueObjects\FileStream;
@ -74,67 +75,30 @@ describe('UuidPathGenerator generation without directory', function (): void {
});
});
describe('UuidPathGenerator generation with directory', function (): void {
it('prepends the given directory to the generated UUID filename', function (): void {
describe('UuidPathGenerator generation with prefix', function (): void {
it('prepends the configured prefix to the generated UUID filename', function (): void {
// GIVEN
$generator = new UuidPathGenerator();
$config = new StorageServiceConfig(
defaultDisk: 'local',
eligibleDisks: ['local'],
laravelExistingDisks: [(object) ['disk' => 'local', 'driver' => 'local']],
allowedExtensions: ['pdf'],
prefix: 'billing/invoices'
);
$generator = new UuidPathGenerator($config);
$disk = new DiskName('local', 'local');
$sanitizedFile = new SanitizedFile(
originalName: 'invoice.pdf',
sanitizedName: 'invoice.pdf',
contents: FileStream::fromString('PDF DATA')
);
$directory = 'billing/invoices';
// WHEN
$result = $generator->generate($disk, $sanitizedFile, $directory);
$result = $generator->generate($disk, $sanitizedFile);
// THEN
expect($result)->toBeInstanceOf(StorageFilePath::class)
->and($result->value)->toStartWith('billing/invoices/')
->and($result->value)->toMatch('#^billing/invoices/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.pdf$#');
});
it('trims leading and trailing slashes from the directory', function (string $directory): void {
// GIVEN
$generator = new UuidPathGenerator();
$disk = new DiskName('local', 'local');
$sanitizedFile = new SanitizedFile(
originalName: 'file.txt',
sanitizedName: 'file.txt',
contents: FileStream::fromString('text')
);
// WHEN
$result = $generator->generate($disk, $sanitizedFile, $directory);
// THEN
expect($result->value)->toStartWith('custom/path/');
})->with([
'leading slash' => '/custom/path',
'trailing slash' => 'custom/path/',
'both slashes' => '/custom/path/',
'multiple outer slashes' => '///custom/path///',
]);
it('ignores empty or slash-only directory', function (string $directory): void {
// GIVEN
$generator = new UuidPathGenerator();
$disk = new DiskName('local', 'local');
$sanitizedFile = new SanitizedFile(
originalName: 'file.txt',
sanitizedName: 'file.txt',
contents: FileStream::fromString('text')
);
// WHEN
$result = $generator->generate($disk, $sanitizedFile, $directory);
// THEN
expect($result->value)->toMatch('#^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$#');
})->with([
'empty string' => '',
'single slash' => '/',
'multi slashes' => '///',
]);
});