rhertogh /
yii2-oauth2-server
| 1 | <?php |
||
| 2 | |||
| 3 | namespace rhertogh\Yii2Oauth2Server\helpers; |
||
| 4 | |||
| 5 | use Yii; |
||
| 6 | use yii\base\InvalidConfigException; |
||
| 7 | use yii\di\Instance; |
||
| 8 | |||
| 9 | class DiHelper |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * Resolve a class or interface to the configured class name. |
||
| 13 | * @param Instance|callable|string|object|array $class |
||
| 14 | * @return mixed|string |
||
| 15 | * @throws InvalidConfigException |
||
| 16 | * @since 1.0.0 |
||
| 17 | */ |
||
| 18 | 13 | public static function getClassName($class) |
|
| 19 | { |
||
| 20 | 13 | if ($class instanceof Instance) { |
|
| 21 | 1 | return static::getClassName($class->id); |
|
| 22 | } |
||
| 23 | |||
| 24 | 13 | $definitions = Yii::$container->definitions; |
|
| 25 | |||
| 26 | 13 | if (empty($definitions[$class])) { |
|
| 27 | 3 | return $class; |
|
| 28 | } |
||
| 29 | |||
| 30 | 10 | $definition = $definitions[$class]; |
|
| 31 | |||
| 32 | 10 | if (is_callable($definition, true)) { |
|
| 33 | 1 | $definition = Yii::createObject($class); |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 34 | } |
||
| 35 | |||
| 36 | 10 | if (is_object($definition)) { |
|
| 37 | 2 | return get_class($definition); |
|
| 38 | } |
||
| 39 | |||
| 40 | 8 | if (is_array($definition) && !empty($definition['class'])) { |
|
| 41 | 7 | return $definition['class']; |
|
| 42 | } |
||
| 43 | |||
| 44 | 1 | throw new \LogicException('Unknown dependency type: ' . gettype($definition)); |
|
| 45 | } |
||
| 46 | |||
| 47 | /** |
||
| 48 | * Resolves a class name and, in case of an interface, ensure that the concrete class implements the interface. |
||
| 49 | * @param Instance|callable|string|object|array $class |
||
| 50 | * @return string |
||
| 51 | * @throws InvalidConfigException |
||
| 52 | * @see getClassName() |
||
| 53 | * @since 1.0.0 |
||
| 54 | */ |
||
| 55 | 7 | public static function getValidatedClassName($class) |
|
| 56 | { |
||
| 57 | 7 | $classDefinition = static::getClassName($class); |
|
| 58 | |||
| 59 | 7 | if (interface_exists($class)) { |
|
| 60 | 6 | if (empty($classDefinition) || $classDefinition === $class) { |
|
| 61 | 1 | throw new InvalidConfigException( |
|
| 62 | 1 | $class . ' must be configured in the application dependency injection container.' |
|
| 63 | 1 | ); |
|
| 64 | 5 | } elseif (!is_a($classDefinition, $class, true)) { |
|
| 65 | 5 | throw new InvalidConfigException($classDefinition . ' must implement ' . $class); |
|
| 66 | } |
||
| 67 | 1 | } elseif (!class_exists($classDefinition)) { |
|
| 68 | 1 | throw new InvalidConfigException('Class ' . $classDefinition . ' does not exist.'); |
|
| 69 | } |
||
| 70 | |||
| 71 | 4 | return $classDefinition; |
|
| 72 | } |
||
| 73 | } |
||
| 74 |