/
Component.php
225 lines (199 loc) · 7.85 KB
/
Component.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\helpers;
use Craft;
use craft\base\ComponentInterface;
use craft\errors\MissingComponentException;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
/**
* Component helper
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class Component
{
/**
* Returns whether a component class exists, is an instance of a given interface,
* and doesn't belong to a disabled plugin.
*
* @param string $class The component’s class name.
* @phpstan-param class-string<ComponentInterface> $class
* @param string|null $instanceOf The class or interface that the component must be an instance of.
* @phpstan-param class-string<ComponentInterface>|null $instanceOf
* @param bool $throwException Whether an exception should be thrown if an issue is encountered
* @return bool
* @throws InvalidConfigException if $config doesn’t contain a `type` value, or the type isn’t compatible with|null $instanceOf.
* @throws MissingComponentException if the class specified by $config doesn’t exist, or belongs to an uninstalled plugin
* @since 3.2.0
*/
public static function validateComponentClass(string $class, ?string $instanceOf = null, bool $throwException = false): bool
{
// Validate the class
if (!class_exists($class)) {
if (!$throwException) {
return false;
}
throw new MissingComponentException("Unable to find component class '$class'.");
}
if (!is_subclass_of($class, ComponentInterface::class)) {
if (!$throwException) {
return false;
}
throw new InvalidConfigException("Component class '$class' does not implement ComponentInterface.");
}
/** @var string $class */
/** @phpstan-var class-string $class */
if ($instanceOf !== null && !is_subclass_of($class, $instanceOf)) {
if (!$throwException) {
return false;
}
throw new InvalidConfigException("Component class '$class' is not an instance of '$instanceOf'.");
}
// If it comes from a plugin, make sure the plugin is installed
$pluginsService = Craft::$app->getPlugins();
$pluginHandle = $pluginsService->getPluginHandleByClass($class);
if ($pluginHandle !== null && !$pluginsService->isPluginEnabled($pluginHandle)) {
if (!$throwException) {
return false;
}
$pluginInfo = $pluginsService->getComposerPluginInfo($pluginHandle);
$pluginName = $pluginInfo['name'] ?? $pluginHandle;
if ($pluginsService->isPluginInstalled($pluginHandle)) {
$message = "Component class '$class' belongs to a disabled plugin ($pluginName).";
} else {
$message = "Component class '$class' belongs to an uninstalled plugin ($pluginName).";
}
throw new MissingComponentException($message);
}
return true;
}
/**
* Cleanses a component config of any `on X` or `as X` keys.
*
* @param array $config
* @return array
* @since 4.4.15
*/
public static function cleanseConfig(array $config): array
{
foreach ($config as $key => $value) {
if (is_string($key) && (str_starts_with($key, 'on ') || str_starts_with($key, 'as '))) {
unset($config[$key]);
continue;
}
if (is_array($value)) {
$config[$key] = static::cleanseConfig($value);
}
}
return $config;
}
/**
* Instantiates and populates a component, and ensures that it is an instance of a given interface.
*
* @template T of ComponentInterface
* @param string|array $config The component’s class name, or its config, with a `type` value and optionally a `settings` value.
* @phpstan-param class-string<T>|array{type:class-string<T>,__class?:string} $config
* @param string|null $instanceOf The class or interface that the component must be an instance of.
* @phpstan-param class-string<T>|null $instanceOf
* @return T The component
* @throws InvalidConfigException if $config doesn’t contain a `type` value, or the type isn’t compatible with|null $instanceOf.
* @throws MissingComponentException if the class specified by $config doesn’t exist, or belongs to an uninstalled plugin
*/
public static function createComponent(string|array $config, ?string $instanceOf = null): ComponentInterface
{
// Normalize the config
if (is_string($config)) {
$class = $config;
$config = [];
} else {
if (empty($config['type'])) {
throw new InvalidConfigException('The config passed into Component::createComponent() did not specify a class: ' . Json::encode($config));
}
$class = $config['type'];
unset($config['type'], $config['__class']);
}
// Validate the component class
static::validateComponentClass($class, $instanceOf, true);
// Merge the settings sub-key into the main config
$config = self::mergeSettings($config);
// Typecast the properties
Typecast::properties($class, $config);
// Instantiate and return
$config['class'] = $class;
return Craft::createObject($config);
}
/**
* Extracts settings from a given component config, and returns a new config array with the settings merged in.
*
* @param array $config
* @return array
*/
public static function mergeSettings(array $config): array
{
if (($settings = ArrayHelper::remove($config, 'settings')) === null) {
return $config;
}
if (is_string($settings)) {
$settings = Json::decode($settings);
if (!is_array($settings)) {
return $config;
}
}
return array_merge($config, $settings);
}
/**
* Returns an SVG icon’s contents, namespaced and with `aria-hidden="true"` added to it.
*
* @param string|null $icon The path to the SVG icon, or the actual SVG contents
* @param string $label The label of the component
* @return string
* @since 3.5.0
*/
public static function iconSvg(?string $icon, string $label): string
{
if ($icon === null) {
return self::_defaultIconSvg($label);
}
if (stripos($icon, '<svg') === false) {
$icon = Craft::getAlias($icon);
if (!is_file($icon)) {
Craft::warning("Icon file doesn't exist: $icon", __METHOD__);
return self::_defaultIconSvg($label);
}
if (!FileHelper::isSvg($icon)) {
Craft::warning("Icon file is not an SVG: $icon", __METHOD__);
return self::_defaultIconSvg($label);
}
$icon = file_get_contents($icon);
}
// Namespace it
$ns = StringHelper::randomString(10);
$icon = Html::namespaceAttributes($icon, $ns, true);
// Add aria-hidden="true"
try {
$icon = Html::modifyTagAttributes($icon, [
'aria' => ['hidden' => 'true'],
]);
} catch (InvalidArgumentException) {
}
return $icon;
}
/**
* Returns the default icon SVG for a given widget type.
*
* @param string $label
* @return string
*/
private static function _defaultIconSvg(string $label): string
{
return Craft::$app->getView()->renderTemplate('_includes/defaulticon.svg.twig', [
'label' => $label,
]);
}
}