Completed
Pull Request — master (#169)
by Mikołaj
05:25
created

MediaUploader::upload()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 9.1448
c 0
b 0
f 0
cc 5
nc 3
nop 2
1
<?php
2
3
/*
4
 * This file has been created by developers from BitBag.
5
 * Feel free to contact us once you face any issues or want to start
6
 * another great project.
7
 * You can find more information about us on https://bitbag.shop and write us
8
 * an email on [email protected].
9
 */
10
11
declare(strict_types=1);
12
13
namespace BitBag\SyliusCmsPlugin\Uploader;
14
15
use BitBag\SyliusCmsPlugin\Entity\MediaInterface;
16
use Gaufrette\Filesystem;
17
use Symfony\Component\HttpFoundation\File\File;
18
use Webmozart\Assert\Assert;
19
20
final class MediaUploader implements MediaUploaderInterface
21
{
22
    /** @var Filesystem */
23
    private $filesystem;
24
25
    /** @var string */
26
    private $projectDir;
27
28
    public function __construct(Filesystem $filesystem, string $projectDir)
29
    {
30
        $this->filesystem = $filesystem;
31
        $this->projectDir = $projectDir;
32
    }
33
34
    public function upload(MediaInterface $media, string $pathPrefix): void
35
    {
36
        if (!$media->hasFile()) {
37
            return;
38
        }
39
40
        $file = $media->getFile();
41
42
        /** @var File $file */
43
        Assert::isInstanceOf($file, File::class);
44
45
        if (null !== $media->getPath() && $this->has($media->getPath())) {
46
            $this->remove($media->getPath());
47
        }
48
49
        do {
50
            $hash = bin2hex(random_bytes(16));
51
            $path = $this->expandPath($hash . '.' . $file->guessExtension(), $pathPrefix);
52
        } while ($this->filesystem->has($path));
53
54
        $media->setPath($path);
55
        $media->setOriginalPath(sprintf('%s/%s', $this->projectDir, $path));
56
        $media->setMimeType($file->getMimeType());
57
58
        $this->filesystem->write(
59
            $media->getPath(),
60
            file_get_contents($media->getFile()->getPathname())
61
        );
62
    }
63
64
    public function remove(string $path): bool
65
    {
66
        if ($this->filesystem->has($path)) {
67
            return $this->filesystem->delete($path);
68
        }
69
70
        return false;
71
    }
72
73
    private function expandPath(string $path, string $pathPrefix): string
74
    {
75
        return sprintf(
76
            '%s/%s/%s/%s',
77
            $pathPrefix,
78
            substr($path, 0, 2),
79
            substr($path, 2, 2),
80
            substr($path, 4)
81
        );
82
    }
83
84
    private function has(string $path): bool
85
    {
86
        return $this->filesystem->has($path);
87
    }
88
}
89