Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
MimeTypesSrcJsDelivr
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
2 / 2
5
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
1
 getMimeTypes
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3/**
4 * @author: Doug Wilbourne (dougwilbourne@gmail.com)
5 */
6
7declare(strict_types=1);
8
9namespace pvc\http\mime;
10
11use pvc\http\err\MimeTypeCdnException;
12use pvc\http\err\MimeTypesJsonDecodingException;
13use pvc\interfaces\http\mime\MimeTypeFactoryInterface;
14use pvc\interfaces\http\mime\MimeTypeInterface;
15use 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 */
21class 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(protected MimeTypeFactoryInterface $mimeTypeFactory)
30    {
31    }
32
33    /**
34     * getMimeTypes
35     * @return array<string, MimeTypeInterface>
36     */
37    public function getMimeTypes(): array
38    {
39        $result = [];
40
41        if (!$fileContents = file_get_contents(self::CDN)) {
42            // @codeCoverageIgnoreStart
43            throw new MimeTypeCdnException(self::CDN);
44            // @codeCoverageIgnoreEnd
45        }
46
47        /**
48         * if there was a problem decoding the json, json_decode returns null.
49         */
50
51        /** @var null|array<string, MimeTypesSrcJsDelivr> $array */
52        $array = json_decode($fileContents);
53
54        if (is_null($array)) {
55            // @codeCoverageIgnoreStart
56            throw new MimeTypesJsonDecodingException();
57            // @codeCoverageIgnoreEnd
58        }
59
60        foreach ($array as $mimeTypeName => $obj) {
61            $mt = $this->mimeTypeFactory->makeMimeType();
62            $mt->setMimeTypeName($mimeTypeName);
63            /**
64             * not all mime types have file extensions defined and if there are none defined, then the stdClass object
65             * simply does not have that property.
66             * @var array<string> $extensions
67             */
68            $extensions = $obj->extensions ?? [];
69            $mt->setFileExtensions($extensions);
70            $result[$mimeTypeName] = $mt;
71        }
72        return $result;
73    }
74}