Code Coverage
 
Lines
Branches
Paths
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
16 / 16
88.89% covered (warning)
88.89%
8 / 9
66.67% covered (warning)
66.67%
4 / 6
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Base64FileDecoder
100.00% covered (success)
100.00%
16 / 16
88.89% covered (warning)
88.89%
8 / 9
66.67% covered (warning)
66.67%
4 / 6
100.00% covered (success)
100.00%
2 / 2
4.59
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 decodeToTempFile
100.00% covered (success)
100.00%
15 / 15
87.50% covered (warning)
87.50%
7 / 8
60.00% covered (warning)
60.00%
3 / 5
100.00% covered (success)
100.00%
1 / 1
3.58
1<?php
2
3namespace App\Shared\Infrastructure\Service;
4
5/**
6 * @author Wilhelm Zwertvaegher
7 */
8namespace App\Shared\Infrastructure\Service;
9
10use App\Shared\Domain\Model\TempFile;
11use Symfony\Component\Filesystem\Filesystem;
12use Symfony\Component\Mime\MimeTypesInterface;
13
14final readonly class Base64FileDecoder
15{
16    public function __construct(private Filesystem $filesystem, private MimeTypesInterface $mimeTypes)
17    {
18    }
19
20    public function decodeToTempFile(string $base64, string $originalFilename): TempFile
21    {
22
23        $tempPath = $this->filesystem->tempnam(sys_get_temp_dir(), uniqid('temp_', true));
24
25        $binary = base64_decode($base64, true);
26        if ($binary === false) {
27            throw new \RuntimeException('Invalid Base64');
28        }
29
30        $this->filesystem->dumpFile($tempPath, $binary);
31
32        $mime = $this->mimeTypes->guessMimeType($tempPath);
33
34        $expectedExtension = pathinfo($originalFilename, PATHINFO_EXTENSION);
35        $expectedMimes = $this->mimeTypes->getMimeTypes($expectedExtension);
36
37        if (!in_array($mime, $expectedMimes, true)) {
38            throw new \RuntimeException(sprintf(
39                'File contents does not match its extension (%s vs %s)',
40                $mime,
41                $expectedExtension
42            ));
43        }
44
45        return new TempFile($tempPath, $originalFilename, $mime, $expectedExtension);
46    }
47}