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