/**
  * 
  * @global array $config
  * @param string $class naziv kotrolera koji se instancira
  * @param string $method metod koji se poziva
  * @param array $params parametri metode
  */
 public static function loadController($controller, $method, $params = array())
 {
     global $config;
     $path_to_controller = realpath("controllers/" . strtolower($controller) . "Controller.php");
     if (file_exists($path_to_controller)) {
         include_once $path_to_controller;
         $controller = strtolower($controller) . "Controller";
         $controller_instance = new $controller();
         if (!is_subclass_of($controller_instance, 'baseController')) {
             echo $config['Poruke']['noBaseCont'];
             die;
         }
         if (method_exists($controller_instance, $method)) {
             $refl = new ReflectionMethod(get_class($controller_instance), $method);
             $numParams = $refl->getNumberOfParameters();
             if ($numParams > 0 && count($params) < $numParams) {
                 echo $config['Poruke']['noParams'];
                 die;
             }
             call_user_func_array(array($controller_instance, $method), $params);
         } else {
             echo $config['Poruke']['noMethod'];
         }
     } else {
         echo $config['Poruke']['error404'];
     }
 }
Example #2
0
 public function dispatch()
 {
     $acao = self::sulfixo_controle . $this->paginaSolicitada;
     if (method_exists($this, $acao)) {
         $reflection = new ReflectionMethod($this, $acao);
         $qtdArgumentos = $reflection->getNumberOfParameters();
         $parametros = array();
         $i = 0;
         foreach ($_GET as $key => $value) {
             if (!empty($value) && $key != 'a' && $i <= $qtdArgumentos) {
                 $parametros[$i] = $value;
             }
             $i++;
         }
         if (count($parametros) < $qtdArgumentos) {
             $i = $qtdArgumentos - count($parametros);
             for ($index = 0; $index < $i; $index++) {
                 $parametros[$index + count($parametros) + 1] = '';
             }
         }
         call_user_func_array(array($this, $acao), $parametros);
     } else {
         $this->erro_404();
     }
 }
Example #3
0
 public static function run()
 {
     $currentPath = substr($_SERVER['REQUEST_URI'], 44);
     $currentMethod = $_SERVER['REQUEST_METHOD'];
     if (strpos($currentPath, '?') !== false) {
         $currentPath = explode('?', $currentPath);
         $currentPath = $currentPath[0];
     }
     foreach (static::$routes as $value) {
         $matches[] = array();
         if (preg_match($value['path'], $currentPath, $matches) === 0) {
             continue;
         }
         if ($currentMethod !== $value['method']) {
             continue;
         }
         unset($matches[0]);
         $controller = new $value['class']();
         $info = new \ReflectionMethod($controller, $value['function']);
         if ($info->getNumberOfParameters() !== count($matches)) {
             throw new \Exception('Numero de parametros incorrecto: ' . $value['class'] . '::' . $value['function']);
         }
         $response = $info->invokeArgs($controller, $matches);
         if (is_null($response)) {
             return;
         }
         if ($response instanceof View) {
             Response::view($response);
         }
         return;
     }
     // Lanzar 404
     App::abort(404, 'No se encuentra la ruta');
 }
Example #4
0
 /**
  * @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;
 }
Example #5
0
 /**
  * Runs the action.
  * The action method defined in the controller is invoked.
  * This method is required by {@link CAction}.
  */
 public function run()
 {
     $controller = $this->getController();
     $methodName = 'action' . $this->getId();
     $method = new ReflectionMethod($controller, $methodName);
     if (($n = $method->getNumberOfParameters()) > 0) {
         $params = array();
         foreach ($method->getParameters() as $i => $param) {
             $name = $param->getName();
             if (isset($_GET[$name])) {
                 if ($param->isArray()) {
                     $params[] = is_array($_GET[$name]) ? $_GET[$name] : array($_GET[$name]);
                 } else {
                     if (!is_array($_GET[$name])) {
                         $params[] = $_GET[$name];
                     } else {
                         throw new CHttpException(400, Yii::t('yii', 'Your request is invalid.'));
                     }
                 }
             } else {
                 if ($param->isDefaultValueAvailable()) {
                     $params[] = $param->getDefaultValue();
                 } else {
                     throw new CHttpException(400, Yii::t('yii', 'Your request is invalid.'));
                 }
             }
         }
         $method->invokeArgs($controller, $params);
     } else {
         $controller->{$methodName}();
     }
 }
