Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
MimeTypesSrcJsDelivr | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
5 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getMimeTypes | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
4 |
1 | <?php |
2 | |
3 | /** |
4 | * @author: Doug Wilbourne (dougwilbourne@gmail.com) |
5 | */ |
6 | |
7 | declare(strict_types=1); |
8 | |
9 | namespace pvc\http\mime; |
10 | |
11 | use pvc\http\err\MimeTypeCdnException; |
12 | use pvc\http\err\MimeTypesJsonDecodingException; |
13 | use pvc\interfaces\http\mime\MimeTypeFactoryInterface; |
14 | use pvc\interfaces\http\mime\MimeTypeInterface; |
15 | use pvc\interfaces\http\mime\MimeTypesSrcInterface; |
16 | |
17 | /** |
18 | * Class MimeTypesSrcJsDelivr |
19 | * @phpstan-type MimeTypeShapeJsDelivr object{'source': string, 'extensions': ?array<string>, 'compressible': bool, 'charset': string} |
20 | */ |
21 | class MimeTypesSrcJsDelivr implements MimeTypesSrcInterface |
22 | { |
23 | /** |
24 | * this cdn is a compilation from apache, iana, and nginx. |
25 | * @see https://www.jsdelivr.com/package/npm/mime-db |
26 | */ |
27 | protected const CDN = 'https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json'; |
28 | |
29 | public function __construct( |
30 | protected MimeTypeFactoryInterface $mimeTypeFactory |
31 | = new MimeTypeFactory() |
32 | ) { |
33 | } |
34 | |
35 | /** |
36 | * getMimeTypes |
37 | * @return array<string, MimeTypeInterface> |
38 | */ |
39 | public function getMimeTypes(): array |
40 | { |
41 | $result = []; |
42 | |
43 | if (!$fileContents = file_get_contents(self::CDN)) { |
44 | // @codeCoverageIgnoreStart |
45 | throw new MimeTypeCdnException(self::CDN); |
46 | // @codeCoverageIgnoreEnd |
47 | } |
48 | |
49 | /** |
50 | * if there was a problem decoding the json, json_decode returns null. |
51 | */ |
52 | |
53 | /** @var null|array<string, MimeTypesSrcJsDelivr> $array */ |
54 | $array = json_decode($fileContents); |
55 | |
56 | if (is_null($array)) { |
57 | // @codeCoverageIgnoreStart |
58 | throw new MimeTypesJsonDecodingException(); |
59 | // @codeCoverageIgnoreEnd |
60 | } |
61 | |
62 | foreach ($array as $mimeTypeName => $obj) { |
63 | $mt = $this->mimeTypeFactory->makeMimeType(); |
64 | $mt->setMimeTypeName($mimeTypeName); |
65 | /** |
66 | * not all mime types have file extensions defined and if there are none defined, then the stdClass object |
67 | * simply does not have that property. |
68 | * @var array<string> $extensions |
69 | */ |
70 | $extensions = $obj->extensions ?? []; |
71 | $mt->setFileExtensions($extensions); |
72 | $result[$mimeTypeName] = $mt; |
73 | } |
74 | return $result; |
75 | } |
76 | } |