/** * @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); }
function getReflectedMinimumParams($name) { // Reflection gets this one wrong. if (strcasecmp($name, 'define') == 0) { return 2; } if (strcasecmp($name, 'strtok') == 0) { return 1; } if (strcasecmp($name, 'implode') == 0) { return 1; } if (strcasecmp($name, "sprintf") == 0) { return 1; } if (strcasecmp($name, "array_merge") == 0) { return 1; } if (strcasecmp($name, "stream_set_timeout") == 0) { return 2; } try { $func = new \ReflectionFunction($name); return $func->getNumberOfRequiredParameters(); } catch (\ReflectionException $e) { return -1; } }
/** * Evaluate * * @param \Closure $other * @param string $description Additional information about the test * @param bool $returnResult Whether to return a result or throw an exception * @return boolean */ public function evaluate($other, $description = '', $returnResult = FALSE) { if (!$other instanceof \Closure) { $this->_cause = 'Variable must be a Closure'; if ($returnResult) { return FALSE; } $this->fail($other, $description); } $reflection = new \ReflectionFunction($other); $requiredParameters = new \PHPUnit_Framework_Constraint_IsEqual(1); if (false === $requiredParameters->evaluate($reflection->getNumberOfRequiredParameters(), $description, true)) { $this->_cause = 'Closure does not have 1 required parameter'; if ($returnResult) { return FALSE; } $this->fail($other, $description); } $params = $reflection->getParameters(); $tokenParameter = $params[0]; /* @var $tokenParameter \ReflectionParameter */ $parameterType = new \PHPUnit_Framework_Constraint_IsEqual('PHP\\Manipulator\\Token'); if (false === $parameterType->evaluate($tokenParameter->getClass()->name, $description, true)) { $this->_cause = 'Closures Token-Parameter has wrong Typehint'; if ($returnResult) { return FALSE; } $this->fail($other, $description); } 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); } foreach (get_declared_traits() as $class_name) { add_class($class_name); } 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', 'namespace' => $function->getNamespaceName(), '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 required parameters * * @return integer The number of required parameters * @since PHP 5.0.3 */ public function getNumberOfRequiredParameters() { if ($this->reflectionSource instanceof ReflectionFunction) { return $this->reflectionSource->getNumberOfRequiredParameters(); } else { return parent::getNumberOfRequiredParameters(); } }
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()); }
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); }
public function onCreate() { $this->closed = false; if (!is_callable($this->params)) { throw new InvalidArgumentException('No valid callback parameter given to stream_filter_(append|prepend)'); } $this->callback = $this->params; // callback supports end event if it accepts invocation without arguments $ref = new ReflectionFunction($this->callback); $this->supportsClose = $ref->getNumberOfRequiredParameters() === 0; return true; }
function __construct($callable, $argumentCommands = array()) { if (!is_callable($callable)) { throw new \InvalidArgumentException(); } $this->callable = $callable; foreach ($argumentCommands as $argumentCommand) { if (!$argumentCommand instanceof CommandInterface) { throw new \InvalidArgumentException(); } } $reflection = new \ReflectionFunction($this->callable); if (sizeof($argumentCommands) < $reflection->getNumberOfRequiredParameters()) { throw new \FormulaInterpreter\Exception\NotEnoughArgumentsException(); } $this->argumentCommands = $argumentCommands; }
/** * Get all rules * * @return Integer */ public function getNumberOfRequiredParametersForRule($ruleName) { $rc = new \ReflectionClass($this->RuleList); try { $rm = $rc->getMethod($ruleName); } catch (\Exception $e) { } if (isset($rm)) { return $rm->getNumberOfRequiredParameters(); } else { if (isset($this->RuleList->closures[$ruleName])) { $rf = new \ReflectionFunction($this->RuleList->closures[$ruleName]); return $rf->getNumberOfRequiredParameters(); } } return 0; }
/** * Ensure that this callback takes no arguments * * @param callable $cb */ public static function validateCallback(callable $cb) { if (is_string($cb) and strpos($cb, "::") !== false) { $cb = explode("::", $cb); } if (is_string($cb) or $cb instanceof \Closure) { $function = new \ReflectionFunction($cb); if ($function->getNumberOfRequiredParameters() > 0) { throw new \InvalidArgumentException("Callable requires parameters"); } } elseif (is_array($cb)) { list($ctx, $m) = $cb; $method = new \ReflectionMethod($ctx, $m); if ($method->getNumberOfRequiredParameters() > 0) { throw new \InvalidArgumentException("Callable requires parameters"); } } }
/** * @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); }
<?php $funcs = get_extension_funcs("intl"); function ignore_err() { } set_error_handler("ignore_err"); $arg = new stdClass(); foreach ($funcs as $func) { $rfunc = new ReflectionFunction($func); if ($rfunc->getNumberOfRequiredParameters() == 0) { continue; } try { $res = $func($arg); } catch (Exception $e) { continue; } if ($res != false) { echo "{$func}: "; var_dump($res); } } echo "OK!\n";
var_dump($rf->getStartLine()); print "\n"; print "--- getEndLine(\"f\") ---\n"; var_dump($rf->getEndLine()); print "\n"; print "--- getFileName(\"f\") ---\n"; var_dump($rf->getFileName()); print "\n"; print "--- getName(\"f\") ---\n"; var_dump($rf->getName()); print "\n"; print "--- getNumberOfParameters(\"f\") ---\n"; var_dump($rf->getNumberOfParameters()); print "\n"; print "--- getNumberOfRequiredParameters(\"f\") ---\n"; var_dump($rf->getNumberOfRequiredParameters()); print "\n"; print "--- getParameters(\"f\") ---\n"; var_dump($rf->getParameters()); print "\n"; print "--- getStaticVariables(\"f\") ---\n"; var_dump($rf->getStaticVariables()); print "\n"; print "--- isInternal(\"f\") ---\n"; var_dump($rf->isInternal()); print "\n"; print "--- isUserDefined(\"f\") ---\n"; var_dump($rf->isUserDefined()); print "\n"; print "--- returnsReference(\"f\") ---\n"; var_dump($rf->returnsReference());
/** * Uses reflection to determine the number of required arguements for a callable * * NOTE: This will only consider *required* arguments, i.e. optional and variadic * arguments do *not* contribute to the count */ function n_required_args(callable $f) { /* * Get an appropriate reflector * * If we have some kind of method (static or instance), this should be a * ReflectionMethod * * If we have a function name or closure, this should be a ReflectionFunction */ $reflector = null; if (is_array($f)) { // If we have an array, that is a method $reflector = new \ReflectionMethod($f[0], $f[1]); } elseif (is_string($f) && strpos($f, '::') !== false) { // If we have a string containing '::', that is a static method $reflector = new \ReflectionMethod($f); } else { // Otherwise, we have some kind of function $reflector = new \ReflectionFunction($f); } return $reflector->getNumberOfRequiredParameters(); }
<?php class TestClass { } function optionalTest(TestClass $a, TestClass $b, $c = 3) { } $function = new ReflectionFunction('optionalTest'); $numberOfNotOptionalParameters = 0; $numberOfOptionalParameters = 0; foreach ($function->getParameters() as $parameter) { var_dump($parameter->isOptional()); if ($parameter->isOptional()) { ++$numberOfOptionalParameters; } else { ++$numberOfNotOptionalParameters; } } var_dump($function->getNumberOfRequiredParameters()); var_dump($numberOfNotOptionalParameters);
/** * @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); }
/** * @internal * @param $callable * @return int */ function _number_of_required_params($callable) { if (is_array($callable)) { $refl = new \ReflectionClass($callable[0]); $method = $refl->getMethod($callable[1]); return $method->getNumberOfRequiredParameters(); } $refl = new \ReflectionFunction($callable); return $refl->getNumberOfRequiredParameters(); }
public function testGetNumberOfRequiredParameters() { self::assertEquals(3, $this->fctM1->getNumberOfRequiredParameters()); $func = new ReflectionFunction('mmm'); self::assertEquals(0, $func->getNumberOfRequiredParameters()); }
$info_function = new ReflectionFunction($function_console); $arr_opts = array(); $arr_params = array(); foreach ($info_function->getParameters() as $param) { $name = $param->getName(); if ($param->isOptional()) { $arr_opts[] = $name . '::'; $arr_params[] = '--' . $name . '=[optional]'; } else { $arr_opts[] = $name . ':'; $arr_params[] = '--' . $name . '=[required]'; } } $final_params = getopt('', $arr_opts); $required_parameters = count($final_params); if ($info_function->getNumberOfRequiredParameters() > $required_parameters) { $climate->white()->backgroundBlack()->out("Use: php console.php -m=group/module -c=console_controller " . implode(' ', $arr_params)); die; } call_user_func_array($function_console, $final_params); } else { $climate->white()->backgroundRed()->out("Error: Don't exists the function with name " . $function_console . " in " . $controller . "..."); exit(1); } } else { $climate->white()->backgroundRed()->out("Error: Don't exists the controller " . $controller . " for console statement..."); exit(1); } /** * Function for obtain options from console. The opts use the format of getopt function */
/** * Specify the user-defined callback for receiving data from asynchronous * events sent by the controller. * * The callback must accept 2 arguments: $event, and $data where $event is * the name of the event (e.g. ADDRMAP, NEW_CONSENSUS) and $data is the * content of the event (typically ProtocolReply, array, or RouterDescriptor) * * @param callback $callback A valid callback that will be called after event data is received * @throws \Exception If the $callback is not a callable function or method * @return \Dapphp\TorUtils\ControlClient */ public function setAsyncEventHandler($callback) { if (!is_callable($callback)) { throw new \Exception('Callback provided is not callable'); } $ref = new \ReflectionFunction($callback); $numargs = $ref->getNumberOfRequiredParameters(); if ($numargs < 2) { throw new \Exception("Supplied callback must accept 2 arguments but it accepts {$numargs}"); } $this->_eventCallback = $callback; return $this; }
function curry($f) { $args = array_slice(func_get_args(), 1); $meta = new \ReflectionFunction($f); return call_user_func_array('F\\curryN', array_merge([$meta->getNumberOfRequiredParameters(), $f], $args)); }
<?php $r = new ReflectionExtension("mysql"); $ignore = array(); $functions = $r->getFunctions(); asort($functions); printf("Functions:\n"); foreach ($functions as $func) { if (isset($ignore[$func->name])) { continue; } printf(" %s\n", $func->name); $rf = new ReflectionFunction($func->name); printf(" Deprecated: %s\n", $rf->isDeprecated() ? "yes" : "no"); printf(" Accepted parameters: %d\n", $rf->getNumberOfParameters()); printf(" Required parameters: %d\n", $rf->getNumberOfRequiredParameters()); foreach ($rf->getParameters() as $param) { printf(" %s\n", $param); } } print "done!";
<?php include "src/helpers.php"; foreach (get_defined_functions()["user"] as $fn) { $__fn = new ReflectionFunction($fn); $output = array(); $attributes = array(); $name = $__fn->getName(); $params = $__fn->getParameters(); $paramcount = $__fn->getNumberOfParameters(); $paramrequired = $__fn->getNumberOfRequiredParameters(); // create output foreach ($params as $index => $param) { $optional = $index >= $paramrequired; $value = ""; $output[] = ($optional ? "//" : "") . "\$" . $param->name . " = \"" . $value . "\";"; $attributes[] = ($optional ? "/*" : "") . "\$" . $param->name . ($optional ? "*/" : ""); } $output[] = ""; $output[] = "\$result = " . $name . "(" . implode(", ", $attributes) . ");"; $fn = "test/" . $name . ".php"; if (!file_exists($fn)) { file_put_contents($fn, sprintf("<?php\n\ninclude(\"../src/helpers.php\");\n\n%s\n\nvar_dump(\$result);", implode("\n", $output))); } }
/** * Format XML for the current recordset * * @access public * @param SLS_XMLToolbox $xml current controller's XML * @param array $options transformations on some columns - delimited by ":". each function can be methods of SLS' classes or php standard function * <code> * // Complete example * $xml = $news->toXML($xml, array( "news_excerpt" => array("php:strip_tags", "SLS_String:trimStringToLength:100"), * "news_date" => array("SLS_Date:getDate:FULL_LITTERAL_TIME", "php:ucwords"), * "news_photo" => "SLS_String:getUrlFileImg:_0", * "news_pdf" => "SLS_String:getUrlFile", * "news_title" => "php:trim", * "news_link" => array("/Item/", * "news_title" => "SLS_String:stringToUrl:_", * "-", * "news_id" => array("php:intval","php:pow:2"), * "/User/", * "user_id")) * , true, "news"); * </code> * @param mixed $fks (bool: if true all fks, if false only current Model) - array fks you want to extract params * @param string $nodeName the root node of your model, by default it's your classname in lowercase * @param array $properties all columns/values of your choice if you don't want to take it from getParams() function of the current instance * @return SLS_XMLToolbox $xml current controller's XML updated * @see SLS_FrontModel::getParams * @see SLS_FrontModel::pdoToXML * @since 1.0.8 */ public function toXML($xml,$options=array(),$fks=false,$nodeName="",$properties=array()) { $nodeName = (empty($nodeName)) ? strtolower($this->getTable()) : $nodeName; $properties = (empty($properties)) ? $this->getParams($fks) : $properties; $xml->startTag($nodeName); foreach($properties as $column => $value) { if (in_array($column,$columns=array_keys($options))) { $filters = (is_array($options[$column])) ? $options[$column] : array($options[$column]); foreach($filters as $filter) { $option = explode(":",$filter); switch($option[0]) { case SLS_String::startsWith($option[0],"SLS_"): if (!class_exists($option[0])) SLS_Tracing::addTrace(new Exception("Error: you want to use an undefined class `".$option[0]."` for the column `".$column."` of `".$this->getTable()."` table")); else { if (!method_exists($option[0],((count($option)> 1) ? $option[1] : ""))) SLS_Tracing::addTrace(new Exception("Error: you want to use an undefined function `".$option[1]."` of class `".$option[0]."` for the column `".$column."` of `".$this->getTable()."` table")); else { $ref = new ReflectionMethod($option[0],$option[1]); $nbRequiredParams = $ref->getNumberOfRequiredParameters(); if ($nbRequiredParams > (count($option)-1)) SLS_Tracing::addTrace(new Exception("Error: function `".$option[1]."` of class `".$option[0]."` needs ".$nbRequiredParams." required parameters for the column `".$column."` of `".$this->getTable()."` table"),true); else { $params = array_slice($option,2); array_unshift($params,$value); // Case "SLS_Date::getDate" if ($option[0] == "SLS_Date" && $option[1] == "getDate") { $option[0] = new SLS_Date($value); array_shift($params); } // Case "SLS_String::getUrlFileImg" if ($option[0] == "SLS_String" && $option[1] == "getUrlFileImg" && count($option) > 2) { $xml->addFullTag($column."_original",SLS_String::getUrlFile($value,(count($option) > 3) ? $option[3] : ""),true); $column = $column.$option[2]; } $value = $ref->invokeArgs(($ref->isStatic()) ? null : $option[0],$params); } } } break; case "php": if (count($option) < 2) SLS_Tracing::addTrace(new Exception("Error: you must specify the name of the PHP's function you want to apply on the column `".$column."` of `".$this->getTable()."` table")); else { if (function_exists($option[1])) { $ref = new ReflectionFunction($option[1]); $nbRequiredParams = $ref->getNumberOfRequiredParameters(); if ($nbRequiredParams > (count($option)-1)) SLS_Tracing::addTrace(new Exception("Error: the PHP's function `".$option[1]."` needs ".$nbRequiredParams." required parameters for the column `".$column."` of `".$this->getTable()."` table"),true); else { $params = array_slice($option,2); array_unshift($params,$value); $value = $ref->invokeArgs($params); } } else SLS_Tracing::addTrace(new Exception("Error: the PHP's function '".$option[1]."' you want to use on the column `".$column."` of `".$this->getTable()."` table doesn't exist")); } break; default: SLS_Tracing::addTrace(new Exception("Error: you want to apply an unknown filter on the column `".$column."` of `".$this->getTable()."` table doesn't exist")); break; } } } $xml->addFullTag($column,$value,true); } foreach($options as $col => $concat) { if (!in_array($col,array_keys($properties)) && is_array($concat)) { $values = array(); foreach($concat as $column => $filter) { if (is_int($column) && !empty($filter) && !is_array($filter)) { $column = $filter; $filter = ""; } $value = ""; $filters = (is_array($filter)) ? $filter : ((empty($filter)) ? "" : array($filter)); if (in_array($column,array_keys($properties))) $value .= $properties[$column]; else $value .= $column; if (!empty($filters)) { foreach($filters as $filter) { $option = explode(":",$filter); switch($option[0]) { case SLS_String::startsWith($option[0],"SLS_"): if (!class_exists($option[0])) SLS_Tracing::addTrace(new Exception("Error: you want to use an undefined class `".$option[0]."` for the column `".$column."` of `".$this->getTable()."` table")); else { if (!method_exists($option[0],((count($option)> 1) ? $option[1] : ""))) SLS_Tracing::addTrace(new Exception("Error: you want to use an undefined function `".$option[1]."` of class `".$option[0]."` for the column `".$column."` of `".$this->getTable()."` table")); else { $ref = new ReflectionMethod($option[0],$option[1]); $nbRequiredParams = $ref->getNumberOfRequiredParameters(); if ($nbRequiredParams > (count($option)-1)) SLS_Tracing::addTrace(new Exception("Error: function `".$option[1]."` of class `".$option[0]."` needs ".$nbRequiredParams." required parameters for the column `".$column."` of `".$this->getTable()."` table"),true); else { $params = array_slice($option,2); array_unshift($params,$value); // Case "SLS_Date::getDate" if ($option[0] == "SLS_Date" && $option[1] == "getDate") { $option[0] = new SLS_Date($value); array_shift($params); } // Case "SLS_String::getUrlFileImg" if ($option[0] == "SLS_String" && $option[1] == "getUrlFileImg" && count($option) > 2) { $xml->addFullTag($column."_original",SLS_String::getUrlFile($value),true); $column = $column.$option[2]; } $value = $ref->invokeArgs(($ref->isStatic()) ? null : $option[0],$params); } } } break; case "php": if (count($option) < 2) SLS_Tracing::addTrace(new Exception("Error: you must specify the name of the PHP's function you want to apply on the column `".$column."` of `".$this->getTable()."` table")); else { if (function_exists($option[1])) { $ref = new ReflectionFunction($option[1]); $nbRequiredParams = $ref->getNumberOfRequiredParameters(); if ($nbRequiredParams > (count($option)-1)) SLS_Tracing::addTrace(new Exception("Error: the PHP's function `".$option[1]."` needs ".$nbRequiredParams." required parameters for the column `".$column."` of `".$this->getTable()."` table"),true); else { $params = array_slice($option,2); array_unshift($params,$value); $value = $ref->invokeArgs($params); } } else SLS_Tracing::addTrace(new Exception("Error: the PHP's function '".$option[1]."' you want to use on the column `".$column."` of `".$this->getTable()."` table doesn't exist")); } break; default: SLS_Tracing::addTrace(new Exception("Error: you want to apply an unknown filter on the column `".$column."` of `".$this->getTable()."` table doesn't exist")); break; } } } $values[] = $value; } $xml->addFullTag($col,implode("",$values),true); } } $xml->endTag($nodeName); return $xml; }
public function sort($sorter) { if (!is_callable($sorter)) { $sorter_field = $sorter; $real_sorter = function ($a, $b) use($sorter_field) { if (!isset($a[$sorter_field]) || !isset($b[$sorter_field])) { return 0; } $av = $a[$sorter_field]; $bv = $b[$sorter_field]; if ($av < $bv) { return -1; } if ($av > $bv) { return 1; } return 0; }; } elseif ($sorter instanceof \Closure) { $reflection = new \ReflectionFunction($sorter); $arg_num = $reflection->getNumberOfRequiredParameters(); if ($arg_num === 1) { $real_sorter = function ($a, $b) use($sorter) { $av = $sorter($a); $bv = $sorter($b); if ($av < $bv) { return -1; } if ($av > $bv) { return 1; } return 0; }; } else { $real_sorter = $sorter; } } else { $real_sorter = $sorter; } @uasort($this->data, $real_sorter); return $this; }
/** * 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); }; }
/** * creates a named callable and adds it to $custom_filters array. useful for creating custom filters. * @param string $name the name to assign to the callable. * @param closure $callable the callback function. */ public function custom_filter($name, $callable) { if (empty($name)) { throw new \exception('RedBeanFVM :: custom_filter() An Invalid Name was declared.'); } if (method_exists($this, $name)) { throw new \exception('RedBeanFVM :: custom_filter() `' . $name . '()` is a built in method of RedBeanFVM and a custom filter of that name may not be declared.'); } if (!is_callable($callable)) { throw new \exception('RedBeanFVM :: custom_filter() Method `' . $name . '` isn\'t a valid callable!'); } $info = new \ReflectionFunction($callable); if ($info->getNumberOfParameters() !== 1 || $info->getNumberOfRequiredParameters() !== 1) { throw new \exception('RedbeanFVM :: custom_filter() Method`' . $name . '` declares an invalid number of arguments! only one argument is allowed!'); } self::$custom_filters[$name] = $callable; }
/** * Constructor. * * @param ReflectionMethod $method The PHP method to introspect. */ public function __construct(ReflectionFunction $method) { $docs = $method->getDocComment(); $docs = explode("\n", $docs); $parameters = array(); $returns = 'mixed'; $shortdesc = ''; $paramcount = -1; $this->_name = $method->getName(); // Extract info from docblock. $paramDocs = array(); foreach ($docs as $i => $doc) { $doc = trim($doc, " \r\t/*"); if (strlen($doc) && strpos($doc, '@') !== 0) { if ($shortdesc) { $shortdesc .= "\n"; } $shortdesc .= $doc; continue; } if (strpos($doc, '@param') === 0) { // Save doctag for usage later when filling parameters. $paramDocs[] = $doc; } if (strpos($doc, '@return') === 0) { $param = preg_split("/\\s+/", $doc); if (isset($param[1])) { $param = $param[1]; $returns = $param; } } } // We don't use isOptional() because of bugs in the reflection API. $this->_numberOfRequiredParameters = $method->getNumberOfRequiredParameters(); // Fill in info for each method parameter. foreach ($method->getParameters() as $parameterIndex => $parameter) { // Parameter defaults. $newParameter = array('type' => 'mixed'); // Attempt to extract type and doc from docblock. if (array_key_exists($parameterIndex, $paramDocs) && preg_match('/@param\\s+(\\S+)(\\s+(.+))/', $paramDocs[$parameterIndex], $matches)) { if (strpos($matches[1], '|')) { $newParameter['type'] = self::_limitPHPType(explode('|', $matches[1])); } else { $newParameter['type'] = self::_limitPHPType($matches[1]); } $tmp = '$' . $parameter->getName() . ' '; if (strpos($matches[2], '$' . $tmp) === 0) { $newParameter['doc'] = $matches[2]; } else { // The phpdoc comment is something like "@param string // $param description of param". Let's keep only // "description of param" as documentation (remove // $param). $newParameter['doc'] = substr($matches[2], strlen($tmp)); } } $parameters[$parameter->getName()] = $newParameter; } $this->_parameters = $parameters; $this->_returns = $returns; $this->_help = $shortdesc; }
private function _validateCallbackArguments() { if (!$this->_arguments_checks) { return; } $callable = $this->_callable; if (is_array($callable)) { $reflection_callback_value = new \ReflectionMethod($callable[0], $callable[1]); } else { $reflection_callback_value = new \ReflectionFunction($callable); } $passed_args_number = count($this->_args) + 1; if ($this->_callable_pass_keys) { $passed_args_number += 1; } $agr_num = $reflection_callback_value->getNumberOfRequiredParameters(); if ($agr_num != $passed_args_number) { throw new \InvalidArgumentException("Bad argument count pased for Filter-callable. Awaiting `" . $agr_num . '` arguments. But passed `' . $passed_args_number . "`" . "\nMore information about Filter-callable: \n" . $reflection_callback_value); } }