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
|
|
|
* @param ContainerInterface $container |
29
|
|
|
* @param array $definitions |
30
|
|
|
* @param bool $validate |
31
|
|
|
* |
32
|
|
|
* @psalm-param array<string, mixed> $definitions |
33
|
|
|
* |
34
|
|
|
* @throws InvalidConfigException |
35
|
|
|
* |
36
|
|
|
* @see Factory::__construct() |
37
|
|
|
*/ |
38
|
16 |
|
public static function initialize( |
39
|
|
|
ContainerInterface $container, |
40
|
|
|
array $definitions = [], |
41
|
|
|
bool $validate = true |
42
|
|
|
): void { |
43
|
16 |
|
self::$factory = new Factory($container, $definitions, $validate); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Creates a widget defined by config passed. |
48
|
|
|
* |
49
|
|
|
* @param array|callable|string $config The parameters for creating a widget. |
50
|
|
|
* |
51
|
|
|
* @throws WidgetFactoryInitializationException If factory was not initialized. |
52
|
|
|
* @throws CircularReferenceException |
53
|
|
|
* @throws InvalidConfigException |
54
|
|
|
* @throws NotFoundException |
55
|
|
|
* @throws NotInstantiableException |
56
|
|
|
* |
57
|
|
|
* @see Factory::create() |
58
|
|
|
* |
59
|
|
|
* @return Widget |
60
|
|
|
* |
61
|
|
|
* @psalm-suppress MixedInferredReturnType |
62
|
|
|
* @psalm-suppress MixedReturnStatement |
63
|
|
|
*/ |
64
|
15 |
|
public static function createWidget($config): Widget |
65
|
|
|
{ |
66
|
15 |
|
if (self::$factory === null) { |
67
|
1 |
|
throw new WidgetFactoryInitializationException( |
68
|
|
|
'Widget factory should be initialized with WidgetFactory::initialize() call.', |
69
|
|
|
); |
70
|
|
|
} |
71
|
|
|
|
72
|
14 |
|
return self::$factory->create($config); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|