60 lines
1.8 KiB
PHP
60 lines
1.8 KiB
PHP
<?php
|
|
namespace Incoviba\Service;
|
|
|
|
use InvalidArgumentException;
|
|
use Psr\Http\Message\UploadedFileInterface;
|
|
use Incoviba\Common\Ideal;
|
|
use Incoviba\Exception\ServiceAction;
|
|
use Incoviba\Service\FileUpload\FileUploadInterface;
|
|
|
|
class FileUpload extends Ideal\Service implements FileUploadInterface
|
|
{
|
|
protected array $uploads = [];
|
|
public function register(FileUploadInterface $fileUpload, string $filetype = 'default'): self
|
|
{
|
|
$this->uploads [$filetype]= $fileUpload;
|
|
return $this;
|
|
}
|
|
/**
|
|
* @param UploadedFileInterface $uploadedFile
|
|
* @return array
|
|
* @throws ServiceAction\Read
|
|
*/
|
|
public function getData(UploadedFileInterface $uploadedFile): array
|
|
{
|
|
try {
|
|
$type = $this->getFileType($uploadedFile);
|
|
} catch (InvalidArgumentException $exception) {
|
|
throw new ServiceAction\Read(__CLASS__, $exception);
|
|
}
|
|
|
|
$uploader = $this->getUploader($type);
|
|
return $uploader->getData($uploadedFile);
|
|
}
|
|
|
|
/**
|
|
* @param UploadedFileInterface $uploadedFile
|
|
* @return string|null
|
|
*/
|
|
protected function getFileType(UploadedFileInterface $uploadedFile): ?string
|
|
{
|
|
$fileType = $uploadedFile->getClientMediaType();
|
|
$typesMap = [
|
|
'text/csv' => 'csv',
|
|
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
|
|
'application/vnd.ms-excel' => 'xls',
|
|
];
|
|
if (!array_key_exists($fileType, $typesMap)) {
|
|
throw new InvalidArgumentException("File type {$fileType} not supported.");
|
|
}
|
|
return $typesMap[$fileType];
|
|
}
|
|
protected function getUploader(string $type): FileUploadInterface
|
|
{
|
|
if (!array_key_exists($type, $this->uploads)) {
|
|
return $this->uploads['default'];
|
|
}
|
|
return $this->uploads[$type];
|
|
}
|
|
}
|