/** * Execute requested action */ public function execute() { $method = $_SERVER['REQUEST_METHOD']; $verbs = $this->verbs(); if (isset($verbs[$this->requestMethod])) { $action = 'action' . ucfirst(mb_strtolower($verbs[$method])); $reflectionMethod = new \ReflectionMethod($this, $action); $parsePath = array_slice($this->path, count($this->route)); $args = []; $errors = []; if ($params = $reflectionMethod->getParameters()) { foreach ($params as $key => $param) { if (isset($parsePath[$key])) { $args[$param->name] = $parsePath[$key]; } else { $errors[] = ['code' => 'required', 'message' => ucfirst(mb_strtolower(explode('_', $param->name)[0])) . ' cannot be blank.', 'name' => $param->name]; } } if ($errors) { throw new \phantomd\ShopCart\modules\base\HttpException(400, 'Invalid data parameters', 0, null, $errors); } } if (count($parsePath) === count($params)) { return call_user_func_array([$this, $action], $args); } } throw new HttpException(404, 'Unable to resolve the request "' . $this->requestPath . '".', 0, null, $errors); }
public function __call($name, $arguments) { $store = ucfirst($this->type) . 'Store'; $clientClass = '\\EDAM\\' . $store . '\\' . $store . 'Client'; $method = new \ReflectionMethod($clientClass, $name); $params = array(); foreach ($method->getParameters() as $param) { $params[] = $param->name; } $client = $this->getThriftClient(); if (count($params) == count($arguments)) { return call_user_func_array(array($client, $name), $arguments); } elseif (in_array('authenticationToken', $params)) { $newArgs = array(); foreach ($method->getParameters() as $idx => $param) { if ($param->name == 'authenticationToken') { $newArgs[] = $this->token; } if ($idx < count($arguments)) { $newArgs[] = $arguments[$idx]; } } return call_user_func_array(array($client, $name), $newArgs); } else { return call_user_func_array(array($client, $name), $arguments); } }
private function createClassDefinition() { $fullClassName = $this->getClass(); if (class_exists($fullClassName)) { return; } $parts = explode('\\', $fullClassName); $shortName = array_pop($parts); $namespace = implode('\\', $parts); $properties = []; $parameters = []; $body = []; $getters = []; foreach ($this->method->getParameters() as $parameter) { $name = $parameter->getName(); $parameters[] = '$' . $name . ($parameter->isDefaultValueAvailable() ? ' = ' . var_export($parameter->getDefaultValue(), true) : ''); $body[] = '$this->' . $name . ' = $' . $name . ';'; $properties[] = 'private $' . $name . ';'; $hint = null; $matches = []; if ($parameter->getClass()) { $hint = $parameter->getClass()->getName(); } else { if (preg_match('/@param\\s+(\\S+)\\s+\\$' . $name . '/', $this->method->getDocComment(), $matches)) { $hint = $matches[1]; } } $getters[] = ($hint ? "/**\n * @return " . $hint . "\n */\n " : '') . 'function get' . ucfirst($name) . '() { return $this->' . $name . '; }'; } $code = ($namespace ? "namespace {$namespace};\n" : '') . "class {$shortName} {\n" . ' ' . implode("\n ", $properties) . "\n" . ' function __construct(' . implode(', ', $parameters) . ") {\n" . ' ' . implode("\n ", $body) . "\n" . ' }' . "\n" . ' ' . implode("\n ", $getters) . "\n" . '}'; eval($code); }
/** * Fills out partially available parameters * * @param array $parameters Available values indexed by name * @return array Filled values indexed by name */ public function fill(array $parameters) { foreach ($this->method->getParameters() as $parameter) { if ($parameter->isDefaultValueAvailable() && !array_key_exists($parameter->name, $parameters)) { $parameters[$parameter->name] = $parameter->getDefaultValue(); } } return $parameters; }
public function __construct(Controller $controller, $action) { $this->controller = $controller; $this->name = $action; $this->reflector = new \ReflectionMethod($controller, $action); $this->docComment = $this->reflector->getDocComment(); $this->parameters = $this->reflector->getParameters(); $this->initializeAttributes(); }
/** * @return DependencyContainer */ private function collectDependencies() { $dependencies = new DependencyContainer(); if (!$this->invokableReflection) { return $dependencies; } foreach ($this->invokableReflection->getParameters() as $parameter) { $dependencies->addDependency($parameter); } return $dependencies; }
/** * Exports the PHP code * * @return string */ public function exportCode() { $modifiers = \Reflection::getModifierNames($this->_method->getModifiers()); $params = array(); // Export method's parameters foreach ($this->_method->getParameters() as $param) { $reflection_parameter = new ReflectionParameter($param); $params[] = $reflection_parameter->exportCode(); } return sprintf('%s function %s(%s) {}', join(' ', $modifiers), $this->_method->getName(), join(', ', $params)); }
public function setUp() { $class = DummyService::class; $method = 'dummyMethod'; $this->method = new \ReflectionMethod($class, $method); $this->params = $this->method->getParameters(); $this->normalizer = new ParamsDenormalizer(); $propertyNormalizer = new PropertyNormalizer(); $mixedDenormalizer = new MixedDenormalizer(); $serializer = new Serializer([$this->normalizer, $propertyNormalizer, $mixedDenormalizer]); $this->normalizer->setSerializer($serializer); }
public function getOptions() { $params = $this->reflection->getParameters(); if (empty($params)) { return []; } $param = end($params); if (!$param->isDefaultValueAvailable()) { return []; } if (!$this->isAssoc($param->getDefaultValue())) { return []; } return $param->getDefaultValue(); }
/** * @covers gzip_file::open_archive * @todo Implement testopen_archive(). */ public function testopen_archive() { $methods = get_class_methods($this->object); $this->assertTrue(in_array('open_archive', $methods), 'exists method open_archive'); $r = new ReflectionMethod('gzip_file', 'open_archive'); $params = $r->getParameters(); }
/** * @param object $object an object or classname * @param string $method the method which we want to inspect */ public function reflect($object, $method) { $reflection = new \ReflectionMethod($object, $method); $docs = $reflection->getDocComment(); // extract everything prefixed by @ and first letter uppercase preg_match_all('/@([A-Z]\\w+)/', $docs, $matches); $this->annotations = $matches[1]; // extract type parameter information preg_match_all('/@param\\h+(?P<type>\\w+)\\h+\\$(?P<var>\\w+)/', $docs, $matches); $this->types = array_combine($matches['var'], $matches['type']); foreach ($reflection->getParameters() as $param) { // extract type information from PHP 7 scalar types and prefer them // over phpdoc annotations if (method_exists($param, 'getType')) { $type = $param->getType(); if ($type !== null) { $this->types[$param->getName()] = (string) $type; } } if ($param->isOptional()) { $default = $param->getDefaultValue(); } else { $default = null; } $this->parameters[$param->name] = $default; } }
/** * 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}(); } }
/** * @param \ReflectionMethod $method * @return mixed|string */ public function build(\ReflectionMethod $method) { $functionDefinition = file_get_contents(__DIR__ . '/template/Function.php.template'); $functionDefinition = str_replace('%name%', $method->getName(), $functionDefinition); $arguments = ''; // TODO I guess this won't cut it if (substr($method->getName(), 0, 2) !== '__') { foreach ($method->getParameters() as $parameter) { $type = ''; if ($parameter->getClass() !== null) { $type = $parameter->getClass()->getName(); } elseif ($parameter->isArray()) { $type = 'array'; } $default = ''; if ($parameter->isDefaultValueAvailable()) { if (null === $parameter->getDefaultValue()) { $default = '= NULL'; } else { $default = sprintf("='%s'", $parameter->getDefaultValue()); } } elseif ($parameter->isOptional()) { // Workaround for optional parameters of internal methods $default = '= NULL'; } $arguments .= sprintf('%s $%s %s ,', $type, $parameter->getName(), $default); } $arguments = rtrim($arguments, ','); } $functionDefinition = str_replace('%arguments%', $arguments, $functionDefinition); return $functionDefinition; }
private function dumpMethodParameters($className, MethodInjection $methodInjection) { $methodReflection = new \ReflectionMethod($className, $methodInjection->getMethodName()); $args = []; $definitionParameters = $methodInjection->getParameters(); foreach ($methodReflection->getParameters() as $index => $parameter) { if (array_key_exists($index, $definitionParameters)) { $value = $definitionParameters[$index]; if ($value instanceof EntryReference) { $args[] = sprintf('$%s = get(%s)', $parameter->getName(), $value->getName()); } else { $args[] = sprintf('$%s = %s', $parameter->getName(), var_export($value, true)); } continue; } // If the parameter is optional and wasn't specified, we take its default value if ($parameter->isOptional()) { try { $value = $parameter->getDefaultValue(); $args[] = sprintf('$%s = (default value) %s', $parameter->getName(), var_export($value, true)); continue; } catch (ReflectionException $e) { // The default value can't be read through Reflection because it is a PHP internal class } } $args[] = sprintf('$%s = #UNDEFINED#', $parameter->getName()); } return implode(PHP_EOL . ' ', $args); }
/** * Executes a method of an object with the supplied named parameters. * This method is internally used. * @param mixed $object the object whose method is to be executed * @param ReflectionMethod $method the method reflection * @param array $params the named parameters * @return boolean whether the named parameters are valid * @since 1.1.7 */ protected function runWithParamsInternal($object, $method, $params) { $ps = array(); foreach ($method->getParameters() as $i => $param) { $name = $param->getName(); if (isset($params[$name])) { if ($param->isArray()) { $ps[] = is_array($params[$name]) ? $params[$name] : array($params[$name]); } else { if (!is_array($params[$name])) { $ps[] = $params[$name]; } else { return false; } } } else { if ($param->isDefaultValueAvailable()) { $ps[] = $param->getDefaultValue(); } else { return false; } } } $method->invokeArgs($object, $ps); return true; }
public function getMethodParameters(\ReflectionMethod $method, array $aliases = array()) { $params = $method->getParameters(); // We are done if the method has no parameters if (0 === count($params)) { return array(); } $parameters = array(); /* @var $param \ReflectionParameter */ foreach ($params as $param) { $paramName = $param->getName(); $parameters[$paramName] = array(); if (isset($aliases[$paramName]) && array_key_exists('value', $aliases[$paramName])) { $parameters[$paramName]['value'] = $aliases[$paramName]['value']; continue; } $class = $param->getClass(); if (null === $class) { if ($param->isOptional()) { $parameters[$paramName]['value'] = $param->getDefaultValue(); continue; } $parameters[$paramName]['class'] = null; continue; } $parameters[$paramName]['class'] = $class->getName(); if (isset($aliases[$paramName]['class'])) { $parameters[$paramName]['class'] = $aliases[$paramName]['class']; } } return $parameters; }
/** * @param Action $action * @param Request $request * @return array * @throws \Exception */ protected function _extractActionParameters(Action $action, Request $request) { $reflectionMethod = new \ReflectionMethod($action->getControllerName(), $action->getMethodName()); $parameters = []; foreach ($reflectionMethod->getParameters() as $parameter) { $parameterClass = $parameter->getClass(); if ($parameterClass) { if (is_a($parameterClass->getName(), '\\Wrestler\\Http\\Request\\RouteParams', true)) { $parameters[] = $parameterClass->newInstance($action->getRouteParams()); continue; } if (is_a($parameterClass->getName(), '\\Wrestler\\Http\\Request\\PostData', true)) { $parameters[] = $parameterClass->newInstance($request->getPostData()); continue; } if (is_a($parameterClass->getName(), '\\Wrestler\\Http\\Request\\Query', true)) { $parameters[] = $parameterClass->newInstance($request->getQuery()); continue; } if (is_a($parameterClass->getName(), '\\Wrestler\\Http\\Request\\Headers', true)) { $parameters[] = $parameterClass->newInstance($request->getHeaders()); continue; } } $variable = $parameter->getName(); if ($parameterClass) { $variable = $parameterClass->getName() . ' ' . $variable; } throw new \Exception("Cannot map `{$variable}`"); } return $parameters; }
/** * Binds the parameters to the action. * This method is invoked by [[\yii\base\Action]] when it begins to run with the given parameters. * This method will check the parameter names that the action requires and return * the provided parameters according to the requirement. If there is any missing parameter, * an exception will be thrown. * @param \yii\base\Action $action the action to be bound with parameters * @param array $params the parameters to be bound to the action * @return array the valid parameters that the action can run with. * @throws HttpException if there are missing or invalid parameters. */ public function bindActionParams($action, $params) { if ($action instanceof InlineAction) { $method = new \ReflectionMethod($this, $action->actionMethod); } else { $method = new \ReflectionMethod($action, 'run'); } $args = []; $missing = []; $actionParams = []; foreach ($method->getParameters() as $param) { $name = $param->getName(); if (array_key_exists($name, $params)) { if ($param->isArray()) { $args[] = $actionParams[$name] = is_array($params[$name]) ? $params[$name] : [$params[$name]]; } elseif (!is_array($params[$name])) { $args[] = $actionParams[$name] = $params[$name]; } else { throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', ['param' => $name])); } unset($params[$name]); } elseif ($param->isDefaultValueAvailable()) { $args[] = $actionParams[$name] = $param->getDefaultValue(); } else { $missing[] = $name; } } if (!empty($missing)) { throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', ['params' => implode(', ', $missing)])); } $this->actionParams = $actionParams; return $args; }
public function getMethod($filePath, $ext = '') { $fileName = dirname($filePath); $className = basename(dirname(dirname($filePath))); if (!class_exists($className)) { helper::import($fileName); } $methodName = basename($filePath); $method = new ReflectionMethod($className . $ext, $methodName); $data = new stdClass(); $data->startLine = $method->getStartLine(); $data->endLine = $method->getEndLine(); $data->comment = $method->getDocComment(); $data->parameters = $method->getParameters(); $data->className = $className; $data->methodName = $methodName; $data->fileName = $fileName; $data->post = false; $file = file($fileName); for ($i = $data->startLine - 1; $i <= $data->endLine; $i++) { if (strpos($file[$i], '$this->post') or strpos($file[$i], 'fixer::input') or strpos($file[$i], '$_POST')) { $data->post = true; } } return $data; }
/** * Binds the parameters to the action. * This method is invoked by [[Action]] when it begins to run with the given parameters. * This method will first bind the parameters with the [[options()|options]] * available to the action. It then validates the given arguments. * @param \yii\base\Action $action The action To be bound with parameters. * @param array $params The parameters to be bound to the action. * @return array the valid parameters that the action can run with. * @throws \Exception If there are unknown options or missing arguments. */ public function bindActionParams($action, $params) { $this->_params = $params; if ($action instanceof InlineAction) { $method = new \ReflectionMethod($this, $action->actionMethod); } else { $method = new \ReflectionMethod($action, 'run'); } $args = []; $missing = []; foreach ($method->getParameters() as $i => $param) { /* @var $param \ReflectionParameter */ $name = $param->getName(); if (isset($params[$name])) { if ($param->isArray() && !is_array($params[$name])) { $args[] = preg_split('/\\s*,\\s*/', $params[$name]); } else { $args[] = $params[$name]; } } else { if ($param->isDefaultValueAvailable()) { $args[] = $param->getDefaultValue(); } else { $missing[] = $name; } } } if (!empty($missing)) { throw new \Exception(\Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)])); } return $args; }
public function run() { $response = new Response(); $action = $this->request->query()->get('action', 'home'); try { $arguments = array(); $method = new \ReflectionMethod($this->controller, "{$action}Action"); foreach ($method->getParameters() as $param) { /** Setting parameters by name from request */ $arguments[] = $this->request->query()->get($param->getName()); } $this->controller->setResponse($response); $content = $method->invokeArgs($this->controller, $arguments); /** direct response instances do not require layout and are sent immediately */ if ($content instanceof Response) { return $content; } /** two-step view implementation, classic to most of MVC frameworks */ ob_start(); include 'Resources/layout/main.phtml'; $content = ob_get_clean(); $response->setContent($content); } catch (\ReflectionException $e) { $response->setStatusCode(404)->setContent($e->getMessage()); } return $response; }
public function onKernelController(FilterControllerEvent $event) { if (!is_array($controller = $event->getController())) { return; } $request = $event->getRequest(); if (!($configuration = $request->attributes->get('_acl_permission'))) { return; } $refl = new \ReflectionMethod($controller[0], $controller[1]); foreach ($refl->getParameters() as $param) { if (!$param->getClass() || $param->getClass()->isInstance($request)) { continue; } $name = $param->getName(); $object = $request->get($name); if (is_null($object)) { continue; } $mask = null; foreach ($configuration as $config) { if (!is_null($mask = $config->getEntry($name))) { continue; } } if (is_null($mask)) { continue; } if (!$this->manager->isGranted($mask, $object)) { throw new AccessDeniedException('Acl permission for this object is not granted.'); } } }
/** * @param object $object an object or classname * @param string $method the method which we want to inspect */ public function reflect($object, $method) { $reflection = new \ReflectionMethod($object, $method); $docs = $reflection->getDocComment(); // extract everything prefixed by @ and first letter uppercase preg_match_all('/@([A-Z]\\w+)/', $docs, $matches); $this->annotations = $matches[1]; // extract type parameter information preg_match_all('/@param\\h+(?P<type>\\w+)\\h+\\$(?P<var>\\w+)/', $docs, $matches); // this is just a fix for PHP 5.3 (array_combine raises warning if called with // two empty arrays if ($matches['var'] === array() && $matches['type'] === array()) { $this->types = array(); } else { $this->types = array_combine($matches['var'], $matches['type']); } // get method parameters foreach ($reflection->getParameters() as $param) { if ($param->isOptional()) { $default = $param->getDefaultValue(); } else { $default = null; } $this->parameters[$param->name] = $default; } }
/** * Returns the parameters of the method as ezcReflectionParameter objects * * @return ezcReflectionParameter[] Parameters of the method * @since PHP 5.1.0 */ function getParameters() { $params = $this->docParser->getParamAnnotations(); $extParams = array(); if ($this->reflectionSource instanceof ReflectionMethod) { $apiParams = $this->reflectionSource->getParameters(); } else { $apiParams = parent::getParameters(); } foreach ($apiParams as $param) { $type = null; foreach ($params as $annotation) { if ($annotation instanceof ezcReflectionAnnotationParam and $annotation->getParamName() == $param->getName()) { $type = $annotation->getTypeName(); break; } } if ($this->reflectionSource instanceof ReflectionMethod) { $extParams[] = new ezcReflectionParameter(null, $param, $type); } else { // slightly increase performance and save some memory $extParams[] = new ezcReflectionParameter(array($this->getDeclaringClass()->getName(), $this->getName()), $param->getPosition(), $type); } } return $extParams; }
public function getHtmlData() { $htmlDataString = ""; foreach (get_class_methods(get_called_class()) as $method) { if (substr($method, 0, 3) == "get" && $method != "getHtmlData" && $method != "getPK") { $ref = new ReflectionMethod($this, $method); if (sizeOf($ref->getParameters()) == 0) { $field = strtolower(substr($method, 3)); $value = $this->{$method}(); if (is_object($value)) { if (get_class($value) != "Doctrine\\ORM\\PersistentCollection") { $field = "id{$field}"; $pkGetter = "get" . $field; $value = $value->{$pkGetter}(); $data = "data-{$field}=\"" . $value . "\" "; $htmlDataString .= $data; } } else { $data = "data-{$field}=\"" . $value . "\" "; $htmlDataString .= $data; } } } } return $htmlDataString . " data-crud=" . get_called_class() . " data-string=" . $this; }
/** * @covers PMException::__toString * @todo Implement test__toString(). */ public function test__toString() { $methods = get_class_methods($this->object); $this->assertTrue(in_array('__toString', $methods), 'exists method __toString'); $r = new ReflectionMethod('PMException', '__toString'); $params = $r->getParameters(); }
/** * Actual routing + sanitizing data * * @param $class * @param array $params */ public static function connect($namespace, $class, $params = array()) { $defaults = array('indexPage' => 'index', 'loginPage' => false, 'loginRedirect' => false); static::$class = strtolower($class); $class = $namespace . '\\' . $class; $params += $defaults; extract($params); // Authenticated controllers if ($loginPage) { Auth::checkLogin($loginRedirect, $loginPage); } $method = $indexPage; $parameters = array(); if (isset($_SERVER[URI_INFO])) { $url = explode('/', substr($_SERVER[URI_INFO], 1)); array_shift($url); if ($url) { foreach ($url as $key => $element) { if (!$key && !is_numeric($element)) { $method = $element; } else { $parameters[] = $element; } } } } // Check availability try { $methodInfo = new \ReflectionMethod($class, $method); // Methods that start with _ are not accesible from browser $name = $methodInfo->getName(); if ($name[0] == '_') { $method = $indexPage; } $methodParams = $methodInfo->getParameters(); // Force cast parameters by arguments default value if ($methodParams) { foreach ($methodParams as $parameterKey => $parameterValue) { try { $defaultValue = $parameterValue->getDefaultValue(); $type = gettype($defaultValue); if ($defaultValue) { unset($methodParams[$parameterKey]); } // settype($parameters[$parameterKey], $type); } catch (\Exception $e) { continue; } } } // if(count($methodParams) != count($parameters)) { // $parameters = array(); // } } catch (\Exception $e) { $method = $indexPage; } static::$method = $method; call_user_func_array($class . '::' . $method, $parameters); return; }
/** * @covers wsResponse::getPayloadArray * @todo Implement testgetPayloadArray(). */ public function testgetPayloadArray() { $methods = get_class_methods($this->object); $this->assertTrue(in_array('getPayloadArray', $methods), 'exists method getPayloadArray'); $r = new ReflectionMethod('wsResponse', 'getPayloadArray'); $params = $r->getParameters(); }
/** * @internal * * @param Oxygen_Http_Request $request * @param Oxygen_Util_RequestData $requestData * @param string $className * @param string $method * @param array $actionParameters * * @return Oxygen_Http_Response * @throws Oxygen_Exception */ public function handleRaw($request, $requestData, $className, $method, array $actionParameters) { $reflectionMethod = new ReflectionMethod($className, $method); $parameters = $reflectionMethod->getParameters(); $arguments = array(); foreach ($parameters as $parameter) { if (isset($actionParameters[$parameter->getName()])) { $arguments[] = $actionParameters[$parameter->getName()]; } else { if (!$parameter->isOptional()) { throw new Oxygen_Exception(Oxygen_Exception::ACTION_ARGUMENT_NOT_PROVIDED); } $arguments[] = $parameter->getDefaultValue(); } } if (is_subclass_of($className, 'Oxygen_Container_ServiceLocatorAware')) { $instance = call_user_func(array($className, 'createFromContainer'), $this->container); } else { $instance = new $className(); } $result = call_user_func_array(array($instance, $method), $arguments); if (is_array($result)) { $result = $this->convertResultToResponse($request, $requestData, $result); } elseif (!$result instanceof Oxygen_Http_Response) { throw new LogicException(sprintf('An action should return array or an instance of Oxygen_Http_Response; %s gotten.', gettype($result))); } return $result; }
/** * @param \ReflectionMethod $method */ public function __construct(ClassSymbol $class, \ReflectionMethod $method) { $this->classSymbol = $class; $this->reflectionMethod = $method; $this->parameters = $method->getParameters(); $this->handle = $method->getName(); }