Completed
Push — master ( c264d0...44985a )
by Taosikai
12:57
created

Flysystem::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
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
}