123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188 |
- <?php
- namespace yii\di;
- use Yii;
- use yii\base\InvalidConfigException;
- class Instance
- {
-
- public $id;
-
- protected function __construct($id)
- {
- $this->id = $id;
- }
-
- public static function of($id)
- {
- return new static($id);
- }
-
- public static function ensure($reference, $type = null, $container = null)
- {
- if (is_array($reference)) {
- $class = isset($reference['class']) ? $reference['class'] : $type;
- if (!$container instanceof Container) {
- $container = Yii::$container;
- }
- unset($reference['class']);
- $component = $container->get($class, [], $reference);
- if ($type === null || $component instanceof $type) {
- return $component;
- }
- throw new InvalidConfigException('Invalid data type: ' . $class . '. ' . $type . ' is expected.');
- } elseif (empty($reference)) {
- throw new InvalidConfigException('The required component is not specified.');
- }
- if (is_string($reference)) {
- $reference = new static($reference);
- } elseif ($type === null || $reference instanceof $type) {
- return $reference;
- }
- if ($reference instanceof self) {
- try {
- $component = $reference->get($container);
- } catch (\ReflectionException $e) {
- throw new InvalidConfigException('Failed to instantiate component or class "' . $reference->id . '".', 0, $e);
- }
- if ($type === null || $component instanceof $type) {
- return $component;
- }
- throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
- }
- $valueType = is_object($reference) ? get_class($reference) : gettype($reference);
- throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
- }
-
- public function get($container = null)
- {
- if ($container) {
- return $container->get($this->id);
- }
- if (Yii::$app && Yii::$app->has($this->id)) {
- return Yii::$app->get($this->id);
- }
- return Yii::$container->get($this->id);
- }
-
- public static function __set_state($state)
- {
- if (!isset($state['id'])) {
- throw new InvalidConfigException('Failed to instantiate class "Instance". Required parameter "id" is missing');
- }
- return new self($state['id']);
- }
- }
|