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\Keys;
4
5
6
use kalanis\UploadPerPartes\Exceptions\UploadException;
7
use kalanis\UploadPerPartes\Interfaces\IUPPTranslations;
8
use kalanis\UploadPerPartes\Traits\TLang;
9
use kalanis\UploadPerPartes\Uploader\TargetSearch;
10
use ReflectionClass;
11
use ReflectionException;
12
13
14
/**
15
 * Class Factory
16
 * @package kalanis\UploadPerPartes\Keys
17
 * Select correct type of shared key
18
 */
19
class Factory
20
{
21
    use TLang;
22
23
    const VARIANT_VOLUME = 1;
24
    const VARIANT_RANDOM = 2;
25
    const VARIANT_REDIS = 3;
26
27
    /** @var array<int, class-string<AKey>> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<int, class-string<AKey>> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<int, class-string<AKey>>.
Loading history...
28
    protected static $map = [
29
        self::VARIANT_VOLUME => SimpleVolume::class,
30
        self::VARIANT_RANDOM => Random::class,
31
        self::VARIANT_REDIS => Redis::class,
32
    ];
33
34 14
    public function __construct(?IUPPTranslations $lang = null)
35
    {
36 14
        $this->setUppLang($lang);
37 14
    }
38
39
    /**
40
     * @param TargetSearch $target
41
     * @param int $variant
42
     * @throws UploadException
43
     * @return AKey
44
     */
45 14
    public function getVariant(TargetSearch $target, int $variant): AKey
46
    {
47 14
        if (!isset(static::$map[$variant])) {
48 1
            throw new UploadException($this->getUppLang()->uppKeyVariantNotSet());
49
        }
50 13
        $class = static::$map[$variant];
51
        try {
52 13
            $ref = new ReflectionClass($class);
53 12
            if ($ref->isInstantiable()) {
54 12
                $lib = $ref->newInstance($target, $this->getUppLang());
55 11
                if ($lib instanceof AKey) {
56 10
                    return $lib;
57
                }
58
            }
59 1
            throw new UploadException($this->getUppLang()->uppKeyVariantIsWrong($class));
60 3
        } catch (ReflectionException $ex) {
61 2
            throw new UploadException($ex->getMessage(), $ex->getCode(), $ex);
62
        }
63
    }
64
}
65