Passed
Push — v2 ( c484e3...f03721 )
by Daniel
04:34
created

ImageMetadata::__construct()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 21
ccs 0
cts 12
cp 0
crap 20
rs 9.8666
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[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
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentBundle\Dto\File;
15
16
use Silverback\ApiComponentBundle\Exception\FileMissingException;
17
use Silverback\ApiComponentBundle\Exception\FileNotImageException;
18
use function exif_imagetype;
19
20
/**
21
 * @author Daniel West <[email protected]>
22
 */
23
final class ImageMetadata
24
{
25
    private int $width = 0;
26
    private int $height = 0;
27
    private string $url;
28
29
    public function __construct(
30
        string $filePath,
31
        string $url
32
    ) {
33
        if (!file_exists($filePath)) {
34
            throw new FileMissingException(sprintf('The file %s does not exist while constructing %s', $filePath, self::class));
35
        }
36
37
        $this->url = $url;
38
39
        if ('image/svg+xml' === mime_content_type($filePath)) {
40
            $xmlGet = simplexml_load_string(file_get_contents($filePath));
41
            $xmlAttributes = $xmlGet->attributes();
42
            $this->width = (int) $xmlAttributes->width;
43
            $this->height = (int) $xmlAttributes->height;
44
        } else {
45
            if (false === exif_imagetype($filePath)) {
46
                throw new FileNotImageException(sprintf('The file %s is not an image while constructing %s', $filePath, self::class));
47
            }
48
49
            [$this->width, $this->height] = getimagesize($filePath);
50
        }
51
    }
52
53
    public function getWidth(): int
54
    {
55
        return $this->width;
56
    }
57
58
    public function getHeight(): int
59
    {
60
        return $this->height;
61
    }
62
63
    public function getUrl(): string
64
    {
65
        return $this->url;
66
    }
67
}
68