Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Normalizer/DataUriNormalizer.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[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 Symfony\Component\Serializer\Normalizer;
13
14 use Symfony\Component\HttpFoundation\File\File;
15 use Symfony\Component\Mime\MimeTypeGuesserInterface;
16 use Symfony\Component\Mime\MimeTypes;
17 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
18 use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
19
20 /**
21 * Normalizes an {@see \SplFileInfo} object to a data URI.
22 * Denormalizes a data URI to a {@see \SplFileObject} object.
23 *
24 * @author Kévin Dunglas <[email protected]>
25 */
26 final class DataUriNormalizer implements NormalizerInterface, DenormalizerInterface
27 {
28 private const SUPPORTED_TYPES = [
29 \SplFileInfo::class => true,
30 \SplFileObject::class => true,
31 File::class => true,
32 ];
33
34 private readonly ?MimeTypeGuesserInterface $mimeTypeGuesser;
35
36 public function __construct(?MimeTypeGuesserInterface $mimeTypeGuesser = null)
37 {
38 if (!$mimeTypeGuesser && class_exists(MimeTypes::class)) {
39 $mimeTypeGuesser = MimeTypes::getDefault();
40 }
41
42 $this->mimeTypeGuesser = $mimeTypeGuesser;
43 }
44
45 public function getSupportedTypes(?string $format): array
46 {
47 return self::SUPPORTED_TYPES;
48 }
49
50 public function normalize(mixed $data, ?string $format = null, array $context = []): string
51 {
52 if (!$data instanceof \SplFileInfo) {
53 throw new InvalidArgumentException('The object must be an instance of "\SplFileInfo".');
54 }
55
56 $mimeType = $this->getMimeType($data);
57 $splFileObject = $this->extractSplFileObject($data);
58
59 $splFileData = '';
60
61 $splFileObject->rewind();
62 while (!$splFileObject->eof()) {
63 $splFileData .= $splFileObject->fgets();
64 }
65
66 if ('text' === explode('/', $mimeType, 2)[0]) {
67 return \sprintf('data:%s,%s', $mimeType, rawurlencode($splFileData));
68 }
69
70 return \sprintf('data:%s;base64,%s', $mimeType, base64_encode($splFileData));
71 }
72
73 public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
74 {
75 return $data instanceof \SplFileInfo;
76 }
77
78 /**
79 * Regex adapted from Brian Grinstead code.
80 *
81 * @see https://gist.github.com/bgrins/6194623
82 *
83 * @throws InvalidArgumentException
84 * @throws NotNormalizableValueException
85 */
86 public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): \SplFileInfo
87 {
88 if (null === $data || !preg_match('/^data:([a-z0-9][a-z0-9\!\#\$\&\-\^\_\+\.]{0,126}\/[a-z0-9][a-z0-9\!\#\$\&\-\^\_\+\.]{0,126}(;[a-z0-9\-]+\=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9\!\$\&\\\'\,\(\)\*\+\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i', $data)) {
89 throw NotNormalizableValueException::createForUnexpectedDataType('The provided "data:" URI is not valid.', $data, ['string'], $context['deserialization_path'] ?? null, true);
90 }
91
92 try {
93 switch ($type) {
94 case File::class:
95 if (!class_exists(File::class)) {
96 throw new InvalidArgumentException(\sprintf('Cannot denormalize to a "%s" without the HttpFoundation component installed. Try running "composer require symfony/http-foundation".', File::class));
97 }
98
99 return new File($data, false);
100
101 case 'SplFileObject':
102 case 'SplFileInfo':
103 return new \SplFileObject($data);
104 }
105 } catch (\RuntimeException $exception) {
106 throw NotNormalizableValueException::createForUnexpectedDataType($exception->getMessage(), $data, ['string'], $context['deserialization_path'] ?? null, false, $exception->getCode(), $exception);
107 }
108
109 throw new InvalidArgumentException(\sprintf('The class parameter "%s" is not supported. It must be one of "SplFileInfo", "SplFileObject" or "Symfony\Component\HttpFoundation\File\File".', $type));
110 }
111
112 public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
113 {
114 return isset(self::SUPPORTED_TYPES[$type]);
115 }
116
117 /**
118 * Gets the mime type of the object. Defaults to application/octet-stream.
119 */
120 private function getMimeType(\SplFileInfo $object): string
121 {
122 if ($object instanceof File) {
123 return $object->getMimeType();
124 }
125
126 return $this->mimeTypeGuesser?->guessMimeType($object->getPathname()) ?: 'application/octet-stream';
127 }
128
129 /**
130 * Returns the \SplFileObject instance associated with the given \SplFileInfo instance.
131 */
132 private function extractSplFileObject(\SplFileInfo $object): \SplFileObject
133 {
134 if ($object instanceof \SplFileObject) {
135 return $object;
136 }
137
138 return $object->openFile();
139 }
140 }