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

Factory   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 22
dl 0
loc 43
ccs 15
cts 15
cp 1
rs 10
c 1
b 0
f 1
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getVariant() 0 17 5
A __construct() 0 3 1
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