Files
kiri-core/Annotation/Inject.php
T

75 lines
1.7 KiB
PHP
Raw Normal View History

2021-02-22 17:44:24 +08:00
<?php
namespace Annotation;
2021-03-31 18:37:53 +08:00
use Exception;
2021-03-23 17:56:28 +08:00
use ReflectionProperty;
2021-02-22 17:44:24 +08:00
use Snowflake\Snowflake;
/**
* Class Inject
* @package Annotation
*/
2021-03-03 18:35:04 +08:00
#[\Attribute(\Attribute::TARGET_PROPERTY)] class Inject extends Attribute
2021-02-22 17:44:24 +08:00
{
2021-05-03 03:48:52 +08:00
/**
* Inject constructor.
* @param string $className
* @param array $args
*/
public function __construct(private string $className, private array $args = [])
{
}
2021-02-22 17:44:24 +08:00
2021-05-03 03:48:52 +08:00
/**
* @param array $handler
* @return mixed
* @throws Exception
*/
public function execute(mixed $class, mixed $method = null): mixed
{
$injectValue = $this->parseInjectValue();
2021-05-03 03:51:13 +08:00
if (!($method instanceof ReflectionProperty)) {
2021-05-03 03:51:49 +08:00
$method = new ReflectionProperty($class, $method);
2021-05-03 03:48:52 +08:00
}
2021-03-29 16:04:13 +08:00
2021-05-03 03:48:52 +08:00
/** @var ReflectionProperty $class */
2021-05-03 03:52:20 +08:00
if ($method->isPrivate() || $method->isProtected()) {
2021-05-03 03:48:52 +08:00
$method = 'set' . ucfirst($class->getName());
if (!method_exists($class, $method)) {
return false;
}
$class->$method($injectValue);
} else {
$class->{$method->getName()} = $injectValue;
}
return true;
}
2021-03-23 18:00:49 +08:00
2021-05-03 03:48:52 +08:00
/**
* @return mixed
* @throws Exception
*/
private function parseInjectValue(): mixed
{
if (class_exists($this->className)) {
$injectValue = Snowflake::createObject($this->className, $this->args);
} else if (Snowflake::app()->has($this->className)) {
$injectValue = Snowflake::app()->get($this->className);
} else {
$injectValue = $this->className;
}
2021-04-25 12:31:26 +08:00
// if (!empty($this->args) && is_object($injectValue)) {
// Snowflake::configure($injectValue, $this->args);
// }
2021-05-03 03:48:52 +08:00
return $injectValue;
}
2021-03-23 18:00:49 +08:00
2021-02-22 17:44:24 +08:00
}