Files
kiri-core/Annotation/Inject.php
T

111 lines
2.2 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-07-27 00:35:50 +08:00
use HttpServer\Http\Context;
2021-07-12 17:17:36 +08:00
use ReflectionException;
2021-03-23 17:56:28 +08:00
use ReflectionProperty;
2021-08-11 01:04:57 +08:00
use Kiri\Core\Str;
use Kiri\Kiri;
2021-02-22 17:44:24 +08:00
/**
* 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-07-27 16:08:16 +08:00
/**
* Inject constructor.
* @param string $value
* @param array $args
*/
2021-08-01 15:25:59 +08:00
public function __construct(private string $value, private array $args = [])
{
}
/**
* @param mixed $class
* @param mixed|null $method
* @return bool
* @throws ReflectionException
* @throws Exception
*/
public function execute(mixed $class, mixed $method = null): bool
{
if (!($method = $this->getProperty($class, $method))) {
return false;
}
/** @var ReflectionProperty $class */
$injectValue = $this->parseInjectValue();
if ($method->isPrivate() || $method->isProtected()) {
$this->setter($class, $method, $injectValue);
} else {
2021-08-09 02:13:54 +08:00
if (is_string($injectValue)){
var_dump($injectValue);
}
2021-08-01 15:25:59 +08:00
$class->{$method->getName()} = $injectValue;
}
return true;
}
/**
* @param $class
* @param $method
* @param $injectValue
*/
private function setter($class, $method, $injectValue)
{
$method = 'set' . ucfirst(Str::convertUnderline($method->getName()));
if (!method_exists($class, $method)) {
return;
}
$class->$method($injectValue);
}
/**
* @param $class
* @param $method
* @return ReflectionProperty|bool
*/
private function getProperty($class, $method): ReflectionProperty|bool
{
if ($method instanceof ReflectionProperty && !$method->isStatic()) {
return $method;
}
if (is_object($class)) $class = $class::class;
2021-08-11 01:04:57 +08:00
$method = Kiri::getDi()->getClassReflectionProperty($class, $method);
2021-08-01 15:25:59 +08:00
if (!$method || $method->isStatic()) {
return false;
}
return $method;
}
/**
* @return mixed
* @throws Exception
*/
private function parseInjectValue(): mixed
{
if (Context::hasContext($this->value)) {
return Context::getContext($this->value);
}
if (class_exists($this->value)) {
2021-08-11 01:04:57 +08:00
return Kiri::getDi()->get($this->value, $this->args);
} else if (Kiri::app()->has($this->value)) {
return Kiri::app()->get($this->value);
2021-08-01 15:25:59 +08:00
} else {
return $this->value;
}
}
2021-03-23 18:00:49 +08:00
2021-02-22 17:44:24 +08:00
}