FileUploader::validate()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 8
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * Created by PhpStorm.
6
 * User: Valery Maslov
7
 * Date: 18.08.2018
8
 * Time: 17:29.
9
 */
10
11
namespace App\Service;
12
13
use App\Validator\PhotoRequirements;
14
use Gregwar\Image\Image;
15
use Symfony\Component\Filesystem\Filesystem;
16
use Symfony\Component\HttpFoundation\File\UploadedFile;
17
use Symfony\Component\String\ByteString;
18
use Symfony\Component\Validator\ConstraintViolationListInterface;
19
use Symfony\Component\Validator\Validation;
20
21
final class FileUploader
22
{
23
    private string $targetDirectory;
24
    private Filesystem $fileSystem;
25
26
    public function __construct(string $targetDirectory)
27
    {
28
        $this->targetDirectory = $targetDirectory;
29
        $this->fileSystem = new Filesystem();
30
    }
31
32
    public function validate(UploadedFile $file): ConstraintViolationListInterface
33
    {
34
        $validator = Validation::createValidator();
35
36
        return $validator->validate(
37
            $file,
38
            [
39
                new PhotoRequirements(),
40
            ]
41
        );
42
    }
43
44
    /**
45
     * @throws \Exception
46
     */
47
    public function upload(UploadedFile $file): string
48
    {
49
        $fileName = ByteString::fromRandom(20).'.'.$file->guessExtension();
50
51
        // Full
52
        $file->move($this->targetDirectory.'/full/', $fileName);
53
54
        // Small
55
        Image::open($this->targetDirectory.'/full/'.$fileName)
56
            ->zoomCrop(500, 300, 'transparent', 'center', 'center')
57
            ->save($this->targetDirectory.'/small/'.$fileName);
58
59
        // Medium
60
        Image::open($this->targetDirectory.'/full/'.$fileName)
61
            ->zoomCrop(700, 420, 'transparent', 'center', 'center')
62
            ->save($this->targetDirectory.'/medium/'.$fileName);
63
64
        // Large
65
        Image::open($this->targetDirectory.'/full/'.$fileName)
66
            ->cropResize(1200, 800, 'transparent')
67
            ->save($this->targetDirectory.'/large/'.$fileName);
68
69
        return $fileName;
70
    }
71
72
    public function remove(string $fileName): void
73
    {
74
        $folders = [
75
            '/small/',
76
            '/medium/',
77
            '/full/',
78
            '/large/',
79
        ];
80
81
        foreach ($folders as $folder) {
82
            $this->fileSystem->remove($this->targetDirectory.$folder.$fileName);
83
        }
84
    }
85
}
86