/** * @return Method[] */ public static function methodListFromReflectionClassAndMethod(Context $context, CodeBase $code_base, \ReflectionClass $class, \ReflectionMethod $reflection_method) : array { $reflection_method = new \ReflectionMethod($class->getName(), $reflection_method->name); $method = new Method($context, $reflection_method->name, new UnionType(), $reflection_method->getModifiers()); $method->setNumberOfRequiredParameters($reflection_method->getNumberOfRequiredParameters()); $method->setNumberOfOptionalParameters($reflection_method->getNumberOfParameters() - $reflection_method->getNumberOfRequiredParameters()); $method->setFQSEN(FullyQualifiedMethodName::fromStringInContext($method->getName(), $context)); return self::functionListFromFunction($method, $code_base); }
/** * Dispatch the request, return the response * * @return Response The returned response */ public function dispatch() { $service = $this->request->getService(); $method = $this->request->getMethod(); $params = (array) $this->request->getParams(); try { $handlerClass = sprintf('Handler_%s', ucfirst($service)); $handler = new $handlerClass($this->request); } catch (Exception $e) { $this->jsonError(JSONRPC_ERROR_METHOD_NOT_FOUND, 'Requested service unknown'); } if (!method_exists($handler, $method)) { $this->jsonError(JSONRPC_ERROR_METHOD_NOT_FOUND, 'Requested method unknown'); } $ref = new ReflectionMethod($handler, $method); $handlerParams = $ref->getParameters(); foreach ($handlerParams as $handlerParam) { if (!array_key_exists($handlerParam->name, $params)) { $this->jsonError(JSONRPC_ERROR_INVALID_PARAMS, sprintf('Missing parameter "%s"', $handlerParam->name)); } } if (count($params) !== $ref->getNumberOfRequiredParameters()) { $this->jsonError(JSONRPC_ERROR_INVALID_PARAMS, 'Wrong number of parameters'); } Context::getInstance()->getLogger()->info(sprintf('Executing method "%s" in service "%s" with parameters "%s"', $method, $handlerClass, json_encode($params))); return call_user_func_array(array($handler, $method), $params); }
static function executeControllerAction($controller, $action, $args) { if (self::controllerExists($controller)) { if (!method_exists($controller, $action)) { if (method_exists($controller, self::$method_unknown)) { array_unshift($args, $action); $action = self::$method_unknown; } else { throw new ErrorNotFound("Method " . $action . " could not be found in Controller " . $controller); } } } else { //fallback to unkown controller method in main if (self::controllerExists("main") && method_exists("main", self::$method_unknown)) { array_unshift($args, $controller, $action); $controller = "main"; $action = self::$method_unknown; } else { throw new ErrorNotFound("Controller " . $controller . " can not be loaded."); } } #check for parameter-count $method = new ReflectionMethod($controller, $action); $parametercount = $method->getNumberOfRequiredParameters(); if (count($args) < $parametercount) { throw new ErrorNotAllowed("Can't call " . $controller . "." . $action . ".\n" . "Got " . count($args) . " arguments but at least " . $parametercount . " are required."); } #call it $instance = new $controller($controller); call_user_func_array(array($instance, $action), $args); }
/** * @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; }
/** * Método para verificar se os parâmetros informados são pelo menos o total * exigido na classe do módulo. * Adicionada a chamada __call() caso a classe tenha * * @throws ControleException */ private static function checarParametros() { // Se o total de parâmetros não suprir o número requerido if (self::$metodo->getName() != '__call' && count(self::$dadosUrl) < self::$metodo->getNumberOfRequiredParameters()) { throw new ControleException(ControleException::PARAMETROS_INSUFICIENTES, ucfirst(self::$modulo) . "::" . self::$acao); } }
/** * Return Transport. example: TransportFactory::GetTransport('SSH', $ssh_host, $ssh_port, $ssh_user, $ssh_pass); * * @static * @param string $transportname * @return Object */ public static function GetTransport($transportname) { $path_to_transports = dirname(__FILE__) . "/Transports"; if (file_exists("{$path_to_transports}/class.{$transportname}Transport.php")) { Core::Load("class.{$transportname}Transport.php", $path_to_transports); if (class_exists("{$transportname}Transport") && self::IsTransport("{$transportname}Transport")) { // Get Constructor Reflection if (is_callable(array("{$transportname}Transport", "__construct"))) { $reflect = new ReflectionMethod("{$transportname}Transport", "__construct"); } // Delete $objectname from arguments $num_args = func_num_args() - 1; $args = func_get_args(); array_shift($args); if ($reflect) { $required_params = $reflect->getNumberOfRequiredParameters(); if ($required_params > $num_args) { $params = $reflect->getParameters(); //TODO: Show what params are missing in error Core::RaiseError(sprintf(_("Missing some required arguments for %s Transport constructor. Passed: %s, expected: %s."), $transportname, $num_args, $required_params)); } } $reflect = new ReflectionClass("{$transportname}Transport"); if (count($args) > 0) { return $reflect->newInstanceArgs($args); } else { return $reflect->newInstance(true); } } else { Core::RaiseError(sprintf(_("Class '%s' not found or doesn't implements ITransport interface"), "{$transportname}Transport")); } } }
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; }
public function invokeMethod($method, $params) { // for named parameters, convert from object to assoc array if (is_object($params)) { $array = array(); foreach ($params as $key => $val) { $array[$key] = $val; } $params = array($array); } // for no params, pass in empty array if ($params === null) { $params = array(); } $reflection = new \ReflectionMethod($this->exposed_instance, $method); // only allow calls to public functions if (!$reflection->isPublic()) { throw new Serverside\Exception("Called method is not publically accessible."); } // enforce correct number of arguments $num_required_params = $reflection->getNumberOfRequiredParameters(); if ($num_required_params > count($params)) { throw new Serverside\Exception("Too few parameters passed."); } return $reflection->invokeArgs($this->exposed_instance, $params); }
private function getControllerObject(\ReflectionClass $rc, \ReflectionMethod $ra, array $params) { if ($ra->getNumberOfRequiredParameters() > count($params)) { throw new NotFoundException("Wrong number of parameters."); } return $rc->newInstance($this); }
public function callQueueMethod(Queue $queue, $method) { $r = new \ReflectionMethod($queue, $method); if ($num = $r->getNumberOfRequiredParameters()) { return call_user_func_array([$queue, $method], array_fill(0, $num, 'foo')); } return $queue->{$method}(); }
/** * Returns the number of required parameters * * @return integer The number of required parameters * @since PHP 5.0.3 */ public function getNumberOfRequiredParameters() { if ($this->reflectionSource instanceof ReflectionMethod) { return $this->reflectionSource->getNumberOfRequiredParameters(); } else { return parent::getNumberOfRequiredParameters(); } }
public function __construct(\ReflectionMethod $reflector) { $this->name = $reflector->name; $this->class = $reflector->class; $this->export = preg_match('/@Export\\s/', $reflector->getDocComment()) > 0; $this->reqParamCount = $reflector->getNumberOfRequiredParameters(); $this->isPublic = $reflector->isPublic(); $this->isStatic = $reflector->isStatic(); }
public function testExecute_ParamCount() { $action = 'paramAction'; $controller = new Index(); $controller->setAction($action); $reflectionAction = new \ReflectionMethod($controller, $action); $expectedParamCount = $reflectionAction->getNumberOfRequiredParameters(); $actualParamCount = $controller->execute(array(10)); $this->assertEquals($expectedParamCount, $actualParamCount); }
function resolve2($context, array $path) { $original_path = $path; $head = array_shift($path); $args = $path; $head = $this->translate($head); // If the head is empty, then the URL ended in a slash (/), assume // the index is implied if (!$head) { $head = 'index'; } try { $method = new \ReflectionMethod($context, $head); // Ensure that the method is visible if (!$method->isPublic()) { return false; } // Check if argument count matches the rest of the URL if (count($args) < $method->getNumberOfRequiredParameters()) { // Not enough parameters in the URL return false; } if (count($args) > ($C = $method->getNumberOfParameters())) { // Too many parameters in the URL — pass as many as possible to the function $path = array_slice($args, $C); $args = array_slice($args, 0, $C); } // Try to call the method and see what kind of response we get $result = $method->invokeArgs($context, $args); if ($result instanceof View\BaseView) { return $result; } elseif (is_callable($result)) { // We have a callable to be considered the view. We're done. return new View\BoundView($result, $args); } elseif ($result instanceof Dispatcher) { // Delegate to a sub dispatcher return $result->resolve(implode('/', $path)); } elseif (is_object($result)) { // Recurse forward with the remainder of the path return $this->resolve2($result, $path); } // From here, we assume that the call failed } catch (\ReflectionException $ex) { // No such method, try def() or recurse backwards } catch (Exception\ConditionFailed $ex) { // The matched method refused the request — recurse backwards } // Not able to dispatch the method. Try def() if ($head != 'def') { $path = array_merge(['def'], $original_path); return $this->resolve2($context, $path); } // Unable to dispatch the request return false; }
/** * "Start" the application: * Analyze the URL elements and calls the according controller/method or the fallback */ public function __construct() { // create array with URL parts in $url $this->splitUrl(); // check for controller: no controller given ? then load start-page if (!$this->controllerName) { require CONTROLLER_PATH . 'home_ctrl.php'; $page = new HomeCtrl(); $page->index(); } elseif ($this->controllerName == 'public') { return; } elseif (!file_exists(CONTROLLER_PATH . $this->controllerName . '_ctrl.php')) { require CONTROLLER_PATH . 'error_ctrl.php'; $page = new ErrorCtrl(); $page->notFound(); } else { // here we did check for controller: does such a controller exist ? // if so, then load this file and create this controller // example: if controller would be "car", then this line would translate into: $this->car = new car(); $controllerFile = $this->controllerName . '_ctrl.php'; $controllerName = $this->controllerName . 'Ctrl'; require CONTROLLER_PATH . $controllerFile; $this->controller = new $controllerName(); // check for method: does such a method exist in the controller ? if (!method_exists($this->controller, $this->actionName)) { if (strlen($this->actionName) == 0) { // no action defined: call the default index() method of a selected controller $this->controller->index(); } else { require CONTROLLER_PATH . 'error_ctrl.php'; $page = new ErrorCtrl(); $page->notFound(); } } else { $reflectionMethod = new \ReflectionMethod($this->controller, $this->actionName); $numberOfRequiredParameters = $reflectionMethod->getNumberOfRequiredParameters(); if (sizeof($this->params) < $numberOfRequiredParameters) { require CONTROLLER_PATH . 'error_ctrl.php'; $page = new ErrorCtrl(); $page->notFound(); } else { if (!empty($this->params)) { // Call the method and pass arguments to it call_user_func_array(array($this->controller, $this->actionName), $this->params); } else { // If no parameters are given, just call the method without parameters, like $this->home->method(); $this->controller->{$this->actionName}(); } } } } }
/** * Runs the test method. * @return void */ private function runMethod($method) { $method = new \ReflectionMethod($this, $method); if (!$method->isPublic()) { throw new TestCaseException("Method {$method->getName()} is not public. Make it public or rename it."); } $data = array(); $info = Helpers::parseDocComment($method->getDocComment()) + array('dataprovider' => NULL, 'throws' => NULL); if ($info['throws'] === '') { throw new TestCaseException("Missing class name in @throws annotation for {$method->getName()}()."); } elseif (is_array($info['throws'])) { throw new TestCaseException("Annotation @throws for {$method->getName()}() can be specified only once."); } else { $throws = preg_split('#\\s+#', $info['throws'], 2) + array(NULL, NULL); } $defaultParams = array(); foreach ($method->getParameters() as $param) { $defaultParams[$param->getName()] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL; } foreach ((array) $info['dataprovider'] as $provider) { $res = $this->getData($provider); if (!is_array($res)) { throw new TestCaseException("Data provider {$provider}() doesn't return array."); } foreach ($res as $set) { $data[] = is_string(key($set)) ? array_merge($defaultParams, $set) : $set; } } if (!$info['dataprovider']) { if ($method->getNumberOfRequiredParameters()) { throw new TestCaseException("Method {$method->getName()}() has arguments, but @dataProvider is missing."); } $data[] = array(); } foreach ($data as $args) { try { if ($info['throws']) { $tmp = $this; $e = Assert::error(function () use($tmp, $method, $args) { $tmp->runTest($method->getName(), $args); }, $throws[0], $throws[1]); if ($e instanceof AssertException) { throw $e; } } else { $this->runTest($method->getName(), $args); } } catch (AssertException $e) { throw $e->setMessage("{$e->origMessage} in {$method->getName()}" . substr(Dumper::toLine($args), 5)); } } }
private static function validateCall() { $controller = 'application\\controllers\\' . ucfirst(self::$request->controller); $reflection = new \ReflectionMethod($controller, ucfirst(self::$request->action)); $countWaitingParams = $reflection->getNumberOfParameters(); $countWaitingRequiredParams = $reflection->getNumberOfRequiredParameters(); $countComingParams = count(self::$request->params); if ($countComingParams > $countWaitingParams || $countComingParams < $countWaitingRequiredParams) { throw new InvalidException("Passed wrong number of arguments to the method", 404); } else { return $controller; } }
/** * Overload all calls to the adapter and redir them to the @Object contained. * __callStatic() only in PHP >= 5.3.0 * @param $method * @param $parameters * @return */ public function __call($method, $parameters) { try { $method = new ReflectionMethod($this->modelObject, $method); if ($method->getNumberOfRequiredParameters() > 0) { return $method->invokeArgs($this->modelObject, $parameters); } else { return $method->invoke($this->modelObject, null); } } catch (ReflectionException $e) { Soprano::exception($e->getMessage()); } }
public function dispatch() { $this->initRequest(); if (!$this->cInstance) { $this->_notfound(); } $this->cInstance->init(); $this->cInstance->before(); if ($this->cInstance instanceof Controller && method_exists($this->cInstance, $this->getActionName())) { $reflectionMethod = new \ReflectionMethod($this->cInstance, $this->getActionName()); if ($reflectionMethod->getNumberOfRequiredParameters() > 0) { $paramsWithid = $this->application->request()->getParamArrays(); $paramsWithName = $this->application->request()->getParams(); $ps = array(); foreach ($reflectionMethod->getParameters() as $i => $param) { $name = $param->getName(); if (isset($paramsWithName[$name])) { if ($param->isArray()) { $ps[] = is_array($paramsWithName[$name]) ? $paramsWithName[$name] : array($paramsWithName[$name]); } else { if (!is_array($paramsWithName[$name])) { $ps[] = $paramsWithName[$name]; } } } else { if (isset($paramsWithid[$i])) { $ps[] = $paramsWithid[$i]; } else { if ($param->isDefaultValueAvailable()) { $ps[] = $param->getDefaultValue(); } else { $ps[] = NULL; } } } } $reflectionMethod->invokeArgs($this->cInstance, $ps); // call_user_func_array(array($this->cInstance, $this->getActionName()), array()); } else { $reflectionMethod->invoke($this->cInstance); } } else { if ($this->cInstance instanceof RestController) { call_user_func_array(array($this->cInstance, 'dispatch'), array($this->getActionName(), $this->application->request()->getParamArrays())); // call_user_func_array(array($this->cInstance, $this->getActionName()), $this->application->request()->getParamArrays()); } else { $this->_notfound(); } } $this->cInstance->after(); }
/** * Realiza el dispatch de una ruta * * @return Object */ public static function execute($route) { extract($route, EXTR_OVERWRITE); if (!(include_once APP_PATH . "controllers/{$controller_path}" . '_controller.php')) { throw new KumbiaException(NULL, 'no_controller'); } //Asigna el controlador activo $app_controller = Util::camelcase($controller) . 'Controller'; $cont = self::$_controller = new $app_controller($module, $controller, $action, $parameters); View::select($action); View::setPath($controller_path); // Se ejecutan los filtros before if ($cont->k_callback('initialize') === FALSE) { return $cont; } if ($cont->k_callback('before_filter') === FALSE) { return $cont; } //Se ejecuta el metodo con el nombre de la accion //en la clase de acuerdo al convenio if (!method_exists($cont, $action)) { throw new KumbiaException(NULL, 'no_action'); } //Obteniendo el metodo $reflectionMethod = new ReflectionMethod($cont, $action); //k_callback y __constructor metodo reservado if ($reflectionMethod->name == 'k_callback' || $reflectionMethod->isConstructor()) { throw new KumbiaException('Esta intentando ejecutar un método reservado de KumbiaPHP'); } //se verifica que el metodo sea public if (!$reflectionMethod->isPublic()) { throw new KumbiaException(NULL, 'no_action'); } //se verifica que los parametros que recibe //la action sea la cantidad correcta $num_params = count($parameters); if ($cont->limit_params && ($num_params < $reflectionMethod->getNumberOfRequiredParameters() || $num_params > $reflectionMethod->getNumberOfParameters())) { throw new KumbiaException("Número de parámetros erroneo para ejecutar la acción \"{$action}\" en el controlador \"{$controller}\""); } $reflectionMethod->invokeArgs($cont, $parameters); //Corre los filtros after $cont->k_callback('after_filter'); $cont->k_callback('finalize'); //Si esta routed volver a ejecutar if (Router::getRouted()) { Router::setRouted(FALSE); return Dispatcher::execute(Router::get()); // Vuelve a ejecutar el dispatcher } return $cont; }
/** * @param string $context * @param string $controller * @param string $action * @param array|string|null $params * @return string $controller * @throws \Exception */ private static function validateCall($context, $controller, $action, $params = null) { $controller = 'App\\' . ucfirst($context) . '\\Controller\\' . ucfirst($controller) . "Controller"; $action = 'action' . ucfirst($action); $rFunction = new \ReflectionMethod($controller, $action); $countParams = $rFunction->getNumberOfParameters(); $countRequiredParams = $rFunction->getNumberOfRequiredParameters(); $countArgs = count($params); if ($countArgs > $countParams || $countArgs < $countRequiredParams) { throw new HttpException("Passed wrong number of arguments to the method", 404); } else { return $controller; } }
public static function a2o(&$_object, $_data) { if (is_array($_data)) { foreach ($_data as $key => $value) { $method = 'set' . ucfirst($key); if (method_exists($_object, $method)) { $function = new ReflectionMethod($_object, $method); if (is_json($value)) { $value = json_decode($value, true); } if (is_array($value)) { if ($function->getNumberOfRequiredParameters() == 2) { foreach ($value as $arrayKey => $arrayValue) { if (is_array($arrayValue)) { if ($function->getNumberOfRequiredParameters() == 3) { foreach ($arrayValue as $arrayArraykey => $arrayArrayvalue) { $_object->{$method}($arrayKey, $arrayArraykey, $arrayArrayvalue); } } else { $_object->{$method}($arrayKey, $arrayValue); } } else { $_object->{$method}($arrayKey, $arrayValue); } } } else { $_object->{$method}(json_encode($value, JSON_UNESCAPED_UNICODE)); } } else { if ($function->getNumberOfRequiredParameters() < 2) { $_object->{$method}($value); } } } } } }
/** * Create path for URI from method parameter list * * @param \ReflectionMethod $method * @return string */ protected static function getPathPartDefinedByParameters(\ReflectionMethod $method) { $path = ''; $pathEnd = ''; $reqPar = $method->getNumberOfRequiredParameters(); foreach ($method->getParameters() as $key => $param) { if ($key < $reqPar) { $path .= '/{' . preg_replace('#_$#', '+', $param->name) . '}'; } else { $path .= '[/{' . $param->name . '}'; $pathEnd .= ']'; } } return $path . $pathEnd; }
public function __set($name, $value) { $method = 'set_' . $name; if (method_exists($this, $method)) { return call_user_func(array($this, $method), $value); } $set_method_name = 'set_' . $method; if (method_exists($this, $set_method_name)) { $set_method = new \ReflectionMethod(get_class($this), $set_method_name); if ($set_method->getNumberOfRequiredParameters() <= 1) { return call_user_func_array(array($this, $set_method_name), array($value)); } } return parent::__set($name, $value); // return $this->set_param($name, $value); }
protected function setAction($action, $params) { try { $reflector = new ReflectionMethod($this->controller, $action); if (!$reflector->isPublic()) { throw new Exception(); } if (count($params) < $reflector->getNumberOfRequiredParameters()) { $this->error(400, 'Method is missing required parameters'); } } catch (Exception $e) { $this->error(404, 'Unknown method'); } $this->action = $action; $this->params = $params; }
public static function createFromToken(FunctionDefine $aFunctionDefine) { if (!($aClassDefine = $aFunctionDefine->belongsClass())) { throw new Exception("传入的 \$aFunctionDefine 参数无效,必须是一个类方法的定义Token"); } try { $aMethodRef = new \ReflectionMethod($aClassDefine->fullName(), $aFunctionDefine->name()); } catch (\Exception $e) { throw new Exception("无法找到 Pointcut %s::%s 的定义", array($aClassDefine->fullName(), $aFunctionDefine->name()), $e); } // 检查参数(不能有非可缺省的参数) if ($aMethodRef->getNumberOfRequiredParameters()) { throw new Exception("Pointcut %s::%s() 的定义无效:要求了非可缺省的参数; 请检查该Pointcut的参数表。", array($aClassDefine->fullName(), $aFunctionDefine->name())); } // 声明为静态方法 if ($aMethodRef->isStatic()) { if (!$aMethodRef->isPublic()) { throw new Exception("Pointcut %s::%s() 声明为 static 类型,static 类型的 Pointcut 必须为 public。", array($aClassDefine->fullName(), $aFunctionDefine->name())); } $arrJointPoints = call_user_func(array($aClassDefine->fullName(), $aFunctionDefine->name())); } else { try { $aClassRef = new \ReflectionClass($aClassDefine->fullName()); } catch (\Exception $e) { throw new Exception("无法找到 Aspect %s 的定义,无法定义Pointcut:%s::%s", array($aClassDefine->fullName(), $aClassDefine->fullName(), $aFunctionDefine->name()), $e); } // 检查该类的构造函数的参数 if ($aConstructor = $aClassRef->getConstructor() and $aConstructor->getNumberOfRequiredParameters()) { throw new Exception("由于 Pointcut %s::%s() 没有被申明为 static ,则所属的Aspect(%s)的构造函数不能要求非可省的参数。将 Pointcut %s::%s() 声明为 static,或者取消Aspect(%s)的构造函数所要求的非可省参数。", array($aClassDefine->fullName(), $aFunctionDefine->name(), $aClassDefine->fullName(), $aClassDefine->fullName(), $aFunctionDefine->name(), $aClassDefine->fullName())); } $aMethodRef->setAccessible(true); $arrJointPoints = $aMethodRef->invokeArgs($aClassRef->newInstanceArgs(), array()); } $aPointcut = new self($aFunctionDefine->name()); $aPointcut->sDefineMethod = $aFunctionDefine->name(); if (is_array($arrJointPoints)) { foreach ($arrJointPoints as $aJointPoint) { if ($aJointPoint instanceof JointPoint) { $aPointcut->jointPoints()->add($aJointPoint); $aJointPoint->setPointcut($aPointcut); } else { throw new Exception("Pointcut %s::%s 的定义中,申明了无效的 JointPoint: %s", array($aClassDefine->fullName(), $aFunctionDefine->name(), var_export($aJointPoint, true))); } } } return $aPointcut; }
protected function setUp() { // Set rule method $this->ruleMethod = 'rule_' . substr($this->getName(), strlen('test_')); try { $ruleMethod = new ReflectionMethod('vacuum\\Rules', $this->ruleMethod); $this->assertTrue($ruleMethod->isStatic(), 'Check if method is static'); $this->assertTrue($ruleMethod->isPublic(), 'Check if method is public'); $this->assertContains($ruleMethod->getNumberOfRequiredParameters(), [0, 1, 2], 'Check if method has 1 or 2 arguments'); $params = $ruleMethod->getParameters(); foreach ($params as $param) { $this->assertFalse($param->isPassedByReference(), 'Check if there are no arguments setted via reference'); } } catch (ReflectionException $e) { $this->assertTrue(false, 'Check if validation method exists'); } }
/** * Ensure that this callback takes no arguments * * @param callable $cb */ public static function validateCallback(callable $cb) { if (is_string($cb) and strpos($cb, "::") !== false) { $cb = explode("::", $cb); } if (is_string($cb) or $cb instanceof \Closure) { $function = new \ReflectionFunction($cb); if ($function->getNumberOfRequiredParameters() > 0) { throw new \InvalidArgumentException("Callable requires parameters"); } } elseif (is_array($cb)) { list($ctx, $m) = $cb; $method = new \ReflectionMethod($ctx, $m); if ($method->getNumberOfRequiredParameters() > 0) { throw new \InvalidArgumentException("Callable requires parameters"); } } }
protected function valid_method($method, $passedParams) { if (method_exists($this, $method)) { $reflectionMethod = new ReflectionMethod($this, $method); if (!$reflectionMethod->isPublic()) { $error = "The method must be public"; } if (count($passedParams) < $reflectionMethod->getNumberOfRequiredParameters()) { $error = 'The method must be called with the number or required parameters'; } } else { $error = 'The method "' . $method . '" does not exist'; } if (isset($error)) { show_error($error); exit; } }
/** * Attempt to publish the object, if it supports this funcitonality. */ public static function attempt_publish($obj) { if ($obj->hasExtension('Versioned')) { if (method_exists($obj, 'doPublish')) { // Detect legacy function signatures with parameters (e.g. as in EditableFormFields) $reflection = new ReflectionMethod(get_class($obj), 'doPublish'); if ($reflection->getNumberOfRequiredParameters() == 0) { // New $obj->doPublish(); } else { // Legacy $obj->doPublish('Stage', 'Live'); } } else { // Versioned default $obj->publish('Stage', 'Live'); } } }