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; } }
public function run($coreClass, $command, $parameters) { $messenger = new Service_Messenger(); try { $reflection = new ReflectionClass($coreClass); $interface = 'Service_Interface'; if (!$reflection->implementsInterface($interface)) { if ($reflection->hasMethod($command)) { $method = new ReflectionMethod($coreClass, $command); if ($method->isPublic() && $command != '__construct') { $core = new $coreClass($messenger); $result = $core->{$command}($parameters); return $this->_output($result, $messenger); } } $messenger->addMessage('Invalid command'); return $this->_output(false, $messenger); } else { throw new Service_Exception('Core Class does not implement ' . $interface); } } catch (Exception $e) { $messenger->addMessage('EXCEPTION' . "\n\n" . 'Exception Type: ' . get_class($e) . "\n" . 'File: ' . $e->getFile() . "\n" . 'Line: ' . $e->getLine() . "\n" . 'Message: ' . $e->getMessage() . "\n" . 'Stack Trace' . "\n" . $e->getTraceAsString()); return $this->_output(false, $messenger); } }
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; }
protected function _isPrivateAction(\ReflectionMethod $method) { if ($method->name[0] === '_' || !$method->isPublic()) { return true; } return false; }
/** * 执行当前控制器方法 * * @param string $actionName 方法名 * @param array $params 参数列表 * @return Response|mixed * @throws AppException */ public function runActionWithParams($actionName, $params = array()) { if (empty($actionName)) { $actionName = $this->defaultAction; } if (!method_exists($this, $actionName)) { throw new \BadMethodCallException("方法不存在: {$actionName}"); } $method = new \ReflectionMethod($this, $actionName); if (!$method->isPublic()) { throw new \BadMethodCallException("调用非公有方法: {$actionName}"); } $args = array(); $methodParams = $method->getParameters(); if (!empty($methodParams)) { foreach ($methodParams as $key => $p) { $default = $p->isOptional() ? $p->getDefaultValue() : null; $value = isset($params[$key]) ? $params[$key] : $default; if (null === $value && !$p->isOptional()) { throw new AppException(get_class($this) . "::{$actionName}() 缺少参数: " . $p->getName()); } $args[] = $value; } } $result = $method->invokeArgs($this, $args); if ($result instanceof Response) { return $result; } elseif (null !== $result) { $this->response->setContent(strval($result)); } return $this->response; }
private static function start() { $control = control(CONTROL); if (!$control) { if (IS_GROUP and !is_dir(GROUP_PATH . GROUP_NAME)) { _404('应用组' . GROUP_PATH . GROUP_NAME . '不存在'); } if (!is_dir(APP_PATH)) { _404('应用' . APP . '不存在'); } $control = Control("Empty"); if (!$control) { _404('模块' . CONTROL . C("CONTROL_FIX") . '不存在'); } } try { $method = new ReflectionMethod($control, METHOD); if ($method->isPublic()) { $method->invoke($control); } else { throw new ReflectionException(); } } catch (ReflectionException $e) { $method = new ReflectionMethod($control, '__call'); $method->invokeArgs($control, array(METHOD, '')); } }
/** * Вызывает действие, контролируя его наличие и публичный доступ к нему. * Действие запускается через ReflectionMethod->invokeArgs() что позволяет самому действию * контролировать принимаемые на вход параметры. Все прочие параметры отсеиваются. * * @param string $action действие - название публичного метода в классе контроллера * @param array $request данные запроса - ассоциативный массив данных пришедших по любому каналу * @return array результат выполнения действия (зачастую действие самостоятельно редиректит дальше) * @throws Exception */ private function Invoke($action, $request) { if (!method_exists($this, $action)) { throw new Exception("Неизвестное действие - '{$action}'"); } //$this->Debug($action, 'Invoke $action'); //$this->Debug($request, 'Invoke $request'); $reflection = new \ReflectionMethod($this, $action); if (!$reflection->isPublic()) { throw new Exception("Действие '{$action}' запрещено вызывать из контроллера публичной части"); } $request = array_change_key_case($request); $parameters = $reflection->getParameters(); //$this->Debug($parameters, 'Invoke $parameters'); $arguments = array(); foreach ($parameters as $parameter) { $code = strtolower($parameter->name); if (isset($request[$code])) { $arguments[$code] = $request[$code]; } else { try { $arguments[$code] = $parameter->getDefaultValue(); } catch (Exception $error) { $arguments[$code] = null; } } } //$this->Debug($arguments, 'Invoke $arguments'); return $reflection->invokeArgs($this, $arguments); }
/** * Magic function to read a data value * * @param $name string Name of the property to be returned * @throws Exception * @return mixed */ public function __get($name) { if (isset($this->_valueMap[$name])) { $key = $this->_valueMap[$name]; } else { $key = $name; } if (!is_array($this->_primaryKey) && $key == $this->_primaryKey) { return $this->getId(); } if (!array_key_exists($key, $this->_data)) { // Is there a public getter function for this value? $functionName = $this->composeGetterName($key); if (method_exists($this, $functionName)) { $reflection = new \ReflectionMethod($this, $functionName); if ($reflection->isPublic()) { return $this->{$functionName}(); } } throw new Exception('Column not found in data: ' . $name); } $result = $this->_data[$key]; if (isset($this->_formatMap[$key])) { $result = Format::fromSql($this->_formatMap[$key], $result); } return $result; }
/** * @param mixed $method * @return mixed|void */ public function setMethod(\ReflectionMethod $method) { if (!$method->isPublic()) { throw new Exception("You can not use the Register or Subscribe annotation on a non-public method"); } $this->method = $method; }
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; }
/** * Check to see if said module has method and is publically callable * @param {string} $module The raw module name * @param {string} $method The method name */ public function moduleHasMethod($module, $method) { $this->getActiveModules(); $module = ucfirst(strtolower($module)); if (!empty($this->moduleMethods[$module]) && in_array($method, $this->moduleMethods[$module])) { return true; } $amods = array(); foreach (array_keys($this->active_modules) as $mod) { $amods[] = $this->cleanModuleName($mod); } if (in_array($module, $amods)) { try { $rc = new \ReflectionClass($this->FreePBX->{$module}); if ($rc->hasMethod($method)) { $reflection = new \ReflectionMethod($this->FreePBX->{$module}, $method); if ($reflection->isPublic()) { $this->moduleMethods[$module][] = $method; return true; } } } catch (\Exception $e) { } } return false; }
public function __construct($argv) { $this->verbose = $this->verbose == true ? true : false; $argv[] = '-clean'; $argv[] = ''; $this->args = $argv; // get the systems username and set the home dir. $this->user = get_current_user(); $this->home = '/home/' . $this->user . '/'; foreach ($this->args as $location => $args) { $chars = str_split($args); if ($chars[0] === '-') { $tmp = explode('-', $args); $function = end($tmp); unset($tmp); // this does a check to make sure we can only // run public functions via this constructor. $check = new ReflectionMethod($this, $function); if (!$check->isPublic()) { continue; } $this->{$function}($argv[++$location]); } } }
/** * */ public function setRoute() { $segments = $this->getSegments(); $this->moduleName = isset($segments[0]) ? $segments[0] : self::DEFAULT_MODULE; $this->controllerName = isset($segments[1]) ? $segments[1] : self::DEFAULT_CONTROLLER; $this->methodName = isset($segments[2]) ? $segments[2] : self::DEFAULT_METHOD; $className = sprintf('%s\\Controller\\%s\\%s\\%s', $GLOBALS['appNameSpace'], ucwords($this->moduleName), ucwords($this->controllerName), ucwords($this->methodName)); if (class_exists($className)) { if (method_exists($className, self::FUNCTIONNAME)) { $method = new \ReflectionMethod($className, self::FUNCTIONNAME); if ($method->isPublic() && $method->getName() === self::FUNCTIONNAME) { $this->controller = new $className(); return true; } } } //退到/module/index.php $this->methodName = self::DEFAULT_METHOD; $this->controllerName = self::DEFAULT_CONTROLLER; $className = sprintf('%s\\Controller\\%s\\%s', $GLOBALS['appNameSpace'], ucwords($this->moduleName), ucwords($this->controllerName)); if (class_exists($className) && method_exists($className, self::FUNCTIONNAME)) { $this->controller = new $className(); return true; } $this->moduleName = self::DEFAULT_MODULE; $className = sprintf('%s\\Controller\\%s', $GLOBALS['appNameSpace'], ucwords($this->moduleName)); if (class_exists($className) && method_exists($className, self::FUNCTIONNAME)) { $this->controller = new $className(); return true; } if (is_null($this->controller)) { throw new \BadMethodCallException('wrong route path', -1); } }
public function __try($method) { if (!$this->app->is_admin() && $method !== 'auth') { throw new \exception('denied'); } try { if (!method_exists($this, $method)) { throw new \exception('method not found'); } else { $reflection = new \ReflectionMethod($this, $method); if (!$reflection->isPublic()) { throw new \exception('method not found'); } } $msg = call_user_func([$this, $method]); } catch (\exception $e) { if ($this->app->debug === true) { $err = $e->getMessage() . '<br/><hr>' . $e->getFile() . ' @ Line ' . $e->getLine() . '<br/><hr>STACK TRACE:<br/>' . $e->getTraceAsString(); } else { $err = $e->getMessage(); } $msg = ['error' => 1, 'message' => $err]; } echo json_encode($msg, JSON_HEX_QUOT | JSON_HEX_TAG); }
/** * @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; }
public function run() { if (!\Yii::app()->request->isAjaxRequest) { $this->throwError(\Yii::t('ajaxAction', 'We love only ajax requests.')); } $this->loadParams(); if (!($method = $this->getParam('method'))) { $this->throwError(\Yii::t('ajaxAction', 'Please send request with method.')); } $methodReflection = null; try { $methodReflection = new \ReflectionMethod($this, $method); } catch (\ReflectionException $e) { $this->throwError(\Yii::t('ajaxAction', 'The method does not exist.')); } if (!$methodReflection->isPublic()) { $this->throwError(\Yii::t('ajaxAction', 'The method does not exist.')); } else { try { $methodReflection->invokeArgs($this, $this->getMethodParams($methodReflection)); } catch (AjaxException $e) { $this->throwError($e->getMessage(), $e->getCode()); } } $this->sendResponse(); }
/** * 运行应用 * @access private */ private static function start() { //控制器实例 $controller = controller(CONTROLLER); //控制器不存在 if (!$controller) { //模块检测 if (!is_dir(MODULE_PATH)) { _404('模块' . MODULE . '不存在'); } //空控制器 $controller = Controller("Empty"); if (!$controller) { _404('控制器' . CONTROLLER . C("CONTROLLER_FIX") . '不存在'); } } //执行动作 try { $action = new ReflectionMethod($controller, ACTION); if ($action->isPublic()) { $action->invoke($controller); } else { throw new ReflectionException(); } } catch (ReflectionException $e) { $action = new ReflectionMethod($controller, '__call'); $action->invokeArgs($controller, array(ACTION, '')); } }
/** * 运行应用 * @access private */ private static function start() { //控制器实例 $control = control(CONTROL); //控制器不存在 if (!$control) { //空控制器 $control = Control("Empty"); if (!$control) { _404('模块' . CONTROL . '不存在'); } } //执行动作 try { $method = new ReflectionMethod($control, METHOD); if ($method->isPublic()) { $method->invoke($control); } else { throw new ReflectionException(); } } catch (ReflectionException $e) { $method = new ReflectionMethod($control, '__call'); $method->invokeArgs($control, array(METHOD, '')); } }
public static function gettersToArray($object) { if (!is_object($object)) { throw new \InvalidArgumentException('$object must be an object.'); } $result = []; // Iterate over all getters. foreach (get_class_methods($object) as $method) { if (strncmp('get', $method, 3) == 0) { $reflector = new \ReflectionMethod($object, $method); if ($reflector->isPublic() && $reflector->getNumberOfParameters() == 0) { $key = lcfirst(substr($method, 3)); $value = $object->{$method}(); if (is_array($value)) { foreach ($value as &$entry) { if (is_object($entry)) { $entry = static::gettersToArray($entry); } } } $result[$key] = is_object($value) ? static::gettersToArray($value) : $value; } elseif ($object instanceof Question && $method === 'getQuestions') { for ($i = 0; $i < $object->getDimensions(); $i++) { foreach ($object->getQuestions($i) as $question) { $result['questions'][$i][] = self::gettersToArray($question); } } } } } return $result; }
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); }
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; }
private function format_controller_methods($path, $file) { $this->load->helper("url"); $controller = array(); // only show php files if (($extension = substr($file, strrpos($file, ".") + 1)) == "php") { // include the class include_once $path . "/" . $file; $parts = explode(".", $file); $class_lower = $parts["0"]; $class = ucfirst($class_lower); // check if a class actually exists if (class_exists($class) and get_parent_class($class) == "MY_Controller") { // get a list of all methods $controller["name"] = $class; $controller["path"] = base_url() . $class_lower; $controller["methods"] = array(); // get a list of all public methods foreach (get_class_methods($class) as $method) { $reflect = new ReflectionMethod($class, $method); if ($reflect->isPublic()) { // ignore some methods $object = new $class(); if (!in_array($method, $object->internal_methods)) { $method_array = array(); $method_array["name"] = $method; $method_array["path"] = base_url() . $class_lower . "/" . $method; $controller["methods"][] = $method_array; } } } } } return $controller; }
public function _run_($param = null) { if (is_null($param)) { if (method_exists($this, '_absent_')) { $this->_absent_(); } else { Router::set404(); } return; } if (method_exists($this, '_always_')) { if ($this->_always_() === false) { return; } } if ($param === '') { if (method_exists($this, '_empty_')) { $this->_empty_(); } else { Router::set404(); } } elseif (mb_substr($param, 0, 1) !== '_' && method_exists($this, $param)) { $rm = new ReflectionMethod($this, $param); if ($rm->isPublic()) { $this->{$param}(); } else { Router::set404(); } } else { Router::set404(); } }
/** * Run the application */ public function run() { // Determine the client-side path to root if (!empty($_SERVER['REQUEST_URI'])) { $this->rootPath = preg_replace('/(index\\.php)?(\\?.*)?$/', '', $_SERVER['REQUEST_URI']); if (!empty($_GET['q'])) { $this->rootPath = preg_replace('/' . preg_quote($_GET['q'], '/') . '$/', '', $this->rootPath); } } // Extract controller name, view name, action name and arguments from URL $controllerName = 'Index'; if (!empty($_GET['q'])) { $this->args = explode('/', $_GET['q']); if ($this->args) { $controllerName = str_replace(' ', '/', ucwords(str_replace('_', ' ', str_replace('-', '', array_shift($this->args))))); } if ($action = $this->args ? array_shift($this->args) : '') { $this->action = str_replace('-', '', $action); } } if (!is_file('Swiftlet/Controllers/' . $controllerName . '.php')) { $controllerName = 'Error404'; } $this->view = new View($this, strtolower($controllerName)); // Instantiate the controller $controllerName = 'Swiftlet\\Controllers\\' . basename($controllerName); $this->controller = new $controllerName($this, $this->view); // Load plugins if ($handle = opendir('Swiftlet/Plugins')) { while (($file = readdir($handle)) !== FALSE) { if (is_file('Swiftlet/Plugins/' . $file) && preg_match('/^(.+)\\.php$/', $file, $match)) { $pluginName = 'Swiftlet\\Plugins\\' . $match[1]; $this->plugins[$pluginName] = array(); foreach (get_class_methods($pluginName) as $methodName) { $method = new \ReflectionMethod($pluginName, $methodName); if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor()) { $this->plugins[$pluginName][] = $methodName; } } } } ksort($this->plugins); closedir($handle); } // Call the controller action $this->registerHook('actionBefore'); if (method_exists($this->controller, $this->action)) { $method = new \ReflectionMethod($this->controller, $this->action); if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor()) { $this->controller->{$this->action}(); } else { $this->controller->notImplemented(); } } else { $this->controller->notImplemented(); } $this->registerHook('actionAfter'); return array($this->view, $this->controller); }
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 public * * @return boolean TRUE if this method is public */ public function isPublic() { if ($this->reflectionSource instanceof ReflectionMethod) { return $this->reflectionSource->isPublic(); } else { return parent::isPublic(); } }
/** * Verifica se um método é público para o objeto em questão. * * @param object $object Objeto a ser analisado * @param string $method Método a ser verificado * @return boolean Verdadeiro para público */ function can_call_method(&$object, $method) { if (method_exists($object, $method)) { $method = new ReflectionMethod($object, $method); return $method->isPublic(); } return false; }
function isMethodIgnored(ReflectionMethod $method) { global $ignoredMethods; $methodName = $method->getName(); if ($method->isPublic() === false || in_array($methodName, $ignoredMethods) === true) { return true; } return false; }
private function _actionExists($action) { try { $method = new ReflectionMethod(get_class($this), $action); return $method->isPublic() && !$method->isConstructor(); } catch (Exception $e) { return false; } }
private static function run($classname, $action) { $module = new $classname(); $class = new \ReflectionClass($module); $method = new \ReflectionMethod($module, $action); if ($class->hasMethod($action) && $method->isPublic()) { $method->invoke($module); } }