Passed
Push — master ( b71d8d...e6115e )
by Petr
02:57
created

Factory::getFormat()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 12
nc 7
nop 1
dl 0
loc 17
ccs 12
cts 12
cp 1
crap 5
rs 9.5555
c 1
b 0
f 1
1
<?php
2
3
namespace kalanis\UploadPerPartes\InfoFormat;
4
5
6
use kalanis\UploadPerPartes\Exceptions\UploadException;
7
use kalanis\UploadPerPartes\Interfaces\IInfoFormatting;
8
use kalanis\UploadPerPartes\Interfaces\IUPPTranslations;
9
use kalanis\UploadPerPartes\Traits\TLang;
10
use ReflectionClass;
11
use ReflectionException;
12
13
14
/**
15
 * Class Factory
16
 * @package kalanis\UploadPerPartes\DriveFile
17
 * Drive file format - Factory to get formats
18
 */
19
class Factory
20
{
21
    use TLang;
22
23
    const FORMAT_TEXT = 1;
24
    const FORMAT_JSON = 2;
25
26
    /** @var array<int, class-string<IInfoFormatting>> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<int, class-string<IInfoFormatting>> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<int, class-string<IInfoFormatting>>.
Loading history...
27
    protected static $map = [
28
        self::FORMAT_TEXT => Text::class,
29
        self::FORMAT_JSON => Json::class,
30
    ];
31
32 13
    public function __construct(?IUPPTranslations $lang = null)
33
    {
34 13
        $this->setUppLang($lang);
35 13
    }
36
37
    /**
38
     * @param int $variant
39
     * @throws UploadException
40
     * @return IInfoFormatting
41
     */
42 13
    public function getFormat(int $variant): IInfoFormatting
43
    {
44 13
        if (!isset(static::$map[$variant])) {
45 1
            throw new UploadException($this->getUppLang()->uppDriveFileVariantNotSet());
46
        }
47 12
        $class = static::$map[$variant];
48
        try {
49 12
            $ref = new ReflectionClass($class);
50 11
            if ($ref->isInstantiable()) {
51 11
                $lib = $ref->newInstance();
52 11
                if ($lib instanceof IInfoFormatting) {
53 10
                    return $lib;
54
                }
55
            }
56 1
            throw new UploadException($this->getUppLang()->uppDriveFileVariantIsWrong($class));
57 2
        } catch (ReflectionException $ex) {
58 1
            throw new UploadException($ex->getMessage(), $ex->getCode(), $ex);
59
        }
60
    }
61
}
62