|
81 | 81 | use Twig\TwigFilter; |
82 | 82 | use Twig\TwigFunction; |
83 | 83 | use Twig\TwigTest; |
| 84 | +use yii\base\BaseObject; |
84 | 85 | use yii\base\InvalidArgumentException; |
85 | 86 | use yii\base\InvalidConfigException; |
86 | 87 | use yii\db\Exception; |
@@ -1390,7 +1391,7 @@ public function getFunctions(): array |
1390 | 1391 | new TwigFunction('combine', 'array_combine'), |
1391 | 1392 | new TwigFunction('configure', [Craft::class, 'configure']), |
1392 | 1393 | new TwigFunction('cpUrl', [UrlHelper::class, 'cpUrl']), |
1393 | | - new TwigFunction('create', [Craft::class, 'createObject']), |
| 1394 | + new TwigFunction('create', [$this, 'createFunction']), |
1394 | 1395 | new TwigFunction('dataUrl', [$this, 'dataUrlFunction']), |
1395 | 1396 | new TwigFunction('date', [$this, 'dateFunction'], ['needs_environment' => true]), |
1396 | 1397 | new TwigFunction('dump', [$this, 'dumpFunction'], ['is_safe' => ['html'], 'needs_context' => true, 'is_variadic' => true]), |
@@ -1472,6 +1473,26 @@ public function collectFunction(mixed $var): Collection |
1472 | 1473 | return $collection; |
1473 | 1474 | } |
1474 | 1475 |
|
| 1476 | + /** |
| 1477 | + * Creates a new object. |
| 1478 | + * |
| 1479 | + * @template T of BaseObject |
| 1480 | + * @param class-string<T>|array{class:class-string<T>}|array{__class:class-string<T>} $type |
| 1481 | + * @param array $params |
| 1482 | + * @return T |
| 1483 | + * @since 5.9.0 |
| 1484 | + */ |
| 1485 | + public function createFunction(string|array $type, array $params = []): BaseObject |
| 1486 | + { |
| 1487 | + $class = is_string($type) ? $type : ($type['__class'] ?? $type['class'] ?? null); |
| 1488 | + if (!is_subclass_of($class, BaseObject::class)) { |
| 1489 | + throw new InvalidArgumentException(sprintf('create() can only be used to create instances of %s.', BaseObject::class)); |
| 1490 | + } |
| 1491 | + |
| 1492 | + /** @var BaseObject */ |
| 1493 | + return Craft::createObject($type, $params); |
| 1494 | + } |
| 1495 | + |
1475 | 1496 | /** |
1476 | 1497 | * Generates a base64-encoded [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) for the given file path or asset. |
1477 | 1498 | * |
|
0 commit comments