Jacek Kowalski
4 hours ago 6b9278a5d57091fce636dbb640b380cfb990db6c
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
<?php
declare(strict_types=1);
 
namespace App\Service;
 
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Filesystem\Filesystem;
 
class CoverStorage {
    public const array EXTENSIONS = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
    ];
 
    public function __construct(
        #[Autowire('%app.cover_originals_dir%')]
        private readonly string           $originalsDir,
        #[Autowire('%app.cover_thumbnails_dir%')]
        private readonly string           $thumbnailsDir,
        private readonly CoverThumbnailer $thumbnailer,
        private readonly Filesystem       $filesystem,
    ) {
    }
 
    /**
     * @param string $contents the image, kept byte for byte as the original
     *
     * @return string the name of the stored cover
     *
     * @throws CoverProcessingException
     */
    public function store(string $contents): string {
        // The extension comes from the detected content, never from the client's file name.
        $extension = self::EXTENSIONS[@getimagesizefromstring($contents)['mime'] ?? ''] ?? null;
 
        if ($extension === null) {
            throw new CoverProcessingException('Unsupported image type.');
        }
 
        $name = bin2hex(random_bytes(16)) . '.' . $extension;
        $this->filesystem->mkdir([$this->originalsDir, $this->thumbnailsDir]);
 
        try {
            $this->thumbnailer->createThumbnails(
                $contents,
                fn(string $size): string => $this->thumbnailPath($name, $size),
            );
            $this->filesystem->dumpFile($this->originalPath($name), $contents);
        } catch (\Throwable $exception) {
            $this->delete($name);
 
            throw $exception;
        }
 
        return $name;
    }
 
    public function delete(string $name): void {
        $this->filesystem->remove([
            $this->originalPath($name),
            ...array_map(
                fn(string $size): string => $this->thumbnailPath($name, $size),
                array_keys(CoverThumbnailer::SIZES),
            ),
        ]);
    }
 
    public function originalPath(string $name): string {
        return $this->originalsDir . '/' . $name;
    }
 
    public function thumbnailPath(string $name, string $size): string {
        return $this->thumbnailsDir . '/' . $name . '.' . $size . '.jpg';
    }
}