Factory   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
dl 0
loc 40
ccs 11
cts 11
cp 1
rs 10
c 1
b 0
f 0
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A getByType() 0 17 4
1
<?php
2
3
namespace kalanis\kw_images\Graphics\Format;
4
5
6
use kalanis\kw_images\ImagesException;
7
use kalanis\kw_images\Interfaces\IIMTranslations;
8
use ReflectionClass;
9
use ReflectionException;
10
11
12
/**
13
 * Class Factory
14
 * @package kalanis\kw_images\Graphics\Format
15
 */
16
class Factory
17
{
18
    /** @var array<string, class-string<AFormat>> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string, class-string<AFormat>> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<string, class-string<AFormat>>.
Loading history...
19
    protected array $types = [
20
        'autodetect' => Autodetect::class,
21
        'auto' => Autodetect::class,
22
        'bmp' => Bmp::class,
23
        'gif' => Gif::class,
24
        'jpeg' => Jpeg::class,
25
        'jpg' => Jpeg::class,
26
        'png' => Png::class,
27
        'wbmp' => Wbmp::class,
28
        'webp' => Webp::class,
29
        'avif' => Avif::class,
30
        'xbm' => Xbm::class,
31
    ];
32
33
    /**
34
     * @param string $type
35
     * @param IIMTranslations $lang
36
     * @throws ImagesException
37
     * @return AFormat
38
     */
39 33
    public function getByType(string $type, IIMTranslations $lang): AFormat
40
    {
41 33
        if (!isset($this->types[$type])) {
42 2
            throw new ImagesException($lang->imUnknownType($type), ImagesException::FORMAT_FACTORY_WRONG_FORMAT);
43
        }
44 31
        $className = $this->types[$type];
45
46
        try {
47
            /** @var class-string $className */
48 31
            $ref = new ReflectionClass($className);
49 30
            $instance = $ref->newInstance($lang);
50 30
            if (!$instance instanceof AFormat) {
51 1
                throw new ImagesException($lang->imWrongInstance($className), ImagesException::FORMAT_FACTORY_WRONG_TYPE);
52
            }
53 29
            return $instance;
54 2
        } catch (ReflectionException $ex) {
55 1
            throw new ImagesException($ex->getMessage(), $ex->getCode(), $ex);
56
        }
57
    }
58
}
59