1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/zhimiao-frame-php

Клонировать/Скачать
Reflection.php 3.3 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
倒霉狐狸(公司PC) Отправлено 29.01.2019 14:28 1211209
<?php
/**
* 反射类- 用于解析控制器中方法参数
* Created by PhpStorm.
* User: 倒霉狐狸
* Date: 2018-08-14
* Time: 11:42
*/
namespace zhimiao;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Exception;
class Reflection
{
/**
* 调用反射执行类的方法 支持参数绑定
* @access public
* @param mixed $method 方法
* @param array $vars 参数
* @return mixed
*/
public function invokeMethod($method, $vars = [])
{
try {
if (is_array($method)) {
$class = is_object($method[0]) ? $method[0] : $this->invokeClass($method[0]);
$reflect = new ReflectionMethod($class, $method[1]);
} else {
// 静态方法
$reflect = new ReflectionMethod($method);
}
if (!$reflect->isPublic()) {
throw new ReflectionException('the function is not found [-.0]');
}
$args = $this->bindParams($reflect, $vars);
return $reflect->invokeArgs(isset($class) ? $class : null, $args);
} catch (Exception $e) {
Response::json(-10001, null, $e->getMessage());
}
}
/**
* 调用反射执行类的实例化 支持依赖注入
* @access public
* @param string $class 类名
* @param array $vars 参数
* @return mixed
*/
public function invokeClass($class, $vars = [])
{
try {
$reflect = new ReflectionClass($class);
if ($reflect->hasMethod('__make')) {
$method = new ReflectionMethod($class, '__make');
if ($method->isPublic() && $method->isStatic()) {
$args = $this->bindParams($method, $vars);
return $method->invokeArgs(null, $args);
}
}
$constructor = $reflect->getConstructor();
$args = $constructor ? $this->bindParams($constructor, $vars) : [];
return $reflect->newInstanceArgs($args);
} catch (Exception $e) {
Response::json(-10000, null, $e->getMessage());
}
}
/**
* 绑定参数
* @access protected
* @param \ReflectionMethod|\ReflectionFunction $reflect 反射类
* @param array $vars 参数
* @return array
*/
protected function bindParams($reflect, $vars = [])
{
if ($reflect->getNumberOfParameters() == 0) {
return [];
}
// 判断数组类型 数字数组时按顺序绑定参数
reset($vars);
$type = key($vars) === 0 ? 1 : 0;
$params = $reflect->getParameters();
foreach ($params as $param) {
$name = $param->getName();
$class = $param->getClass();
if ($class) {
$args[] = $this->getObjectParam($class->getName(), $vars);
} elseif (1 == $type && !empty($vars)) {
$args[] = array_shift($vars);
} elseif (0 == $type && isset($vars[$name])) {
$args[] = $vars[$name];
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
throw new \Exception('method param miss:' . $name);
}
}
return $args;
}
}

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/zhimiao-frame-php.git
git@api.gitlife.ru:oschina-mirror/zhimiao-frame-php.git
oschina-mirror
zhimiao-frame-php
zhimiao-frame-php
master