1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the slince/upload package. |
5
|
|
|
* |
6
|
|
|
* (c) Slince <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Slince\Upload\Filesystem; |
13
|
|
|
|
14
|
|
|
use League\Flysystem\FileExistsException; |
15
|
|
|
use League\Flysystem\Filesystem; |
16
|
|
|
use Symfony\Component\HttpFoundation\File\UploadedFile; |
17
|
|
|
|
18
|
|
|
class Flysystem implements FilesystemInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var Filesystem |
22
|
|
|
*/ |
23
|
|
|
protected $filesystem; |
24
|
|
|
|
25
|
|
|
public function __construct(Filesystem $filesystem) |
26
|
|
|
{ |
27
|
|
|
$this->filesystem = $filesystem; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* {@inheritdoc} |
32
|
|
|
*/ |
33
|
|
|
public function upload($key, UploadedFile $file, $overwrite = false) |
34
|
|
|
{ |
35
|
|
|
try { |
36
|
|
|
$this->uploadToFlysystem($key, $file); |
37
|
|
|
} catch (FileExistsException $exception) { |
38
|
|
|
if (!$overwrite) { |
39
|
|
|
throw new \RuntimeException(sprintf('The file with key "%s" is exists.', $key)); |
40
|
|
|
} |
41
|
|
|
$this->filesystem->delete($key); |
42
|
|
|
$this->uploadToFlysystem($key, $file); |
43
|
|
|
} |
44
|
|
|
@unlink($file->getPathname()); //remove old |
|
|
|
|
45
|
|
|
return true; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param string $key |
50
|
|
|
* @param UploadedFile $file |
51
|
|
|
* @throws FileExistsException |
52
|
|
|
*/ |
53
|
|
|
protected function uploadToFlysystem($key, UploadedFile $file) |
54
|
|
|
{ |
55
|
|
|
if (!$this->filesystem->writeStream($key, fopen($file->getPathname(), 'r'))) { |
56
|
|
|
throw new \RuntimeException('Failed to upload to flysystem'); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
If you suppress an error, we recommend checking for the error condition explicitly: