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

Factory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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