Files
myep-team/src/Service/Upload/UploadHandler.php
T

250 lines
8.4 KiB
PHP

<?php
namespace App\Service\Upload;
use App\Entity\Upload;
use App\Model\UploadDto;
use App\Model\UploadSessionDto;
use App\Service\Pdf\Sanitizer;
use Flagception\Manager\FeatureManagerInterface;
use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\RequestStack;
class UploadHandler
{
public const SESSION_KEY = 'myep_upload_session';
public function __construct(
private readonly RequestStack $requestStack,
private readonly OrphanageManager $orphanageManager,
private readonly Sanitizer $sanitizer,
private readonly LoggerInterface $logger,
private readonly FeatureManagerInterface $featureManager,
private readonly string $projectDir,
private readonly string $uploadReplacementFile,
) {
}
public function getUploadSession(): UploadSessionDto
{
$session = $this->requestStack->getSession();
if ($session->has(self::SESSION_KEY) && null !== $session->get(self::SESSION_KEY)) {
/** @var UploadSessionDto $uploadSession */
$uploadSession = $session->get(self::SESSION_KEY);
} else {
$uploadSession = new UploadSessionDto();
$session->set(self::SESSION_KEY, $uploadSession);
}
return $uploadSession;
}
public function destroyUploadSession(): void
{
$this->requestStack->getSession()->remove(self::SESSION_KEY);
}
public function flushUploadSession(UploadSessionDto $uploadSession): void
{
$uploadSession->flushUploads();
$session = $this->requestStack->getSession();
$session->set(self::SESSION_KEY, $uploadSession);
}
public function addUploadToSession(UploadDto $upload): UploadSessionDto
{
$uploadSession = $this->getUploadSession();
$uploadSession->addUpload($upload);
$session = $this->requestStack->getSession();
$session->set(self::SESSION_KEY, $uploadSession);
return $uploadSession;
}
/**
* Drops the uploads of one mapping from the session and writes the trimmed DTO back, so a
* consumer clears only what it has just persisted. destroyUploadSession() below still exists
* for a full reset, but a page with two dropzones must not use it: it would throw away the
* files belonging to the other one.
*/
public function removeUploadSessionUploadsByType(string $type): UploadSessionDto
{
$uploadSession = $this->getUploadSession();
$uploadSession->removeUploadsByType($type);
$session = $this->requestStack->getSession();
$session->set(self::SESSION_KEY, $uploadSession);
return $uploadSession;
}
public function removeUploadFromSession(string $filename): UploadSessionDto
{
$uploadSession = $this->getUploadSession();
$uploadSession->removeUpload($filename);
$session = $this->requestStack->getSession();
$session->set(self::SESSION_KEY, $uploadSession);
return $uploadSession;
}
public function moveUploadSessionFilesFromOrphanage(string $uploader, UploadSessionDto $uploadSession): void
{
$uploadSessionFilenames = $this->getUploadSessionFilenames($uploadSession, true);
$this->moveUploads($uploader, $uploadSessionFilenames);
}
public function moveUploads(string $uploader, array $filenames = []): array
{
$manager = $this->orphanageManager->get($uploader);
if (0 === count($filenames)) {
return $manager->uploadFiles();
}
$finder = $manager->getFiles();
try {
$files = iterator_to_array($finder->files()->name($filenames));
} catch (\Exception $e) {
$this->logger->warning('Failed to retrieve orphanage files', [
'uploader' => $uploader,
'filenames' => $filenames,
'exception' => $e->getMessage(),
]);
return [];
}
if (0 === count($files)) {
return [];
}
return $manager->uploadFiles($files);
}
/**
* Where a file dropped in this session waits in the orphanage, or null once it is gone -
* moved on by a save, or cleared away after the orphanage maxage (oneup_uploader.yaml).
*/
public function findOrphanageFilepath(string $uploader, string $filename): ?string
{
try {
foreach ($this->orphanageManager->get($uploader)->getFiles()->files()->name($filename) as $file) {
return $file->getPathname();
}
} catch (\Exception $e) {
// the session's orphanage directory does not exist until its first upload
}
return null;
}
public function removeUploadedFile(Upload $upload): void
{
$filepath = $this->getUploadFilepath($upload);
$filesystem = new Filesystem();
try {
$filesystem->remove($filepath);
} catch (IOException $e) {
$this->logger->error($e->getMessage());
}
}
public function getUploadSessionFilenames(UploadSessionDto $uploadSession, bool $basename = false): array
{
$uploadSessionId = $uploadSession->getUid();
return $uploadSession
->getUploads()
->map(function (UploadDto $uploadDto) use ($basename, $uploadSessionId) {
return true === $basename ? $uploadDto->getFilename() : $this->getTempUploadFilepath($uploadDto, $uploadSessionId);
})
->toArray()
;
}
public function getUploadFilepath(Upload $upload, bool $absolute = true): string
{
$folder = substr($upload->getFilename(), 0, 1);
$relativePath = sprintf('uploads/%s/%s/%s', $upload->getType(), $folder, $upload->getFilename());
return true === $absolute ? sprintf('%s/%s', $this->projectDir, $relativePath) : $relativePath;
}
/**
* Returns the upload file path, falling back to the stand-in document when the real file is
* missing and the upload_replacement feature is on.
*
* Environments other than prod run on anonymized copies of the production database but never
* carry over the uploaded files, so most rows point at a file that is not there. The stand-in
* fills exactly that gap: a file that is present - one uploaded while testing - is always
* served as it is, which is what keeps the upload flow exercisable.
*
* Use this for read-only access (downloads, email attachments); getUploadFilepath() stays the
* real location and is what writes target.
*/
public function getResolvedUploadFilepath(Upload $upload): string
{
$originalPath = $this->getUploadFilepath($upload);
if (true === file_exists($originalPath)) {
return $originalPath;
}
if (false === $this->featureManager->isActive('upload_replacement')) {
return $originalPath;
}
$replacementPath = sprintf('%s/%s', $this->projectDir, $this->uploadReplacementFile);
if (false === file_exists($replacementPath)) {
throw new \RuntimeException('Upload replacement file not found at '.$replacementPath);
}
$this->logger->info('Serving upload replacement', [
'file_id' => $upload->getId(),
'missing_path' => $originalPath,
]);
return $replacementPath;
}
public function getTempUploadFilepath(UploadDto $uploadDto, string $uploadSessionId): string
{
$tempUploadDir = $this->getTempUploadDir($uploadSessionId);
return sprintf('%s/%s', $tempUploadDir, $uploadDto->getFilename());
}
public function getTempUploadDir(string $uploadSessionId): string
{
return sprintf('%s/uploads/temp/%s', $this->projectDir, $uploadSessionId);
}
public function ensurePdf(Upload $upload): void
{
try {
$filepath = $this->getUploadFilepath($upload);
$sanitizedFilepath = $this->sanitizer->sanitizeFile($filepath);
if ($filepath !== $sanitizedFilepath) {
$upload
->setFilename(basename($sanitizedFilepath))
->setMimeType('application/pdf')
;
}
} catch (\InvalidArgumentException $e) {
$this->logger->error($e->getMessage());
}
}
}