Passed
Push — master ( bfe5be...dad09b )
by Sergei
14:45 queued 12:02
created

WidgetFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 80%

Importance

Changes 5
Bugs 0 Features 1
Metric Value
eloc 7
c 5
b 0
f 1
dl 0
loc 48
ccs 8
cts 10
cp 0.8
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A initialize() 0 6 1
A createWidget() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Widget;
6
7
use Psr\Container\ContainerInterface;
8
use Yiisoft\Definitions\Exception\CircularReferenceException;
9
use Yiisoft\Definitions\Exception\InvalidConfigException;
10
use Yiisoft\Definitions\Exception\NotInstantiableException;
11
use Yiisoft\Factory\NotFoundException;
12
use Yiisoft\Factory\Factory;
13
14
/**
15
 * WidgetFactory creates an instance of the widget based on the specified configuration
16
 * {@see WidgetFactory::createWidget()}. Before creating a widget, you need to initialize
17
 * the WidgetFactory with {@see WidgetFactory::initialize()}.
18
 */
19
final class WidgetFactory
20
{
21
    private static ?Factory $factory = null;
22
23
    private function __construct()
24
    {
25
    }
26
27
    /**
28
     * @psalm-param array<string, mixed> $definitions
29
     *
30
     * @throws InvalidConfigException
31
     *
32
     * @see Factory::__construct()
33
     */
34 16
    public static function initialize(
35
        ContainerInterface $container,
36
        array $definitions = [],
37
        bool $validate = true
38
    ): void {
39 16
        self::$factory = new Factory($container, $definitions, $validate);
40
    }
41
42
    /**
43
     * Creates a widget defined by config passed.
44
     *
45
     * @param array|callable|string $config The parameters for creating a widget.
46
     *
47
     * @throws WidgetFactoryInitializationException If factory was not initialized.
48
     * @throws CircularReferenceException
49
     * @throws InvalidConfigException
50
     * @throws NotFoundException
51
     * @throws NotInstantiableException
52
     *
53
     * @see Factory::create()
54
     *
55
     * @psalm-suppress MixedInferredReturnType
56
     * @psalm-suppress MixedReturnStatement
57
     */
58 15
    public static function createWidget(array|callable|string $config): Widget
59
    {
60 15
        if (self::$factory === null) {
61 1
            throw new WidgetFactoryInitializationException(
62 1
                'Widget factory should be initialized with WidgetFactory::initialize() call.',
63 1
            );
64
        }
65
66 14
        return self::$factory->create($config);
67
    }
68
}
69