/** * @param string | object $listener * @param \ReflectionMethod $methodReflection * @return array */ protected function createHandler($listener, \ReflectionMethod $methodReflection) { if (is_string($listener) && $methodReflection->isStatic()) { return [$listener, $methodReflection->getName()]; } elseif (is_object($listener) && $methodReflection->isStatic()) { return [get_class($listener), $methodReflection->getName()]; } elseif (is_object($listener) && $methodReflection->isStatic() == false) { return [$listener, $methodReflection->getName()]; } return false; }
/** * {@inheritDoc} */ public function getMode() { if ($this->reflection instanceof \ReflectionFunction) { return self::MODE_FUNCTION; } elseif ($this->reflection instanceof \ReflectionMethod) { if ($this->reflection->isStatic()) { return self::MODE_METHOD_STATIC; } else { return self::MODE_METHOD; } } else { throw new \RuntimeException(sprintf('The reflection "%s" not supported.', get_class($this->reflection))); } }
/** * Execute callback * @return mixed */ public function execute() { // token check if (!$this->checkToken()) { throw new InvalidArgumentException('Invalid security token.', self::ERROR_SECURITY_TOKEN); } // authorisation check if (!$this->checkPermission()) { throw new LogicException('Access denied.', self::ERROR_PERMISSION); } // function if (function_exists($this->callable_name)) { return call_user_func_array($this->callable_name, $this->args); } list($class, $method) = explode('::', $this->callable_name); $methodRef = new ReflectionMethod($class, $method); // static method if ($methodRef->isStatic()) { return call_user_func_array($this->callable_name, $this->args); } // object method - create object instance $classRef = new ReflectionClass($class); $cargsNum = $classRef->getConstructor()->getNumberOfParameters(); $cargs = array_slice($this->args, 0, $cargsNum); $instance = $classRef->newInstanceArgs($cargs); // call instance method $args = array_slice($this->args, $cargsNum); return $methodRef->invokeArgs($instance, $args); }
public static function getCallback($callback, $file = null) { try { if ($file) { self::loadFile($file); } if (is_array($callback)) { $method = new \ReflectionMethod(array_shift($callback), array_shift($callback)); if ($method->isPublic()) { if ($method->isStatic()) { $callback = array($method->class, $method->name); } else { $callback = array(new $method->class(), $method->name); } } } else { if (is_string($callback)) { $callback = $callback; } } if (is_callable($callback)) { return $callback; } throw new InvalidCallbackException("Invalid callback"); } catch (\Exception $ex) { throw $ex; } }
/** * @throws \InvalidArgumentException */ private function set_title() { /** * @var $router Router */ $router = Application::get_class(Router::class); $pageModel = $router->current_page(); if ($pageModel) { $title = $this->titles[$pageModel->name]; if (is_array($title)) { list($class, $method, $prefix) = array_pad($title, 3, ''); try { $reflection_method = new \ReflectionMethod($class, $method); $params = $router->get_route_params(); $params[] = $prefix; if ($reflection_method->isStatic()) { $this->current = call_user_func_array([$class, $method], $params); } else { $this->current = call_user_func_array([Application::get_class($class), $method], $params); } } catch (\Exception $e) { Error::log($e->getMessage()); } } else { $this->current = $title; } } }
public function __call($method, $args) { if (stripos($method, 'static') === 0) { $mtd = substr($method, 6); $nmtd = strtolower($mtd); if (!isset($this->staticMethods[$nmtd])) { try { $rm = new ReflectionMethod($this->classn, $mtd); } catch (Exception $e) { throw new Exception('Method "Clap_ServiceInstance->' . $method . '()" is trying to call "' . $this->classn . '::' . $mtd . '()" static method, which is not defined'); } if (!$rm->isStatic()) { throw new Exception('Method "Clap_ServiceInstance->' . $method . '()" cannot call "' . $this->classn . '::' . $mtd . '()" because this is not a static method'); } $this->staticMethods[$nmtd] = true; } return call_user_func_array(array($this->classn, $mtd), $args); } else { $class = get_called_class(); if ($class == 'Clap_ServiceInstance') { throw new Exception('Method "' . $method . '()" called on a "' . $this->classn . '" ServiceInstance, use "getNew()" or "getInstance()" to get an instance of "' . $this->classn . '"'); } else { throw new Exception('Undefined method "' . $class . '::' . $method . '()" called, check "Backtrace" for more informations'); } } }
public function execute($argv) { if (!is_array($argv)) { $argv = array($argv); } $argc = count($argv); if (empty($this->action)) { throw new \Jolt\Exception('controller_action_not_set'); } try { $action = new \ReflectionMethod($this, $this->action); } catch (\ReflectionException $e) { throw new \Jolt\Exception('controller_action_not_part_of_class'); } $paramCount = $action->getNumberOfRequiredParameters(); if ($paramCount != $argc && $paramCount > $argc) { $argv = array_pad($argv, $paramCount, NULL); } ob_start(); if ($action->isPublic()) { if ($action->isStatic()) { $action->invokeArgs(NULL, $argv); } else { $action->invokeArgs($this, $argv); } } $renderedController = ob_get_clean(); if (!empty($renderedController)) { $this->renderedController = $renderedController; } else { $this->renderedController = $this->renderedView; } return $this->renderedController; }
/** * This method searches for the renderer in den Renderer directory and * loads them. The class itself ensures to run this method once before * the data from this run is needed. */ public function findRenderer() { if (!$this->findRendererAlreadyRun) { foreach (glob(dirname(__FILE__) . DIRECTORY_SEPARATOR . "Renderer" . DIRECTORY_SEPARATOR . "*Renderer") as $filename) { $filename = $filename . DIRECTORY_SEPARATOR . basename($filename) . ".php"; if (is_file($filename)) { $className = basename($filename, '.php'); $classNameWithNamespace = 'PartKeepr\\Printing\\Renderer\\' . $className . '\\' . $className; $exists = class_exists($classNameWithNamespace); if ($exists) { try { $onRegister = new \ReflectionMethod($classNameWithNamespace, 'onRegister'); if ($onRegister->isStatic()) { // Enough sanity checks, if now something goes wrong, we will fail. $onRegister->invoke(null, $this); } else { trigger_error("Method onRegister in class {$classNameWithNamespace} is not static, ignoring class.", E_USER_WARNING); } } catch (\ReflectionException $e) { trigger_error("Method onRegister in class {$classNameWithNamespace} gave an error: " . $e->getMessage() . ". Ignoring class.", E_USER_WARNING); } } else { // Sanely ignore this case, because this may arise often if a needed library is not present. // trigger_error("File $filename does not contain a class with $classNameWithNamespace.",E_USER_WARNING ); } } } $this->findRendererAlreadyRun = true; } }
private function _invoke($clz = '', $act = '', $param, $namespace = 'Home\\Controller\\') { $clz = ucwords($clz); $clz_name = $namespace . $clz . 'Controller'; try { $ref_clz = new \ReflectionClass($clz_name); if ($ref_clz->hasMethod($act)) { $ref_fun = new \ReflectionMethod($clz_name, $act); if ($ref_fun->isPrivate() || $ref_fun->isProtected()) { $ref_fun->setAccessible(true); } if ($ref_fun->isStatic()) { $ref_fun->invoke(null); } else { $ref_fun_par = $ref_fun->getParameters(); if (!empty($param) && is_array($param)) { if (is_array($ref_fun_par) && count($ref_fun_par) == count($param)) { $ref_fun->invokeArgs(new $clz_name(), $param); } else { $ref_fun->invoke(new $clz_name()); } } else { $ref_fun->invoke(new $clz_name()); } } } } catch (\LogicException $le) { $this->ajaxReturn(array('status' => '500', 'info' => '服务器内部发生严重错误')); } catch (\ReflectionException $re) { $this->ajaxReturn(array('status' => '404', 'info' => '访问' . $clz . '控制器下的非法操作', 'data' => array('code' => $re->getCode()))); } }
/** * * Expects an either a function name or an array of class and method as * callback. * * @param string $prefix * @param mixed $callback * @param bool $is_fallback if true, method will be used as last resort (if there's no phptal_tales_foo) */ public function registerPrefix($prefix, $callback, $is_fallback = false) { if ($this->isRegistered($prefix) && !$this->_callbacks[$prefix]['is_fallback']) { if ($is_fallback) { return; // simply ignored } throw new PHPTAL_ConfigurationException("Expression modifier '{$prefix}' is already registered"); } // Check if valid callback if (is_array($callback)) { $class = new ReflectionClass($callback[0]); if (!$class->isSubclassOf('PHPTAL_Tales')) { throw new PHPTAL_ConfigurationException('The class you want to register does not implement "PHPTAL_Tales".'); } $method = new ReflectionMethod($callback[0], $callback[1]); if (!$method->isStatic()) { throw new PHPTAL_ConfigurationException('The method you want to register is not static.'); } // maybe we want to check the parameters the method takes } else { if (!function_exists($callback)) { throw new PHPTAL_ConfigurationException('The function you are trying to register does not exist.'); } } $this->_callbacks[$prefix] = array('callback' => $callback, 'is_fallback' => $is_fallback); }
/** * Resolves the target of the route and returns a callable. * * @param mixed $target * @param array $construct_args * * @throws RuntimeException If the target is not callable * * @return callable */ private static function getCallable($target, array $construct_args) { if (is_string($target)) { //is a class "classname::method" if (strpos($target, '::') === false) { $class = $target; $method = '__invoke'; } else { list($class, $method) = explode('::', $target, 2); } if (!class_exists($class)) { throw new RuntimeException("The class {$class} does not exists"); } $fn = new \ReflectionMethod($class, $method); if (!$fn->isStatic()) { $class = new \ReflectionClass($class); $instance = $class->hasMethod('__construct') ? $class->newInstanceArgs($construct_args) : $class->newInstance(); $target = [$instance, $method]; } } //if it's callable as is if (is_callable($target)) { return $target; } throw new RuntimeException('The route target is not callable'); }
public function do_ajax() { $class = $_REQUEST['module']; $function = $_REQUEST['act']; if ($class == 'core' || $class == 'this') { $module = 'core'; } else { if (class_exists($class)) { $module = $class; } else { $module = '\\module\\' . $class . '\\controller'; } } if (class_exists($module)) { $class = new \ReflectionClass($module); if ($class->hasMethod($function)) { $method = new \ReflectionMethod($module, $function); if ($method->isStatic()) { $module::$function(); } else { if ($module != 'core') { $object = new $module(); $object->{$function}(); } else { $this->{$function}(); } } } } ajax::do_serve(); exit; }
/** * Executes an action with named parameters * @param mixed $action An action that can be a function, callback or class method. * @param array $params (optional) An array of named parameters to pass into the action. * @return mixed Returns any values returned by the action. */ public function dispatch($action, $params = array()) { $invokeParams = array(); if (is_array($action)) { $reflection = new \ReflectionMethod($action[0], $action[1]); if ($reflection->isStatic()) { $invokeParams[] = null; } else { $invokeParams[] = $action[0]; } } else { $reflection = new \ReflectionFunction($action); } $pass = array(); foreach ($reflection->getParameters() as $param) { /* @var $param ReflectionParameter */ if (isset($params[$param->getName()])) { $pass[] = $params[$param->getName()]; } elseif ($param->isOptional()) { try { $pass[] = $param->getDefaultValue(); } catch (\ReflectionException $ex) { // move on if there is no default value. } } } $invokeParams[] = $pass; return call_user_func_array(array($reflection, 'invokeArgs'), $invokeParams); }
public function profile($classname, $methodname, $methodargs, $invocations = 1) { if (class_exists($classname) != TRUE) { throw new Exception("{$classname} doesn't exist"); } $method = new ReflectionMethod($classname, $methodname); $this->reflection = $method; $instance = NULL; if (!$method->isStatic()) { $class = new ReflectionClass($classname); $instance = $class->newInstance(); } $durations = array(); for ($i = 0; $i < $invocations; $i++) { $start = microtime(true); $method->invokeArgs($instance, $methodargs); $durations[] = microtime(true) - $start; $memory_script[] = memory_get_peak_usage(false) / 1024 / 1024; // User from the script $memory_real[] = memory_get_peak_usage(true) / 1024 / 1024; // Allocated memory from the system } $duration["total"] = round(array_sum($duration), 4); $duration["average"] = round($duration["total"] / count($durations), 4); $duration["worst"] = round(max($durations), 4); $mm_real["total"] = round(array_sum($memory_real), 4); $mm_real["average"] = round($mm_real["total"] / count($memory_real), 4); $mm_real["worst"] = round(max($memory_real), 4); $mm_script["total"] = round(array_sum($memory_script), 4); $mm_script["average"] = round($mm_script["total"] / count($memory_script), 4); $mm_script["worst"] = round(max($memory_script), 4); $this->details = array("date" => date('Y-m-d h:m:s'), "class" => $classname, "method" => $methodname, "arguments" => $methodargs, "duration" => $duration, "invocations" => $invocations, "allocated_memory_average" => $mm_real['average'], "allocated_memory_worst" => $mm_real['worst'], "script_memory_average" => $mm_script['average'], "script_memory_worst" => $mm_script['worst']); $this->printDetails(); $this->storeDetails(); }
/** * @param App\Request $request * @return App\IResponse */ public function run(App\Request $request) { $this->request = $request; $this->startup(); if (!$this->startupCheck) { $class = (new \ReflectionClass($this))->getMethod('startup')->getDeclaringClass()->getName(); throw new Nette\InvalidStateException("'{$class}::startup()' or its descendant does not call parent method"); } try { $rm = new \ReflectionMethod($this, $this->getAction()); } catch (\ReflectionException $e) { } if (isset($e) || $rm->isAbstract() || $rm->isStatic() || !$rm->isPublic()) { throw new App\BadRequestException("Method '{$request->getMethod()}' not allowed", 405); } $params = $this->getParameters(); $args = App\UI\PresenterComponentReflection::combineArgs($rm, $params); $response = $rm->invokeArgs($this, $args); if ($response === null) { $response = new Responses\NullResponse(); } elseif (!$response instanceof App\IResponse) { throw new Nette\InvalidStateException("Action '{$this->getAction(true)}' does not return instance of Nette\\Application\\IResponse"); } return $response; }
private static function reflector($method_and_params) { $class = get_called_class(); $method = $method_and_params[0]; $args = $method_and_params[1]; $reflectionMethod = new \ReflectionMethod($class, $method); if (!$reflectionMethod->isStatic()) { throw new \Exception("The method: {$class}::{$method} should be static!!"); } if (!$reflectionMethod->isPrivate()) { throw new \Exception("The static method: {$class}::{$method} should be private!!"); } $params = array(); foreach ($reflectionMethod->getParameters() as $param) { if (isset($args[$param->getName()])) { $params[] = $args[$param->getName()]; } else { if ($param->isOptional()) { $params[] = $param->getDefaultValue(); } else { throw new \Exception("The method: {$class}::{$method} signature requires a \"\${$param->getName()}\" argument!!"); } } } $reflectionMethod->setAccessible(true); return $reflectionMethod->invokeArgs(null, $params); }
public function __construct($callable, array $annotations = array()) { if (is_array($callable)) { list($this->class, $method) = $callable; $reflMethod = new \ReflectionMethod($this->class, $method); if (!$reflMethod->isPublic()) { throw new \InvalidArgumentException('Class method must be public'); } elseif ($reflMethod->isStatic()) { $this->staticMethod = $method; } else { $this->method = $method; $class = $this->class; $this->instance = new $class(); } } elseif ($callable instanceof \Closure) { $this->closure = $callable; } elseif (is_string($callable)) { if (!function_exists($callable)) { throw new \InvalidArgumentException('Function does not exist'); } $this->function = $callable; } else { throw new \InvalidArgumentException('Invalid callable type'); } $this->annotations = $annotations; }
/** * {@inheritdoc} */ public function validate($object, Constraint $constraint) { if (!$constraint instanceof Callback) { throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Callback'); } $method = $constraint->callback; if ($method instanceof \Closure) { $method($object, $this->context, $constraint->payload); } elseif (is_array($method)) { if (!is_callable($method)) { if (isset($method[0]) && is_object($method[0])) { $method[0] = get_class($method[0]); } throw new ConstraintDefinitionException(sprintf('%s targeted by Callback constraint is not a valid callable', json_encode($method))); } call_user_func($method, $object, $this->context, $constraint->payload); } elseif (null !== $object) { if (!method_exists($object, $method)) { throw new ConstraintDefinitionException(sprintf('Method "%s" targeted by Callback constraint does not exist in class %s', $method, get_class($object))); } $reflMethod = new \ReflectionMethod($object, $method); if ($reflMethod->isStatic()) { $reflMethod->invoke(null, $object, $this->context, $constraint->payload); } else { $reflMethod->invoke($object, $this->context, $constraint->payload); } } }
public function testLoadValidatorMetadataMethodIsStatic() { foreach ($this->classes as $class) { $method = new \ReflectionMethod($class, 'loadValidatorMetadata'); $this->assertTrue($method->isStatic()); } }
/** * {@inheritdoc} */ public function validate($object, Constraint $constraint) { if (null === $object) { return; } if (null !== $constraint->callback && null !== $constraint->methods) { throw new ConstraintDefinitionException('The Callback constraint supports either the option "callback" ' . 'or "methods", but not both at the same time.'); } // has to be an array so that we can differentiate between callables // and method names if (null !== $constraint->methods && !is_array($constraint->methods)) { throw new UnexpectedTypeException($constraint->methods, 'array'); } $methods = $constraint->methods ?: array($constraint->callback); foreach ($methods as $method) { if (is_array($method) || $method instanceof \Closure) { if (!is_callable($method)) { throw new ConstraintDefinitionException(sprintf('"%s::%s" targeted by Callback constraint is not a valid callable', $method[0], $method[1])); } call_user_func($method, $object, $this->context); } else { if (!method_exists($object, $method)) { throw new ConstraintDefinitionException(sprintf('Method "%s" targeted by Callback constraint does not exist', $method)); } $reflMethod = new \ReflectionMethod($object, $method); if ($reflMethod->isStatic()) { $reflMethod->invoke(null, $object, $this->context); } else { $reflMethod->invoke($object, $this->context); } } } }
protected static function call($callable, $parameter = array()) { if (is_callable($callable)) { call_user_func_array($callable, $parameter); } else { try { $controllerArray = explode("@", $callable); $controllerClass = new $controllerArray[0](); $method = $controllerArray[1]; if (method_exists($controllerClass, $method)) { $methodChecker = new ReflectionMethod($controllerClass, $method); if ($methodChecker->isStatic()) { call_user_func_array([$controllerClass, $method], $parameter); } else { if (is_subclass_of($controllerClass, "BaseController")) { $template_engine_name = TEMPLATE_ENGINE_NAME; $template_engine = new $template_engine_name(); $controllerClass->setTemplateEngine($template_engine); } call_user_func_array([$controllerClass, $method], $parameter); } } else { throw new Exception("No method named {$method} found in {$controllerClass}"); } } catch (Exception $e) { throw new Exception("No Class named {$controllerClass} was found"); } } }
/** * @param \ReflectionMethod $method * @return bool */ private function isAutoloadMethod(\ReflectionMethod $method) { if (strpos($method->getName(), KnotConsts::AUTOLOAD_METHOD_PREFIX) !== 0 || $method->getNumberOfParameters() != 1 || $method->getNumberOfRequiredParameters() != 1 || $method->isStatic() || $method->isAbstract() || !Extractor::instance()->has($method, KnotConsts::AUTOLOAD_ANNOTATIONS)) { return false; } return true; }
public static function call($className, $methodParams = null, $classParams = null) { $className = str_replace('.', '\\', $className); $methodName = null; if (strpos($className, '::') !== false) { list($className, $methodName) = explode('::', $className); } // Check if the Class Exists if (!class_exists($className, true)) { throw new \Exception($className . ' does not exist'); } if (!is_null($methodName)) { // Check if Static Method or Object Method Call $reflectionMethod = new \ReflectionMethod($className, $methodName); if ($reflectionMethod->isStatic()) { return static::staticMethodCall($className, $methodName, $methodParams); } // Create Instance of Class return static::objectMethodCall($className, $classParams, $methodName, $methodParams); } // If there are no method must be a invokable object // Create Instance of Class $class = static::createObject($className, $classParams); if (!is_callable($class)) { throw new \Exception($className . ' is not callable'); } return static::objectCall($class, $methodParams); }
/** * @param Factory $factory * @param string $class * @param string $name * @param array|Argument[] $arguments * @param array|History[] $collected * @throws \ReflectionException If the method cannot be stubbed */ function __construct(Factory $factory, $class, $name, array $arguments = [], array $collected = []) { $this->class = $class; $this->name = $name; $this->arguments = $arguments; $this->reflection = new \ReflectionMethod($class, $name); $this->typeHint = new ReturnTypeInferer($this->reflection, $factory); $this->history = new History($collected); if ($this->reflection->isPrivate()) { throw new \ReflectionException("Cannot stub private methods [{$this->class}::{$name}()]"); } else { if ($this->reflection->isStatic()) { throw new \ReflectionException("Cannot stub static methods [{$this->class}::{$name}()]"); } } }
public function validate_action(Request $request) { try { $rmethod = new ReflectionMethod($this->controller, $request->parameter('action')); } catch (ReflectionException $rfEx) { throw new ChainError($rfEx->getMessage()); } if (!$rmethod->isPublic() || $rmethod->isStatic()) { throw new ChainError('Method `' . $rmethod->getName() . '` should be declared as public on class instance `' . get_class($this->controller) . '`'); } $rparams = $rmethod->getParameters(); $action_args = array(); foreach ($rparams as $arg) { $arg_name = $arg->getName(); $arg_value = $request->parameter($arg_name); // XXX: detect behavior on Merb / Django if (null === $arg_value) { if ($arg->isOptional()) { continue; } else { throw new ChainError('Mandatory agrument `' . $arg_name . '` for action `' . $rmethod->getName() . '` not in request!'); } } $action_args[$arg_name] = $arg_value; } // ready to fire this action later $this->chain['action'] = array($rmethod, $action_args); // return true for now return true; }
public function __call($methodName, array $args) { $method = new \ReflectionMethod($this->class, $methodName); if (!$method->isPublic()) { $method->setAccessible(true); } return $method->isStatic() ? $method->invokeArgs(null, $args) : $method->invokeArgs($this->object, $args); }
/** * Returns whether this method is static * * @return boolean TRUE if this method is static */ public function isStatic() { if ($this->reflectionSource instanceof ReflectionMethod) { return $this->reflectionSource->isStatic(); } else { return parent::isStatic(); } }
public function hasMethod($name) { if ($this->owner->modelClass && method_exists($this->owner->modelClass, $name)) { $ref = new \ReflectionMethod($this->owner->modelClass, $name); return $ref->isStatic() && count($ref->getParameters()) >= 1; } return false; }
/** * Determines if the method is suitable to be used by the processor. * (see \Magento\Framework\Reflection\MethodsMap::isSuitableMethod) * * @param \ReflectionMethod $method * @return bool */ public function _isSuitableMethod(\ReflectionMethod $method) { /* '&&' usage is shorter then '||', if first part is 'false' then all equity is false */ $isSuitableMethodType = !$method->isStatic() && !$method->isFinal() && !$method->isConstructor() && !$method->isDestructor(); $isExcludedMagicMethod = strpos($method->getName(), '__') === 0; $result = $isSuitableMethodType && !$isExcludedMagicMethod; return $result; }
function getInvokeMethodArray($class, $method) { $ReflectionMethod = new ReflectionMethod($class, $method); if ($ReflectionMethod->isStatic()) { return [$class, $method]; } return [new $class(), $method]; }