Files
kiri-core/Annotation/Inject.php
T

94 lines
1.9 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-12 17:17:36 +08:00
use ReflectionException;
2021-03-23 17:56:28 +08:00
use ReflectionProperty;
2021-07-21 13:49:55 +08:00
use Snowflake\Core\Str;
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-07-21 11:25:31 +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-07-12 17:17:36 +08:00
/**
* @param mixed $class
* @param mixed|null $method
* @return bool
* @throws ReflectionException
* @throws Exception
*/
2021-07-21 11:25:31 +08:00
public function execute(mixed $class, mixed $method = null): bool
{
$injectValue = $this->parseInjectValue();
2021-07-21 13:49:55 +08:00
if (!($method = $this->getProperty($class, $method))) {
return false;
2021-07-21 11:25:31 +08:00
}
/** @var ReflectionProperty $class */
if ($method->isPrivate() || $method->isProtected()) {
2021-07-21 13:49:55 +08:00
$method = 'set' . ucfirst(Str::convertUnderline($method->getName()));
2021-07-21 11:25:31 +08:00
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-07-21 13:49:55 +08:00
/**
* @param $class
* @param $method
* @return ReflectionProperty|bool
*/
private function getProperty($class, $method): ReflectionProperty|bool
{
if ($method instanceof ReflectionProperty) {
return $method;
}
2021-07-21 13:51:52 +08:00
if (is_object($class)) $class = $class::class;
2021-07-21 13:49:55 +08:00
$method = Snowflake::getDi()->getClassProperty($class, $method);
if (!$method) {
return false;
}
return $method;
}
2021-07-21 11:25:31 +08:00
/**
* @return mixed
* @throws Exception
*/
private function parseInjectValue(): mixed
{
if (class_exists($this->className)) {
$injectValue = Snowflake::getDi()->get($this->className, $this->args);
} else if (Snowflake::app()->has($this->className)) {
$injectValue = Snowflake::app()->get($this->className);
} else {
$injectValue = $this->className;
}
return $injectValue;
}
2021-03-23 18:00:49 +08:00
2021-02-22 17:44:24 +08:00
}