Passed
Push — master ( ef2e09...1b1261 )
by Alexander
02:55
created

WidgetFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 80%

Importance

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

3 Methods

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