-
Notifications
You must be signed in to change notification settings - Fork 176
/
FilesystemOrphanageStorage.php
94 lines (76 loc) · 2.8 KB
/
FilesystemOrphanageStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
declare(strict_types=1);
namespace Oneup\UploaderBundle\Uploader\Storage;
use Oneup\UploaderBundle\Uploader\Chunk\Storage\FilesystemStorage as ChunkStorage;
use Oneup\UploaderBundle\Uploader\File\FileInterface;
use Oneup\UploaderBundle\Uploader\File\FilesystemFile;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class FilesystemOrphanageStorage extends FilesystemStorage implements OrphanageStorageInterface
{
/**
* @var SessionInterface
*/
protected $session;
public function __construct(protected StorageInterface $storage, RequestStack $requestStack, protected ChunkStorage $chunkStorage, protected array $config, protected string $type)
{
parent::__construct($config['directory']);
/** @var Request $request */
$request = $requestStack->getCurrentRequest();
$this->session = $request->getSession();
}
/**
* @param FileInterface|File $file
*
* @return FileInterface|File
*/
public function upload($file, string $name, ?string $path = null)
{
if (!$this->session instanceof SessionInterface || !$this->session->isStarted()) {
throw new \RuntimeException('You need a running session in order to run the Orphanage.');
}
return parent::upload($file, $name, $this->getPath());
}
public function uploadFiles(?array $files = null): array
{
try {
if (null === $files) {
$files = $this->getFiles();
}
$return = [];
foreach ($files as $file) {
$return[] = $this->storage->upload(
new FilesystemFile(new File($file->getPathname())),
ltrim(str_replace($this->getFindPath(), '', (string) $file), '/')
);
}
return $return;
} catch (\Exception $e) {
return [];
}
}
public function getFiles(): Finder
{
$finder = new Finder();
try {
$finder->in($this->getFindPath())->files();
} catch (\InvalidArgumentException $e) {
// catch non-existing directory exception.
// This can happen if getFiles is called and no file has yet been uploaded
// push empty array into the finder so we can emulate no files found
$finder->append([]);
}
return $finder;
}
protected function getPath(): string
{
return sprintf('%s/%s', $this->session->getId(), $this->type);
}
protected function getFindPath(): string
{
return sprintf('%s/%s', $this->config['directory'], $this->getPath());
}
}