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
|
|
|
|