Example #6
0
 /**
  * Call this method to load all rules
  */
 public function loadRules()
 {
     $this->rules = [];
     foreach (get_class_methods($this) as $rule) {
         if (mb_substr($rule, 0, 6) === 'rule__') {
             $name = mb_substr($rule, 6);
             $method = new \ReflectionMethod($this, $rule);
             if (!$method->getNumberOfParameters() === 3) {
                 //the method expects too much/less arguments
                 $this->errorHandler->log('methods', "The method \"{$name}\" expects " . $method->getNumberOfParameters() . " but it should expect 3 arguments.");
                 continue;
             }
             $this->rules[] = ['name' => $name, 'class' => $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;
 }
Example #8
0
 public function __construct($class, $method)
 {
     parent::__construct();
     $ref = new ReflectionMethod($class, $method);
     $this->_ref = $ref;
     $this->_args = $ref->getParameters();
     $this->_args_cnt = $ref->getNumberOfParameters();
 }
 public function testSearchMethod()
 {
     $et = new ExactTarget("", "");
     $this->assertTrue(method_exists('ExactTarget', 'search'), "search method exists");
     $method = new ReflectionMethod('ExactTarget', 'search');
     $num = $method->getNumberOfParameters();
     $this->assertEquals(2, $num, "has 2 function argument");
 }
Example #10
0
 /**
  * Returns the number of parameters
  *
  * @return integer The number of parameters
  * @since PHP 5.0.3
  */
 public function getNumberOfParameters()
 {
     if ($this->reflectionSource instanceof ReflectionMethod) {
         return $this->reflectionSource->getNumberOfParameters();
     } else {
         return parent::getNumberOfParameters();
     }
 }
Example #11
0
 /**
  * @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);
 }
Example #12
0
 public function runWithParams($params)
 {
     $method = new ReflectionMethod($this, 'run');
     if ($method->getNumberOfParameters() > 0) {
         return $this->runWithParamsInternal($this, $method, $params);
     } else {
         return $this->run();
     }
 }
 public function setDefaultOptions(OptionsResolverInterface $resolver)
 {
     $resolver->setRequired(array('fields'));
     $reflection = new \ReflectionMethod($resolver, 'setAllowedTypes');
     if ($reflection->getNumberOfParameters() === 2) {
         $resolver->setAllowedTypes('fields', 'array');
     } else {
         $resolver->setAllowedTypes(array('fields' => 'array'));
     }
 }
Example #14
0
 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;
 }
Example #15
0
 /**
  * Выполняет действие с переданными параметрами запроса. Данный метод
  * вызывается методом {@link CController::runAction()}
  * @param array $params параметры запроса (имя => значение)
  * @return boolean верны ли параметры запроса
  * @since 1.1.7
  */
 public function runWithParams($params)
 {
     $methodName = 'action' . $this->getId();
     $controller = $this->getController();
     $method = new ReflectionMethod($controller, $methodName);
     if ($method->getNumberOfParameters() > 0) {
         return $this->runWithParamsInternal($controller, $method, $params);
     } else {
         return $controller->{$methodName}();
     }
 }
 private function _execute_add_action_methods()
 {
     foreach (get_class_methods($this) as $method) {
         if (Strings::position($method, 'add_action_') === 0 || Strings::position($method, 'add_filter_') === 0) {
             $action_name = str_replace(['add_filter_', 'add_action_'], '', $method);
             $reflection = new \ReflectionMethod($this, $method);
             $params_count = $reflection->getNumberOfParameters();
             add_filter($action_name, [$this, $method], 10, $params_count);
         }
     }
 }
Example #17
0
 public function _empty($name, $args)
 {
     require_once APP_PATH . CONTROLLER_NAME . '/' . 'Controller' . '/' . CONTROLLER_NAME . 'Controller.class.php';
     $controller = A('Admin/' . CONTROLLER_NAME);
     $action = ACTION_NAME;
     try {
         $method = new \ReflectionMethod($controller, $name);
         // URL参数绑定检测
         if ($method->getNumberOfParameters() > 0 && C('URL_PARAMS_BIND')) {
             switch ($_SERVER['REQUEST_METHOD']) {
                 case 'POST':
                     $vars = array_merge($_GET, $_POST);
                     break;
                 case 'PUT':
                     parse_str(file_get_contents('php://input'), $vars);
                     break;
                 default:
                     $vars = $_GET;
             }
             $params = $method->getParameters();
             $paramsBindType = C('URL_PARAMS_BIND_TYPE');
             foreach ($params as $param) {
                 $name = $param->getName();
                 if (1 == $paramsBindType && !empty($vars)) {
                     $args[] = array_shift($vars);
                 } elseif (0 == $paramsBindType && isset($vars[$name])) {
                     $args[] = $vars[$name];
                 } elseif ($param->isDefaultValueAvailable()) {
                     $args[] = $param->getDefaultValue();
                 } else {
                     E(L('_PARAM_ERROR_') . ':' . $name);
                 }
             }
             // 开启绑定参数过滤机制
             if (C('URL_PARAMS_SAFE')) {
                 array_walk_recursive($args, 'filter_exp');
                 $filters = C('URL_PARAMS_FILTER') ?: C('DEFAULT_FILTER');
                 if ($filters) {
                     $filters = explode(',', $filters);
                     foreach ($filters as $filter) {
                         $args = array_map_recursive($filter, $args);
                         // 参数过滤
                     }
                 }
             }
             $method->invokeArgs($controller, $args);
         } else {
             $method->invoke($controller);
         }
     } catch (\ReflectionException $e) {
         $this->error('404,您访问的页面不存在。');
     }
 }
 /**
  * Hydrate an entity object from  a source
  *
  * @param type          $entity is the entity we want to populate
  * @param \stdClass     $object is the source of datas
  * @param EntityManager $em     The entity manager
  *
  * @return \PhraseanetSDK\Entity\EntityInterface
  */
 public static function hydrate(EntityInterface $entity, \stdClass $object, EntityManager $em)
 {
     $className = get_class($entity);
     $reflectionClass = new \ReflectionClass($className);
     foreach (get_object_vars($object) as $propertyName => $propertyValue) {
         $methodName = self::camelize(sprintf('set%s', ucfirst($propertyName)));
         if ($reflectionClass->hasMethod($methodName)) {
             $reflectionMethod = new \ReflectionMethod($className, $methodName);
             if ($reflectionMethod->getNumberOfParameters() > 0) {
                 $parameters = $reflectionMethod->getParameters();
                 if (is_scalar($propertyValue)) {
                     foreach ($parameters as $parameter) {
                         /* @var $parameter \ReflectionParameter */
                         if (null === $parameter->getClass()) {
                             $entity->{$methodName}($propertyValue);
                         } elseif ('DateTime' === $parameter->getClass()->getName()) {
                             $date = \DateTime::createFromFormat(\DateTime::ATOM, $propertyValue, new \DateTimeZone(date_default_timezone_get()));
                             $entity->{$methodName}($date);
                         }
                     }
                 } elseif (is_array($propertyValue)) {
                     $entityCollection = new ArrayCollection();
                     foreach ($propertyValue as $object) {
                         if (is_object($object)) {
                             $subEntity = self::hydrate($em->getEntity($propertyName), $object, $em);
                             $entityCollection->add($subEntity);
                         } elseif (is_scalar($object)) {
                             $entityCollection->add($object);
                         }
                     }
                     foreach ($parameters as $parameter) {
                         /* @var $parameter \ReflectionParameter */
                         if ($parameter->getClass() && $parameter->getClass()->isInstance($entityCollection)) {
                             $entity->{$methodName}($entityCollection);
                         }
                     }
                 } elseif (is_object($propertyValue)) {
                     if (!ctype_digit($propertyName)) {
                         $subEntity = self::hydrate($em->getEntity($propertyName), $propertyValue, $em);
                         foreach ($parameters as $parameter) {
                             /* @var $parameter \ReflectionParameter */
                             if ($parameter->getClass() && $parameter->getClass()->isInstance($subEntity)) {
                                 $entity->{$methodName}($subEntity);
                             }
                         }
                     }
                 }
             }
         }
     }
     return $entity;
 }
Example #19
0
 private function _callmethod($controller, $method, $args = array())
 {
     if (is_callable(array($controller, $method))) {
         $reflection = new ReflectionMethod($controller, $method);
         $argnum = $reflection->getNumberOfParameters();
         if ($argnum > count($args) + 1) {
             throw new Exception("not_found call method failed [ method name: {$method} ].");
         }
         $reflection->invokeArgs($controller, $args);
         return true;
     }
     return false;
 }
Example #20
0
 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;
     }
 }
 /**
  * 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;
 }
Example #22
0
 /**
  * @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;
     }
 }
 /**
  * Runs worker action.
  *
  * @throws CException
  * @return array hash array(controllerId, actionName)
  */
 public function run()
 {
     if (!$this->getJob() instanceof IWorkerJob) {
         throw new CException(Yii::t("worker", "Gearman job object not setted to controller action"));
     }
     $controller = $this->getController();
     $methodName = 'action' . $this->getId();
     $method = new ReflectionMethod($controller, $methodName);
     if ($method->getNumberOfParameters() == 1) {
         return $method->invokeArgs($controller, array($this->getJob()));
     } else {
         throw new CException("Controller action must contains 1 parameter");
     }
 }
Example #24
0
 /**
  * 执行请求
  * @param array $params 请求的参数数组
  * @throws \Sky\base\HttpException
  */
 public function run($params)
 {
     $controller = $this->getController();
     if (isset($_REQUEST['ws'])) {
         $methodName = 'action' . $this->getId();
         $method = new \ReflectionMethod($controller, $methodName);
         $useParamName = \Sky\Sky::$app->getUrlManager()->useParamName;
         if ($method->getNumberOfParameters() > 0) {
             if (isset($useParamName) && $useParamName === true) {
                 $result = $this->runWithParamsInternal($controller, $method, $params);
             } else {
                 $result = $this->runWithParamsOuter($controller, $method, $params);
             }
         } else {
             $result = $this->runInternal($controller, $methodName);
         }
         return $result;
         // 			if($result==false){
         // 				throw new \Sky\base\HttpException(400,'Your request is invalid.'/*.ob_get_clean()*/);
         // 			}else{
         // 				if ($controller->rawOutput) {
         // 					echo self::encode($this->getActionOutput());
         // 				}else{
         // 					if(!headers_sent())
         // 						header('Content-Type: application/json;charset=utf-8');
         // 					echo \Sky\help\JSON::encode($this->getActionOutput());
         // 				}
         // 			}
     } else {
         if ($this->id === $this->wsdl) {
             $_REQUEST['IsWsdlRequest'] = true;
         }
         $provider = $controller;
         // 			$namespace=\Sky\Sky::$app->getRequest()->getBaseUrl();
         if (($module = \Sky\Sky::$app->controller->module) === null) {
             $namespace = ltrim(\Sky\Sky::$app->getRequest()->getBaseUrl(), '\\/');
         } else {
             $namespace = $module->name;
             if (($pos = strrpos($module->name, '\\')) !== false) {
                 $namespace = substr($module->name, $pos + 1);
             }
         }
         $this->_service = new WebService($provider, $namespace);
         $this->_service->renderWsdl();
     }
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
     \Sky\Sky::$app->end();
 }
 /**
  * Runs handler action.
  *
  * @throws CException
  * @return array hash array(handlerId, actionName)
  */
 public function run()
 {
     if (!$this->getJob() instanceof IGearmanJob) {
         throw new CException(Yii::t('gearman', 'Gearman job object not setted to handler action'));
     }
     $handler = $this->getHandler();
     $methodName = 'action' . $this->getId();
     $method = new ReflectionMethod($handler, $methodName);
     if ($method->getNumberOfParameters() == 1) {
         return $method->invokeArgs($handler, array($this->getJob()));
     } else {
         throw new CException('Handler action must contains 1 parameter');
     }
 }
Example #26
0
 public static function exec()
 {
     $module = A(MODULE_NAME);
     $action = ACTION_NAME;
     try {
         if (!preg_match('/^[A-Za-z](\\w)*$/', $action)) {
             throw new ReflectionException();
         }
         $method = new ReflectionMethod($module, $action);
         if ($method->isPublic()) {
             //                $class = new ReflectionClass($module);
             switch (REQUEST_METHOD) {
                 case 'post':
                     $vars = array_merge($_POST, $_GET);
                     break;
                 case 'put':
                     parse_str(file_get_contents('php://input'), $vars);
                     break;
                 default:
                     $vars = $_GET;
                     break;
             }
             $_REQUEST = $vars;
             if ($method->getNumberOfParameters() > 0) {
                 $params = $method->getParameters();
                 foreach ($params as $param) {
                     $name = $param->getName();
                     if (isset($vars[$name])) {
                         $args[] = $vars[$name];
                     } elseif ($param->isDefaultValueAvailable()) {
                         $args[] = $param->getDefaultValue();
                     } else {
                         echo 'Error';
                     }
                 }
                 $method->invokeArgs($module, $args);
             } else {
                 $method->invoke($module);
             }
         } else {
             // 非public方法
             throw new ReflectionException();
         }
     } catch (ReflectionException $e) {
         // 引导到_call
         $method = new ReflectionMethod($module, '__call');
         $method->invokeArgs($module, array($action, ''));
         //            print_r($e);
     }
 }
Example #27
0
 /**
  * Search for public methods on an Object for display in template
  * @author Fabien Potencier
  * @author Hélio Costa e Silva <*****@*****.**>
  * @param stdObject $object
  * @param mixed $item
  * @param array $arguments
  * @param boolean $arrayOnly
  */
 protected function getAttribute($object, $item, array $arguments = array(), $arrayOnly = false)
 {
     if (is_object($object)) {
         $arrAllowedPrefixes = array('get', 'has', 'is', 'match', 'contain');
         $reflection = new ReflectionObject($object);
         foreach ($arrAllowedPrefixes as $prefix) {
             if (strpos($item, $prefix) !== 0) {
                 /* if isn't at first position, try next */
                 continue;
             }
             if ($reflection->hasMethod($item)) {
                 $reflectionMethod = new ReflectionMethod($object, $item);
                 if ($reflectionMethod->isPublic()) {
                     if ($reflectionMethod->getNumberOfParameters() > 0) {
                         return $reflectionMethod->invokeArgs($object, $arguments);
                     } else {
                         return $object->{$item}();
                     }
                 } else {
                     return null;
                 }
             }
         }
     }
     $item = (string) $item;
     if ((is_array($object) || is_object($object) && $object instanceof ArrayAccess) && isset($object[$item])) {
         return $object[$item];
     }
     if ($arrayOnly) {
         return null;
     }
     if (is_object($object) && isset($object->{$item})) {
         if ($this->env->hasExtension('sandbox')) {
             $this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item);
         }
         return $object->{$item};
     }
     /* @todo helio.costa __get __isset
      * __get() __isset() support. Still here for a while */
     if (!is_object($object) || !method_exists($object, $method = $item) && !method_exists($object, $method = 'get' . $item)) {
         return null;
     }
     if ($this->env->hasExtension('sandbox')) {
         $this->env->getExtension('sandbox')->checkMethodAllowed($object, $method);
     }
     $reflection = new ReflectionObject($object);
     if ($reflection->hasMethod('__get')) {
         return call_user_func_array(array($object, $method), $arguments);
     }
 }
 public function injectDependences(\ReflectionMethod $method, array $args = [], $byServiceKey = false) : array
 {
     $arguments = [];
     if ($method->getNumberOfParameters() > 0) {
         // Inject dependences
         foreach ($method->getParameters() as $parameter) {
             if ($byServiceKey === true) {
                 $parameterNameAsSnake = strtolower(preg_replace('/(?<=\\w)(?=[A-Z])/', "_\$1", $parameter->getName()));
             }
             $key = $parameter->getPosition();
             // Add parameter if they are given as default arguments.
             if (isset($args[$parameter->getName()]) === true) {
                 $arguments[$key] = $args[$parameter->getName()];
             } else {
                 if (isset($args[$key]) === true) {
                     $arguments[$key] = $args[$key];
                 } else {
                     if ($byServiceKey === true && $this->servicesChain->has($parameterNameAsSnake) === true) {
                         $value = $this->servicesChain->get($parameterNameAsSnake);
                         $typeReturned = gettype($value) === 'object' ? get_class($value) : gettype($value);
                         $typeExpected = (string) $parameter->getType();
                         if ($parameter->hasType() === true && $value instanceof $typeExpected === false) {
                             throw new Exception($parameterNameAsSnake . " expects a '" . $typeExpected . "' type. Services has given a '" . $typeReturned . "' type");
                         }
                         $arguments[$key] = $value;
                     } else {
                         if ($parameter->hasType() === true && $parameter->getType()->isBuiltin() === false && $this->servicesChain->has($parameter->getClass()->name) === true) {
                             $arguments[$key] = $this->servicesChain->get($parameter->getClass()->name);
                         } else {
                             if ($parameter->isDefaultValueAvailable() === true) {
                                 if ($parameter->isDefaultValueConstant() === true) {
                                     $arguments[$key] = $parameter->getDefaultValueConstantName();
                                 } else {
                                     $arguments[$key] = $parameter->getDefaultValue();
                                 }
                             } else {
                                 if ($parameter->isOptional() === true) {
                                     $arguments[$key] = null;
                                 } else {
                                     throw new \Exception("Required parameter is needed. Parameter: '" . $parameter->getName() . "' instance of '" . $parameter->getClass()->name . "'");
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $arguments;
 }
Example #29
0
 private function _call_method($class, $method, $args = array())
 {
     if (is_callable(array($class, $method))) {
         $reflection = new ReflectionMethod($class, $method);
         $argnum = $reflection->getNumberOfParameters();
         if ($argnum > count($args)) {
             throw new Exception('api.err reflection args not match', 1012);
         }
         //公共方法才允许被调用
         $reflection->invokeArgs($class, $args);
         return true;
     }
     return false;
 }
 protected function switch_off_user()
 {
     // Verify the integrity of our wrapper methods
     $target = new ReflectionFunction('switch_off_user');
     $wrapper = new ReflectionMethod(__METHOD__);
     $this->assertSame($wrapper->getNumberOfParameters(), $target->getNumberOfParameters());
     /*
      * `switch_off_user()` and the functions it subsequently calls will trigger "headers already sent" PHP errors, so
      * we need to mute them in order to avoid phpunit throwing an exception.
      */
     $this->silence();
     $user = switch_off_user();
     $this->go_forth();
     return $user;
 }