PropertySetManager::getInstance()   B
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 34
rs 8.439
cc 5
eloc 21
nc 7
nop 2
1
<?php
2
/**
3
 * @link https://github.com/old-town/old-town-propertyset
4
 * @author  Malofeykin Andrey  <[email protected]>
5
 */
6
namespace OldTown\PropertySet;
7
8
use OldTown\PropertySet\Config\PropertySetConfig;
9
use OldTown\PropertySet\Exception\RuntimeException;
10
use ReflectionClass;
11
12
/**
13
 * Class PropertySetManager
14
 *
15
 * @package OldTown\PropertySet
16
 */
17
class PropertySetManager
18
{
19
    /**
20
     * @param       $name
21
     * @param array $args
22
     *
23
     * @return PropertySetInterface
24
     *
25
     * @throws \OldTown\PropertySet\Exception\RuntimeException
26
     */
27
    public static function getInstance($name, array $args = [])
28
    {
29
        $psc = PropertySetConfig::getConfig();
30
        $class = $psc->getClassName($name);
31
32
        if (null === $class || !class_exists($class)) {
33
            return null;
34
        }
35
36
        $config = $psc->getArgs($name);
37
38
        try {
39
            $r = new ReflectionClass($class);
40
            $ps = $r->newInstance();
41
42
            if (!$ps instanceof PropertySetInterface) {
43
                $errMsg = sprintf(
44
                    'Объект должен реализовывать интерфейс %s',
45
                    PropertySetInterface::class
46
                );
47
                throw new RuntimeException($errMsg);
48
            }
49
50
            $ps->init($config, $args);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $psc->getArgs($name) on line 36 can also be of type null; however, OldTown\PropertySet\PropertySetInterface::init() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
51
52
            return $ps;
53
        } catch (\Exception $e) {
54
            $errMsg = sprintf(
55
                'Ошибка при создание сервиса  %s',
56
                $name
57
            );
58
            throw new RuntimeException($errMsg);
59
        }
60
    }
61
}
62