opnform/app/Service/Storage/StorageFileNameParser.php

75 lines
1.9 KiB
PHP
Raw Permalink Normal View History

2022-09-20 19:59:52 +00:00
<?php
namespace App\Service\Storage;
use Illuminate\Support\Str;
/**
* Used
* File can have 2 formats:
* - file_name-{uuid}.{ext}
* - {uuid}
*/
class StorageFileNameParser
{
public ?string $uuid = null;
2024-02-23 10:54:12 +00:00
2022-09-20 19:59:52 +00:00
public ?string $fileName = null;
2024-02-23 10:54:12 +00:00
2022-09-20 19:59:52 +00:00
public ?string $extension = null;
public function __construct(string $fileName)
{
$this->parseFileName($fileName);
}
/**
* If we have parsed a file name and an extension, we keep the same and append uuid to avoid collisions
* Otherwise we just return the uuid
*/
public function getMovedFileName(): ?string
{
if ($this->fileName && $this->extension) {
2022-11-15 10:07:07 +00:00
$fileName = substr($this->fileName, 0, 50).'_'.$this->uuid.'.'.$this->extension;
$fileName = preg_replace('#\p{C}+#u', '', $fileName); // avoid CorruptedPathDetected exceptions
2024-02-23 10:54:12 +00:00
2022-11-15 10:07:07 +00:00
return mb_convert_encoding($fileName, 'UTF-8', 'UTF-8');
2022-09-20 19:59:52 +00:00
}
2024-02-23 10:54:12 +00:00
2022-09-20 19:59:52 +00:00
return $this->uuid;
}
private function parseFileName(string $fileName)
{
if (Str::isUuid($fileName)) {
$this->uuid = $fileName;
2024-02-23 10:54:12 +00:00
2022-09-20 19:59:52 +00:00
return;
}
2024-02-23 10:54:12 +00:00
if (! str_contains($fileName, '_')) {
2022-09-20 19:59:52 +00:00
return;
}
$candidateString = substr($fileName, strrpos($fileName, '_') + 1);
2024-02-23 10:54:12 +00:00
if (! str_contains($candidateString, '.')
|| ! Str::isUuid(substr($candidateString, 0, strpos($candidateString, '.')))) {
2022-09-20 19:59:52 +00:00
return;
}
try {
$this->uuid = substr($candidateString, 0, strpos($candidateString, '.'));
$this->fileName = substr($fileName, 0, strrpos($fileName, '_'));
// get everything after the last dot
$this->extension = substr($candidateString, strrpos($candidateString, '.') + 1);
} catch (\Exception $e) {
return;
}
}
public static function parse(string $fileName): self
{
return new self($fileName);
}
}