function XLLoop_reflection_handler() { try { $input = file_get_contents('php://input'); $value = json_decode($input); if ($value != NULL) { $argc = count($value->args); $args = array(); for ($i = 0; $i < $argc; $i++) { $args[$i] = XLLoop_decode($value->args[$i]); } $function = new ReflectionFunction($value->name); if ($function->isUserDefined()) { $reqArgc = $function->getNumberOfParameters(); for ($i = $argc; $i < $reqArgc; $i++) { $args[$i] = 0; } $result = $function->invokeArgs($args); $enc = XLLoop_encode($result); print json_encode($enc); } else { print json_encode(XLLoop_encode("#Function " . $value->name . "() does not exist")); } } else { print "<html><body><code>XLLoop function handler alive</code></body></html>"; } } catch (Exception $e) { print json_encode(XLLoop_encode("#" . $e->getMessage())); } }
private function shouldRun($callback, $controllerResult) { if (is_array($callback)) { $callbackReflection = new \ReflectionMethod($callback[0], $callback[1]); } elseif (is_object($callback) && !$callback instanceof \Closure) { $callbackReflection = new \ReflectionObject($callback); $callbackReflection = $callbackReflection->getMethod('__invoke'); } else { $callbackReflection = new \ReflectionFunction($callback); } if ($callbackReflection->getNumberOfParameters() > 0) { $parameters = $callbackReflection->getParameters(); $expectedControllerResult = $parameters[0]; if ($expectedControllerResult->getClass() && (!is_object($controllerResult) || !$expectedControllerResult->getClass()->isInstance($controllerResult))) { return false; } if ($expectedControllerResult->isArray() && !is_array($controllerResult)) { return false; } if (method_exists($expectedControllerResult, 'isCallable') && $expectedControllerResult->isCallable() && !is_callable($controllerResult)) { return false; } } return true; }
function add_internal($internal_classes) { global $functions, $internal_arginfo; foreach ($internal_classes as $class_name) { add_class($class_name, 0); } foreach (get_declared_interfaces() as $class_name) { add_class($class_name, \ast\flags\CLASS_INTERFACE); } foreach (get_declared_traits() as $class_name) { add_class($class_name, \ast\flags\CLASS_TRAIT); } foreach (get_defined_functions()['internal'] as $function_name) { $function = new \ReflectionFunction($function_name); $required = $function->getNumberOfRequiredParameters(); $optional = $function->getNumberOfParameters() - $required; $functions[strtolower($function_name)] = ['file' => 'internal', 'avail' => true, 'conditional' => false, 'flags' => 0, 'lineno' => 0, 'endLineno' => 0, 'name' => $function_name, 'docComment' => '', 'required' => $required, 'optional' => $optional, 'ret' => null, 'params' => []]; add_param_info($function_name); } foreach (array_keys($internal_arginfo) as $function_name) { if (strpos($function_name, ':') !== false) { continue; } $ln = strtolower($function_name); $functions[$ln] = ['file' => 'internal', 'avail' => false, 'conditional' => false, 'flags' => 0, 'lineno' => 0, 'endLineno' => 0, 'name' => $function_name, 'docComment' => '', 'ret' => null, 'params' => []]; add_param_info($function_name); } }
/** * Returns the number of parameters * * @return integer The number of parameters * @since PHP 5.0.3 */ public function getNumberOfParameters() { if ($this->reflectionSource instanceof ReflectionFunction) { return $this->reflectionSource->getNumberOfParameters(); } else { return parent::getNumberOfParameters(); } }
public function testClosureHasSameParameters() { $expected = new \ReflectionFunction($this->closure); $actual = new \ReflectionFunction($this->unserializeClosure()->getClosure()); $this->assertEquals($expected->getNumberOfRequiredParameters(), $actual->getNumberOfRequiredParameters()); $this->assertEquals($expected->getNumberOfParameters(), $actual->getNumberOfParameters()); $this->assertEquals($expected->getParameters(), $actual->getParameters()); }
/** * Hash anything, return the unique identity. * * @param $object * @return string */ protected function hash($object) { array_walk_recursive($object, function (&$item) { if ($item instanceof \Closure) { $reflection = new \ReflectionFunction($item); $item = serialize($reflection->getClosureScopeClass()) . $reflection->getNumberOfParameters() . $reflection->getNamespaceName() . $reflection->getStartLine() . $reflection->getEndLine(); } }); return md5(serialize($object)); }
public function displayGridValue($row, Field $field) { $value = null; $fieldName = $field->getFieldName(); if (array_key_exists($fieldName, $row)) { $value = $row[$fieldName]; } // real treatment if (is_callable($field->getFormatValueCallback())) { $callback = $field->getFormatValueCallback(); $reflection = new \ReflectionFunction($callback); if ($reflection->getNumberOfParameters() == 1) { $value = $callback($value); } elseif ($reflection->getNumberOfParameters() == 2) { $value = $callback($value, $row); } else { throw new DataGridException("Wrong number of parameters in the callback for field " . $field->getFieldName()); } } // send event for changing grid query builder $event = new DataGridEvent(); $event->set("value", $value); $event->set("row", $row); $event->set("field", $field); $this->dispatcher->dispatch(KitpagesDataGridEvents::ON_DISPLAY_GRID_VALUE_CONVERSION, $event); if (!$event->isDefaultPrevented()) { $value = $event->get("value"); if ($value instanceof \DateTime) { $returnValue = $value->format("Y-m-d H:i:s"); } else { $returnValue = $value; } $event->set("returnValue", $returnValue); } $this->dispatcher->dispatch(KitpagesDataGridEvents::AFTER_DISPLAY_GRID_VALUE_CONVERSION, $event); $returnValue = $event->get("returnValue"); // auto escape ? (if null, return null, without autoescape...) if ($field->getAutoEscape() && !is_null($returnValue)) { $returnValue = htmlspecialchars($returnValue); } return $returnValue; }
public function getBasicFunctionRenamesTest() { $functs = $this->getBasicFunctionRenames(); foreach ($functs as $oldFunct => $newFunct) { $oldFunctReflection = new ReflectionFunction($oldFunct); $newFunctReflection = new ReflectionFunction($newFunct); if ($oldFunctReflection->getNumberOfParameters() != $newFunctReflection->getNumberOfParameters()) { var_dump($oldFunct); } } }
/** * Execute the closure, passing in the additional data as arguments * * @param Closure $value Closure to execute * @throws \Psecio\PropAuth\Exception\MissingParametersException If not enough params were given for the closure * @return boolean Pass/fail of evaluation */ private function executeClosure($value) { $addl = $this->getAdditional(); // Inspect the closure and ensure we have enough parameters $info = new \ReflectionFunction($value); $required = $info->getNumberOfParameters(); if (count($addl) < $required) { // Here we subtract 1 because the first param (subject) is forcefully injected throw new MissingParametersException('Not enough parameters provided for the check. (' . ($required - 1) . ' required)'); } return call_user_func_array($value, $addl); }
/** * @return Func[] * One or more (alternate) methods begotten from * reflection info and internal method data */ public static function functionListFromReflectionFunction(CodeBase $code_base, \ReflectionFunction $reflection_function) : array { $context = new Context(); $parts = explode('\\', $reflection_function->getName()); $method_name = array_pop($parts); $namespace = '\\' . implode('\\', $parts); $fqsen = FullyQualifiedFunctionName::make($namespace, $method_name); $function = new Func($context, $fqsen->getName(), new UnionType(), 0, $fqsen); $function->setNumberOfRequiredParameters($reflection_function->getNumberOfRequiredParameters()); $function->setNumberOfOptionalParameters($reflection_function->getNumberOfParameters() - $reflection_function->getNumberOfRequiredParameters()); return self::functionListFromFunction($function, $code_base); }
/** * Returns an indication of the number of arguments accepted by a callable. * * @param callable $callback * @return int */ public static function arity(callable $callback) { if (is_array($callback) || is_string($callback) && strpos($callback, '::') !== false) { list($class, $method) = is_string($callback) ? explode('::', $callback) : $callback; $reflection = (new \ReflectionClass($class))->getMethod($method); } elseif (is_object($callback) && !$callback instanceof \Closure) { $reflection = (new \ReflectionClass($callback))->getMethod('__invoke'); } else { $reflection = new \ReflectionFunction($callback); } return $reflection->getNumberOfParameters(); }
/** * Introduces any number of fresh variables into scope. */ function fresh($f) { $reflection = new \ReflectionFunction($f); $argCount = $reflection->getNumberOfParameters(); if ($argCount === 0) { return $f(); } else { return callFresh(function ($x) use($f, $argCount) { return collectArgs($f, $argCount, array(), $x); }); } }
/** * Hash anything (except PDO connection stuff, for now). * * @param mixed $object * @return string */ public static function hash($object) { $object = is_array($object) ? $object : [$object]; array_walk_recursive($object, function ($item) { if ($item instanceof \Closure) { $reflection = new \ReflectionFunction($item); // Unique and fast. $item = serialize($reflection->getClosureScopeClass()) . $reflection->getNumberOfParameters() . $reflection->getNamespaceName() . $reflection->getStartLine() . $reflection->getEndLine(); } }); return md5(serialize($object)); }
public function displayGridValue($row, Field $field) { // parse field name and get value after the dot $fieldNameTab = explode('.', $field->getFieldName()); if (in_array($fieldNameTab[0], $this->rootAliases)) { array_shift($fieldNameTab); } $value = $row; while (count($fieldNameTab) > 0) { $fieldName = array_shift($fieldNameTab); // get parameter in the $row $value = $value[$fieldName]; } // $fieldName = array_shift($fieldNameTab); // $value = $row[$fieldNameTab]; // real treatment if (is_callable($field->getFormatValueCallback())) { $callback = $field->getFormatValueCallback(); $reflection = new \ReflectionFunction($callback); if ($reflection->getNumberOfParameters() == 1) { $returnValue = $callback($value); } elseif ($reflection->getNumberOfParameters() == 2) { $returnValue = $callback($value, $row); } else { throw new DataGridException("Wrong number of parameters in the callback for field " . $field->getFieldName()); } } elseif (is_scalar($value)) { $returnValue = $value; } elseif ($value instanceof \DateTime) { $returnValue = $value->format("Y-m-d H:i:s"); } else { $returnValue = $value; } // auto escape ? if ($field->getAutoEscape()) { $returnValue = htmlspecialchars($returnValue); } return $returnValue; }
public function __construct($function) { parent::__construct(); try { $ref = new ReflectionFunction($function); $this->_function = $ref; $this->_args = $ref->getParameters(); $this->_args_cnt = $ref->getNumberOfParameters(); $this->_available = true; } catch (Exception $ex) { $this->_function = $function; $this->_available = false; } }
protected function sendAndReceiveCallback($response, $error, $use) { list($args, $mode, $context, $callback) = $use; $result = null; if (is_array($callback)) { $f = new \ReflectionMethod($callback[0], $callback[1]); } else { $f = new \ReflectionFunction($callback); } $n = $f->getNumberOfParameters(); if ($error === null) { try { $result = $this->doInput($response, $args, $mode, $context); } catch (\Exception $e) { $error = $e; } } if ($error === null) { switch ($n) { case 0: call_user_func($callback); break; case 1: call_user_func($callback, $result); break; case 2: call_user_func($callback, $result, $args); break; case 3: call_user_func($callback, $result, $args, $error); break; } } else { switch ($n) { case 0: call_user_func($callback); break; case 1: call_user_func($callback, $error); break; case 2: call_user_func($callback, $error, $args); break; case 3: call_user_func($callback, $result, $args, $error); break; } } }
protected function executeInContext() { if (func_num_args() < 1) { throw new \InvalidArgumentException('No closure'); } $param = func_get_args(); $method = array_shift($param); // check parameters count : $refl = new \ReflectionFunction($method); if ($refl->getNumberOfParameters() !== count($param)) { throw new \InvalidArgumentException('Parameters count in closure does not match arguments count'); } $bound = \Closure::bind($method, $this->context, $this->context); call_user_func_array($bound, $param); }
/** * Summary of NumberOfParameters * @param mixed $method * @param mixed $class * @return mixed */ public static function NumberOfParameters($method, $class) { static $cache = array(); $key = $method . '::' . $class; if (!isset($cache[$key])) { if (!empty($class)) { $c = new \ReflectionClass($class); $m = $c->getMethod($method); } else { $m = new \ReflectionFunction($method); } $cache[$key] = $m->getNumberOfParameters(); } return $cache[$key]; }
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; }
/** * Reset function, returning cleared model * * @param array $properties */ public function reset(array $properties = []) { $vars = get_object_vars($this); foreach ($vars as $property => $value) { if (sizeof($properties) && in_array($property, $properties) || !sizeof($properties)) { $this->{$property} = $this->_getCleanProperty($property); } } /** at complete reset re-construct */ if (!sizeof($properties) && method_exists($this, '__construct')) { $reflection = new \ReflectionFunction('__construct'); if ($reflection->getNumberOfParameters() === 0) { $this->__construct(); } } }
protected function shouldRun(\Exception $exception) { if (is_array($this->callback)) { $callbackReflection = new \ReflectionMethod($this->callback[0], $this->callback[1]); } elseif (is_object($this->callback) && !$this->callback instanceof \Closure) { $callbackReflection = new \ReflectionObject($this->callback); $callbackReflection = $callbackReflection->getMethod('__invoke'); } else { $callbackReflection = new \ReflectionFunction($this->callback); } if ($callbackReflection->getNumberOfParameters() > 0) { $parameters = $callbackReflection->getParameters(); $expectedException = $parameters[0]; if ($expectedException->getClass() && !$expectedException->getClass()->isInstance($exception)) { return false; } } return true; }
function __invoke() { $args = func_get_args(); foreach ($this->cases as $k => $v) { if (is_callable($v->condition)) { $vc = new \ReflectionFunction($v->condition); // reduce mistaken hits by only calling the condition on cases when there aren't too many or too few args // the || 0 case is a special one when the condition function hasn't taken any paramenters. Then we should always invoke the function to check because it is presumably using func_get_args() or is our $always condition if ($vc->getNumberOfParameters() <= count($args) && ($vc->getNumberOfRequiredParameters() == 0 || $vc->getNumberOfRequiredParameters() >= count($args)) && $vc->invokeArgs($args)) { $vf = new \ReflectionFunction($v->f); return $vf->invokeArgs($args); } } elseif ($v->condition === $args || count($args) === 1 && $v->condition === $args[0]) { $vf = new \ReflectionFunction($v->f); return $vf->invokeArgs($args); } } throw new \UnexpectedValueException("No conditions matched the given input:" . $args); }
private function validateSignature(callable $filter = null) { $reflection = new \ReflectionFunction($filter); if ($reflection->getNumberOfParameters() !== 1) { throw new \Exception("invalid number of parameters"); } $parameter = $reflection->getParameters()[0]; $name = $parameter->getName(); if (!$parameter->hasType()) { throw new \Exception("missing required type for parameter '{$name}'"); } $type = $parameter->getType(); if ((string) $type !== "ReflectionClass") { throw new \Exception("invalid type for type for parameter '{$name}'"); } if (!$reflection->hasReturnType()) { throw new \Exception("missing required return type"); } $returnType = $reflection->getReturnType(); if ((string) $returnType !== "bool") { throw new \Exception("invalid return type"); } }
/** * @dataProvider getFunctions * * @param string $functionName */ public function testManuallyDb($functionName) { $reflection = $this->getReflector()->getFunction($functionName); if ($reflection) { try { $standardFunctionReflection = new \ReflectionFunction($functionName); } catch (\ReflectionException $e) { parent::markTestSkipped('Function doest not exist'); return; } parent::assertSame($standardFunctionReflection->getNumberOfRequiredParameters(), $reflection->getNumberOfRequiredParameters()); parent::assertSame($standardFunctionReflection->getNumberOfParameters(), $reflection->getNumberOfParameters()); if ($reflection->getNumberOfParameters()) { foreach ($reflection->getParameters() as $key => $parameter) { parent::assertSame($parameter, $reflection->getParameter($key)); parent::assertNotEmpty($parameter->getName()); parent::assertInternalType('integer', $parameter->getType()); parent::assertInternalType('boolean', $parameter->isRequired()); } } return; } parent::markTestSkipped('Unknown manually reflection for function: ' . $functionName); }
protected function getCallable(Field $field, $row, $value) { $callback = $field->getFormatValueCallback(); $reflection = new \ReflectionFunction($callback); if ($reflection->getNumberOfParameters() == 1) { $value = $callback($value); } elseif ($reflection->getNumberOfParameters() == 2) { $value = $callback($value, $row); } else { throw new DataGridException('Wrong number of parameters in the callback for field ' . $field->getFieldName()); } $rowValue = isset($row[$field->getFieldName()]) ? $row[$field->getFieldName()] : null; // if($field->getIsTwig()){ $value = $this->parser->parse($value, array('value' => $rowValue, 'row' => $row)); // } return $value; }
/** * Determines the type of the first callback argument and returns it. * * @param callable $callback * @return string */ protected function getRequiredType(callable $callback) { $ref = new \ReflectionFunction($callback); if ($ref->getNumberOfParameters() > 0) { $params = $ref->getParameters(); if (isset($params[0]) && NULL !== ($type = $params[0]->getClass())) { return $type; } } }
/** * Returns you a curried version of the function * If you are going to curry a function which reads args with func_get_args() then pass a number of args as the 2nd argument. * * @param callable $function * @param bool $withOptionalArgs If true then curry function with optional args otherwise curry it only with required args. Or you can pass the exact number of args you want to curry. * @return callable */ function curried(callable $function, $withOptionalArgs = false) { if (is_bool($withOptionalArgs)) { $reflection = new \ReflectionFunction($function); $numOfArgs = $withOptionalArgs ? $reflection->getNumberOfParameters() : $reflection->getNumberOfRequiredParameters(); } else { $numOfArgs = $withOptionalArgs; } return function ($arg) use($function, $numOfArgs) { if (1 === $numOfArgs) { return $function($arg); } return curried(function () use($arg, $function) { return call_user_func_array($function, array_merge(array($arg), func_get_args())); }, $numOfArgs - 1); }; }
/** * Parse Routes * * Matches any routes that may exist in the config/routes.php file * against the URI to determine if the class/method need to be remapped. * * @return void */ protected function _parse_routes() { // Turn the segment array into a URI string $uri = implode('/', $this->uri->segments); // Is there a literal match? If so we're done if (isset($this->routes[$uri]) && is_string($this->routes[$uri])) { return $this->_set_request(explode('/', $this->routes[$uri])); } // Loop through the route array looking for wild-cards foreach ($this->routes as $key => $val) { // Convert wild-cards to RegEx $key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key); // Does the RegEx match? if (preg_match('#^' . $key . '$#', $uri, $matches)) { // Are we using callbacks to process back-references? if (!is_string($val) && is_callable($val)) { // Remove the original string from the matches array. array_shift($matches); // Get the match count. $match_count = count($matches); // Determine how many parameters the callback has. $reflection = new ReflectionFunction($val); $param_count = $reflection->getNumberOfParameters(); // Are there more parameters than matches? if ($param_count > $match_count) { // Any params without matches will be set to an empty string. $matches = array_merge($matches, array_fill($match_count, $param_count - $match_count, '')); $match_count = $param_count; } // Get the parameters so we can use their default values. $params = $reflection->getParameters(); for ($m = 0; $m < $match_count; $m++) { // Is the match empty and does a default value exist? if (empty($matches[$m]) && $params[$m]->isDefaultValueAvailable()) { // Substitute the empty match for the default value. $matches[$m] = $params[$m]->getDefaultValue(); } } // Execute the callback using the values in matches as its parameters. $val = call_user_func_array($val, $matches); } elseif (strpos($val, '$') !== FALSE && strpos($key, '(') !== FALSE) { $val = preg_replace('#^' . $key . '$#', $val, $uri); } return $this->_set_request(explode('/', $val)); } } // If we got this far it means we didn't encounter a // matching route so we'll set the site default route $this->_set_request($this->uri->segments); }
/** * @return Method[] * One or more (alternate) methods begotten from * reflection info and internal method data */ public static function methodListFromReflectionFunction(CodeBase $code_base, \ReflectionFunction $reflection_function) : array { $number_of_required_parameters = $reflection_function->getNumberOfRequiredParameters(); $number_of_optional_parameters = $reflection_function->getNumberOfParameters() - $number_of_required_parameters; $context = new Context(); $parts = explode('\\', $reflection_function->getName()); $method_name = array_pop($parts); $namespace = '\\' . implode('\\', $parts); $fqsen = FullyQualifiedFunctionName::make($namespace, $method_name); $method = new Method($context, $fqsen->getName(), new UnionType(), 0, $number_of_required_parameters, $number_of_optional_parameters); $method->setFQSEN($fqsen); return self::methodListFromMethod($method, $code_base); }
public function invoke($name, array &$args = array(), $callback = null, InvokeSettings $settings = null) { if ($callback instanceof InvokeSettings) { $settings = $callback; $callback = null; } if ($settings === null) { $settings = new InvokeSettings(); } $context = $this->getContext($settings); $invokeHandler = $this->invokeHandler; if (is_callable($callback)) { if (is_array($callback)) { $f = new ReflectionMethod($callback[0], $callback[1]); } else { $f = new ReflectionFunction($callback); } $n = $f->getNumberOfParameters(); $onError = $this->onError; return all($args)->then(function ($args) use($invokeHandler, $name, $context, $n, $callback, $onError) { $result = toFuture($invokeHandler($name, $args, $context)); $result->then(function ($result) use($n, $callback, $args) { switch ($n) { case 0: call_user_func($callback); break; case 1: call_user_func($callback, $result); break; case 2: call_user_func($callback, $result, $args); break; case 3: call_user_func($callback, $result, $args, null); break; } }, function ($error) use($n, $callback, $args, $name, $onError) { switch ($n) { case 0: call_user_func($callback); if (is_callable($onError)) { call_user_func($onError, $name, $error); } break; case 1: call_user_func($callback, $error); break; case 2: call_user_func($callback, $error, $args); break; case 3: call_user_func($callback, null, $args, $error); break; } }); return $result; }); } else { if ($this->async) { $args = all($args); return $args->then(function ($args) use($invokeHandler, $name, $context) { return $invokeHandler($name, $args, $context); }); } return $invokeHandler($name, $args, $context); } }