Files
kiri-core/Annotation/Inject.php
T

80 lines
1.8 KiB
PHP
Raw Normal View History

2021-02-22 17:44:24 +08:00
<?php
namespace Annotation;
use ReflectionException;
2021-03-23 17:56:28 +08:00
use ReflectionProperty;
2021-02-22 17:44:24 +08:00
use Snowflake\Exception\ComponentException;
use Snowflake\Exception\NotFindClassException;
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
{
/**
* Inject constructor.
* @param string $className
* @param array $args
*/
public function __construct(private string $className, private array $args = [])
{
}
/**
* @param array $handler
* @return mixed
2021-03-23 18:00:49 +08:00
* @throws ComponentException
2021-02-22 17:44:24 +08:00
* @throws NotFindClassException
2021-03-23 18:00:49 +08:00
* @throws ReflectionException
2021-02-22 17:44:24 +08:00
*/
public function execute(array $handler): mixed
{
2021-03-23 18:00:49 +08:00
$injectValue = $this->parseInjectValue();
2021-03-24 19:26:40 +08:00
if (!($handler[1] instanceof ReflectionProperty)) {
$handler[1] = new ReflectionProperty($handler[0], $handler[1]);
}
/** @var ReflectionProperty $handler [1] */
2021-03-23 18:01:28 +08:00
if ($handler[1]->isPrivate() || $handler[1]->isProtected()) {
$method = 'set' . ucfirst($handler[1]->getName());
2021-03-23 18:00:49 +08:00
if (!method_exists($handler[0], $method)) {
return false;
}
$handler[0]->$method($injectValue);
} else {
2021-03-23 18:01:28 +08:00
$handler[0]->{$handler[1]->getName()} = $injectValue;
2021-03-23 18:00:49 +08:00
}
return $handler[0];
}
/**
* @return mixed
* @throws ComponentException
* @throws NotFindClassException
* @throws ReflectionException
*/
private function parseInjectValue(): mixed
{
2021-03-03 18:35:04 +08:00
if (class_exists($this->className)) {
2021-03-23 17:56:28 +08:00
$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-02-22 17:44:24 +08:00
}
2021-03-23 17:56:28 +08:00
if (!empty($this->args) && is_object($injectValue)) {
Snowflake::configure($injectValue, $this->args);
2021-03-03 18:35:04 +08:00
}
2021-03-23 18:00:49 +08:00
return $injectValue;
2021-02-22 17:44:24 +08:00
}
2021-03-23 18:00:49 +08:00
2021-02-22 17:44:24 +08:00
}