function function_signature($function_name) { try { $rf = new ReflectionFunction($function_name); } catch (Exception $e) { return null; } $params = array(); $unknown_param_name = 'unk0'; foreach ($rf->getParameters() as $rp) { $param = $rp->isPassedByReference() ? '&' : ''; $name = $rp->getName(); if ($name == '') { $name = '$' . $unknown_param_name; $unknown_param_name++; } elseif ($name == '...') { } else { $name = '$' . $name; } $param .= $name; if ($rp->isOptional()) { $param .= ' = null'; // is there better way to show that it's optional? } $params[] = $param; } $str = ""; $str .= $rf->returnsReference() ? '&' : ''; $str .= $rf->getName(); $str .= '(' . implode(", ", $params) . ')'; return $str; }
public function onWildcardEvent() { $name = $this->events->firing(); $time = microtime(true); // Get the arguments passed to the event $params = $this->prepareParams(func_get_args()); // Find all listeners for the current event foreach ($this->events->getListeners($name) as $i => $listener) { // Check if it's an object + method name if (is_array($listener) && count($listener) > 1 && is_object($listener[0])) { list($class, $method) = $listener; // Skip this class itself if ($class instanceof static) { continue; } // Format the listener to readable format $listener = get_class($class) . '@' . $method; // Handle closures } elseif ($listener instanceof \Closure) { $reflector = new \ReflectionFunction($listener); // Skip our own listeners if ($reflector->getNamespaceName() == 'Barryvdh\\Debugbar') { continue; } // Format the closure to a readable format $filename = ltrim(str_replace(base_path(), '', $reflector->getFileName()), '/'); $listener = $reflector->getName() . ' (' . $filename . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine() . ')'; } else { // Not sure if this is possible, but to prevent edge cases $listener = $this->formatVar($listener); } $params['listeners.' . $i] = $listener; } $this->addMeasure($name, $time, $time, $params); }
/** * @param mixed $nodes * @return bool */ private function callsFuncGetArgs($nodes) : bool { foreach ($nodes as $node) { if (is_array($node)) { if ($this->callsFuncGetArgs($node)) { return true; } } if (!$node instanceof \PhpParser\Node) { continue; } if ($node instanceof Function_) { $functionName = $node->name; if ((string) $node->namespacedName) { $functionName = (string) $node->namespacedName; } if ($functionName === $this->reflection->getName()) { return $this->functionCallStatementFinder->findFunctionCallInStatements(self::VARIADIC_FUNCTIONS, $node->getStmts()) !== null; } continue; } if ($this->callsFuncGetArgs($node)) { return true; } } return false; }
/** * @return $this */ public function override() { if (!function_exists($this->targetNamespace . '\\' . $this->reflectionFunction->getName())) { eval($this->getCode()); } return $this; }
/** * @return self */ public static function from($from) : self { if (is_string($from) && strpos($from, '::')) { $from = new \ReflectionMethod($from); } elseif (is_array($from)) { $from = new \ReflectionMethod($from[0], $from[1]); } elseif (!$from instanceof \ReflectionFunctionAbstract) { $from = new \ReflectionFunction($from); } $method = new static(); $method->name = $from->isClosure() ? NULL : $from->getName(); foreach ($from->getParameters() as $param) { $method->parameters[$param->getName()] = Parameter::from($param); } if ($from instanceof \ReflectionMethod) { $method->static = $from->isStatic(); $method->visibility = $from->isPrivate() ? 'private' : ($from->isProtected() ? 'protected' : NULL); $method->final = $from->isFinal(); $method->abstract = $from->isAbstract() && !$from->getDeclaringClass()->isInterface(); $method->body = $from->isAbstract() ? FALSE : ''; } $method->returnReference = $from->returnsReference(); $method->variadic = PHP_VERSION_ID >= 50600 && $from->isVariadic(); $method->comment = $from->getDocComment() ? preg_replace('#^\\s*\\* ?#m', '', trim($from->getDocComment(), "/* \r\n\t")) : NULL; if (PHP_VERSION_ID >= 70000 && $from->hasReturnType()) { $returnType = $from->getReturnType(); $method->returnType = $returnType->isBuiltin() ? (string) $returnType : '\\' . $returnType; } return $method; }
/** * Returns this function's name * * @return string This function's name */ public function getName() { if ($this->reflectionSource instanceof ReflectionFunction) { return $this->reflectionSource->getName(); } else { return parent::getName(); } }
function testExecutionShouldCollectName() { $stubName = testFake(); $reflector = new \ReflectionFunction($stubName); $test = new FunctionTest($stubName); $result = $test->execute()[0]; $this->assertSame($reflector->getName(), $result->getName()); }
public static function unwrap(\Closure $closure) { $reflectionFunction = new \ReflectionFunction($closure); if (substr($reflectionFunction->getName(), -1) === '}') { $vars = $reflectionFunction->getStaticVariables(); return isset($vars['_callable_']) ? $vars['_callable_'] : $closure; } else { if ($obj = $reflectionFunction->getClosureThis()) { return [$obj, $reflectionFunction->getName()]; } else { if ($class = $reflectionFunction->getClosureScopeClass()) { return [$class->getName(), $reflectionFunction->getName()]; } } } return $reflectionFunction->getName(); }
protected function describeValue($value, $recursive = false) { if (is_callable($value)) { $function = new \ReflectionFunction($value); $name = $function->getName(); if ($name == '{closure}') { $name = 'function'; } else { $name = 'function ' . $name; } $parameters = array(); foreach ($function->getParameters() as $parameter) { $synopsis = ''; if ($parameter->isArray()) { $synopsis .= 'array '; } else { if ($parameter->getClass()) { $synopsis .= $parameter->getClass() . ' '; } } if ($parameter->isPassedByReference()) { $synopsis .= '&'; } $synopsis .= '$' . $parameter->getName(); if ($parameter->isOptional()) { $synopsis .= ' = ' . var_export($parameter->getDefaultValue(), true); } $parameters[] = $synopsis; } return sprintf('(callable) %s(<br> %s<br>)', $name, implode(',<br> ', $parameters)); } else { if (is_object($value)) { if ($value instanceof \ArrayObject) { if ($recursive) { $values = array_map(array($this, 'describeValue'), $value->getArrayCopy()); return sprintf('(object) %s(<br> %s<br>)', get_class($value), implode(',<br> ', $values)); } else { return sprintf('(object) %s(…)', get_class($value)); } } else { return sprintf('(object) %s', get_class($value)); } } else { if (is_array($value)) { if ($recursive) { $values = array_map(array($this, 'describeValue'), $value); return sprintf('(array) [%s]', implode(', ', $values)); } else { return sprintf('(array) […]'); } } else { return sprintf('(%s) %s', gettype($value), var_export($value, true)); } } } }
function dumpFuncInfo($name) { $funcInfo = new ReflectionFunction($name); var_dump($funcInfo->getName()); var_dump($funcInfo->isInternal()); var_dump($funcInfo->isUserDefined()); var_dump($funcInfo->getStartLine()); var_dump($funcInfo->getEndLine()); var_dump($funcInfo->getStaticVariables()); }
/** * @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); }
/** * Creates a ClosureLocation and seeds it with all the data that can be gleaned from the closure's reflection * * @param \ReflectionFunction $reflection The reflection of the closure that this ClosureLocation should represent * * @return ClosureLocation */ public static function fromReflection(\ReflectionFunction $reflection) { $location = new self(); $location->directory = dirname($reflection->getFileName()); $location->file = $reflection->getFileName(); $location->function = $reflection->getName(); $location->line = $reflection->getStartLine(); // @codeCoverageIgnoreStart if (version_compare(PHP_VERSION, '5.4', '>=')) { $closureScopeClass = $reflection->getClosureScopeClass(); $location->closureScopeClass = $closureScopeClass ? $closureScopeClass->getName() : null; } // @codeCoverageIgnoreEnd return $location; }
/** * Execute the command * @param array $args Arguments gived to the command * @return array Response */ public function execute($args = array()) { $functions = array('names' => array(), 'values' => array()); $functions = get_defined_functions(); foreach ($functions['internal'] as $functionName) { try { $function = new \ReflectionFunction($functionName); } catch (\Exception $e) { continue; } $functions['names'][] = $function->getName(); $args = $this->getMethodArguments($function); $functions['values'][$function->getName()] = array(array('isMethod' => true, 'args' => $args)); } return $functions; }
/** * @param string $name * @param \ReflectionFunction $reflection * * @throws \RuntimeException */ public function __construct($name, \ReflectionFunction $reflection = null) { if (!is_string($name) || empty($name)) { throw new \RuntimeException('Name should be string and not empty'); } $this->name = $name; if ($reflection) { if ($reflection->getName() != $name) { throw new \RuntimeException('Reflection getName not equal with name which you provides'); } $this->setReflection($reflection); } else { if (function_exists($name)) { $reflection = $this->getReflection(); } } if ($reflection && $reflection->isInternal()) { throw new \RuntimeException('You can not works with internal PHP functions, only user defined'); } $this->arguments = new Arguments(array(), $reflection); }
/** * Print cUrl options * * @param array $options */ public static function printOptions($options) { if ($options instanceof \Traversable || is_array($options)) { foreach ($options as $key => $value) { $key = self::getOptionName($key); switch (gettype($value)) { case 'array': echo "{$key} => " . print_r($value, true) . PHP_EOL; break; case 'object': $func = new \ReflectionClass($value); echo "{$key} => class " . $func->getName() . PHP_EOL; break; case 'function': $func = new \ReflectionFunction($value); echo "{$key} => function " . $func->getName() . PHP_EOL; break; default: echo "{$key} => {$value}" . PHP_EOL; break; } } } }
/** * Returns the signature of a function. * * @param ReflectionFunction $function * @return string * @since Method available since Release 3.3.2 * @todo Find a better place for this method. */ public static function getFunctionSignature(ReflectionFunction $function) { if ($function->returnsReference()) { $reference = '&'; } else { $reference = ''; } return sprintf('function %s%s(%s)', $reference, $function->getName(), self::getMethodParameters($function)); }
/** * Factory. * * @param ReflectionFunction|ReflectionMethod $function * @param array $codeCoverage * @return PHPUnit_Util_Metrics_Method */ public static function factory($function, &$codeCoverage = array()) { if ($function instanceof ReflectionMethod) { $scope = $function->getDeclaringClass()->getName(); } else { $scope = 'global'; } $name = $function->getName(); if (!isset(self::$cache[$scope][$name])) { self::$cache[$scope][$name] = new PHPUnit_Util_Metrics_Function($scope, $function, $codeCoverage); } else { if (!empty($codeCoverage) && self::$cache[$scope][$name]->getCoverage() == 0) { self::$cache[$scope][$name]->setCoverage($codeCoverage); } } return self::$cache[$scope][$name]; }
/** * cfdump-style debugging output * @param $var The variable to output. * @param $limit Maximum recursion depth for arrays (default 0 = all) * @param $label text to display in complex data type header * @param $depth Current depth (default 0) */ public function dump(&$var, $limit = 0, $label = '', $depth = 0) { if (!is_int($depth)) $depth = 0; if (!is_int($limit)) $limit = 0; if (($limit > 0) && ($depth >= $limit)) return; static $seen = array(); $he = function ($s) { return htmlentities($s); }; $tabs = "\n" . str_repeat("\t", $depth); $depth++; $printCount = 0; $self = $this; $echoFunction = function($var, $tabs, $limit = 0, $label = '', $depth = 0) use ($self) { if (!is_subclass_of($var, 'ReflectionFunctionAbstract')) { $var = new \ReflectionFunction($var); } echo "$tabs<table class=\"dump function depth${depth}\">$tabs<thead><tr><th>" . ($label != '' ? $label . ' - ' : '') . (is_callable(array($var, 'getModifiers')) ? htmlentities(implode(' ', \Reflection::getModifierNames($var->getModifiers()))) : '') . " function " . htmlentities($var->getName()) . "</th></tr></thead>$tabs<tbody>"; echo "$tabs<tr><td class=\"value\">$tabs<table class=\"dump layout\">$tabs<tr><th>Parameters:</th><td>"; $params = $var->getParameters(); if (count($params) > 0) { echo "</td></tr>$tabs<tr><td colspan=\"2\">$tabs<table class=\"dump param\">$tabs<thead><tr><th>Name</th><th>Array/Ref</th><th>Required</th><th>Default</th></tr></thead>$tabs<tbody>"; foreach ($params as $param) { echo "$tabs<tr><td>" . htmlentities($param->getName()) . "</td><td>" . ($param->isArray() ? "Array " : "") . ($param->isPassedByReference() ? "Reference" : "") . "</td><td>" . ($param->isOptional() ? "Optional" : "Required") . "</td><td>"; if ($param->isOptional() && $param->isDefaultValueAvailable()) { $self->dump($param->getDefaultValue(), $limit, $label, $depth); } echo "</td></tr>"; } echo "$tabs</tbody>$tabs</table>"; } else { echo "none</td></tr>"; } $comment = trim($var->getDocComment()); if (($comment !== NULL) && ($comment !== '')) { echo "$tabs<tr><th>Doc Comment:</th><td><kbd>" . str_replace("\n", "<br/>", htmlentities($comment)) . "</kbd></td></tr>"; } echo "</table>$tabs</td></tr>"; echo "$tabs</tbody>$tabs</table>"; }; if (!array_key_exists('fw1dumpstarted', $_REQUEST)) { $_REQUEST['fw1dumpstarted'] = TRUE; echo<<<DUMPCSSJS <style type="text/css">/* fw/1 dump */ table.dump { color: black; background-color: white; font-size: xx-small; font-family: verdana,arial,helvetica,sans-serif; border-spacing: 0; border-collapse: collapse; } table.dump th { text-indent: -2em; padding: 0.25em 0.25em 0.25em 2.25em; color: #fff; } table.dump td { padding: 0.25em; } table.dump .key { cursor: pointer; } table.dump td.shh { background-color: #ddd; } table.dump td.shh div { display: none; } table.dump td.shh:before { content: "..."; } table.dump th, table.dump td { border-width: 2px; border-style: solid; border-spacing: 0; vertical-align: top; text-align: left; } table.dump.object, table.dump.object > * > tr > td, table.dump.object > thead > tr > th { border-color: #f00; } table.dump.object > thead > tr > th { background-color: #f44; } table.dump.object > tbody > tr > .key { background-color: #fcc; } table.dump.array, table.dump.array > * > tr > td, table.dump.array > thead > tr > th { border-color: #060; } table.dump.array > thead > tr > th { background-color: #090; } table.dump.array > tbody > tr > .key { background-color: #cfc; } table.dump.struct, table.dump.struct > * > tr > td, table.dump.struct > thead > tr > th { border-color: #00c; } table.dump.struct > thead > tr > th { background-color: #44c; } table.dump.struct > tbody > tr > .key { background-color: #cdf; } table.dump.function, table.dump.function > * > tr > td, table.dump.function > thead > tr > th { border-color: #a40; } table.dump.function > thead > tr > th { background-color: #c60; } table.dump.layout, table.dump.layout > * > tr > td, table.dump.layout > thead > tr > th { border-color: #fff; } table.dump.layout > * > tr > th { font-style: italic; background-color: #fff; color: #000; font-weight: normal; border: none; } table.dump.param, table.dump.param > * > tr > td, table.dump.param > thead > tr > th { border-color: #ddd; } table.dump.param > thead > tr > th { background-color: #eee; color: black; font-weight: bold; } </style> <script type="text/javascript" language="JavaScript"> (function(w,d){ var addEvent = function(o,t,f) { if (o.addEventListener) o.addEventListener(t,f,false); else if (o.attachEvent) { o['e' + t + f] = f; o[t + f] = function() { o['e' + t + f](w.event); } o.attachEvent('on' + t, o[t + f]); } }; // addEvent var clickCell = function(e) { var target = e.target || this; var sib = target.nextSibling; if (sib && sib.tagName && (sib.tagName.toLowerCase() === 'td')) { if (/(^|\s)shh(\s|$)/.test(sib.className)) sib.className = sib.className.replace(/(^|\s)shh(\s|$)/, ' '); else sib.className += ' shh'; } if (e && e.stopPropagation) e.stopPropagation(); else w.event.cancelBubble = true; return false; }; // clickCell var collapsifyDumps = function() { setTimeout(function() { var tables = document.getElementsByTagName('table'); for(var t = 0; t < tables.length; t++) { var table = tables[t]; var dumpPattern = /(^|\s)dump(\s|$)/; var depthPattern = /(^|\s)depth1(\s|$)/; if (! (dumpPattern.test(table.className) && depthPattern.test(table.className) )) continue; var cells = table.getElementsByTagName('td'); var keyPattern = /(^|\s)key(\s|$)/; var keyCount = 0; for (var c = 0; c < cells.length; c++) { var cell = cells[c]; if (! (keyPattern.test(cell.className))) continue; addEvent(cell, 'click', clickCell); } // for k } // for t }, 250); }; // collapsify dumps if (d.addEventListener) d.addEventListener("DOMContentLoaded", collapsifyDumps, false); else d.onreadystatechange = function() { if (d.readyState === 'interactive') collapsifyDumps(this); }; })(window,document); </script> DUMPCSSJS; } if (is_array($var)) { // It turns out that identity (===) in PHP isn't actually identity. It's more like "do you look similar enough to fool an untrained observer?". Lame! // $label = $label === '' ? (($var === $_POST) ? '$_POST' : (($var === $_GET) ? '$_GET' : (($var === $_COOKIE) ? '$_COOKIE' : (($var === $_ENV) ? '$_ENV' : (($var === $_FILES) ? '$_FILES' : (($var === $_REQUEST) ? '$_REQUEST' : (($var === $_SERVER) ? '$_SERVER' : (isset($_SESSION) && ($var === $_SESSION) ? '$_SESSION' : '')))))))) : $label; $c = count($var); if(isset($var['fw1recursionsentinel'])) { echo "(Recursion)"; } $aclass = (($c > 0) && array_key_exists(0, $var) && array_key_exists($c - 1, $var)) ? 'array' : 'struct'; $var['fw1recursionsentinel'] = TRUE; echo "$tabs<table class=\"dump ${aclass} depth${depth}\">$tabs<thead><tr><th colspan=\"2\">" . ($label != '' ? $label . ' - ' : '') . "array" . ($c > 0 ? "" : " [empty]") . "</th></tr></thead>$tabs<tbody>"; foreach ($var as $index => $aval) { if ($index === 'fw1recursionsentinel') continue; echo "$tabs<tr><td class=\"key\">" . $he($index) . "</td><td class=\"value\"><div>"; $this->dump($aval, $limit, '', $depth); echo "</div></td></tr>"; $printCount++; if (($limit > 0) && ($printCount >= $limit) && ($aclass === 'array')) break; } echo "$tabs</tbody>$tabs</table>"; // unset($var['fw1recursionsentinel']); } elseif (is_string($var)) { echo $var === '' ? '[EMPTY STRING]' : htmlentities($var); } elseif (is_bool($var)) { echo $var ? "TRUE" : "FALSE"; } elseif (is_callable($var) || (is_object($var) && is_subclass_of($var, 'ReflectionFunctionAbstract'))) { $echoFunction($var, $tabs, $limit, $label, $depth); } elseif (is_float($var)) { echo "(float) " . htmlentities($var); } elseif (is_int($var)) { echo "(int) " . htmlentities($var); } elseif (is_null($var)) { echo "NULL"; } elseif (is_object($var)) { $ref = new \ReflectionObject($var); $parent = $ref->getParentClass(); $interfaces = implode("<br/>implements ", $ref->getInterfaceNames()); /* try { $serial = serialize($var); } catch (\Exception $e) { $serial = 'hasclosure' . $ref->getName(); } $objHash = 'o' . md5($serial); */ $objHash = spl_object_hash($var); $refHash = 'r' . md5($ref); echo "$tabs<table class=\"dump object depth${depth}\"" . (isset($seen[$refHash]) ? "" : "id=\"$refHash\"") . ">$tabs<thead>$tabs<tr><th colspan=\"2\">" . ($label != '' ? $label . ' - ' : '') . "object " . htmlentities($ref->getName()) . ($parent ? "<br/>extends " .$parent->getName() : "") . ($interfaces !== '' ? "<br/>implements " . $interfaces : "") . "</th></tr>$tabs<tbody>"; if (isset($seen[$objHash])) { echo "$tabs<tr><td colspan=\"2\"><a href=\"#$refHash\">[see above for details]</a></td></tr>"; } else { $seen[$objHash] = TRUE; $constants = $ref->getConstants(); if (count($constants) > 0) { echo "$tabs<tr><td class=\"key\">CONSTANTS</td><td class=\"values\"><div>$tabs<table class=\"dump object\">"; foreach ($constants as $constant => $cval) { echo "$tabs<tr><td class=\"key\">" . htmlentities($constant) . "</td><td class=\"value constant\"><div>"; $this->dump($cval, $limit, '', $depth + 1); echo "</div></td></tr>"; } echo "$tabs</table>$tabs</div></td></tr>"; } $properties = $ref->getProperties(); if (count($properties) > 0) { echo "$tabs<tr><td class=\"key\">PROPERTIES</td><td class=\"values\"><div>$tabs<table class=\"dump object\">"; foreach ($properties as $property) { echo "$tabs<tr><td class=\"key\">" . htmlentities(implode(' ', \Reflection::getModifierNames($property->getModifiers()))) . " " . $he($property->getName()) . "</td><td class=\"value property\"><div>"; $wasHidden = $property->isPrivate() || $property->isProtected(); $property->setAccessible(TRUE); $propertyValue = $property->getValue($var); $this->dump($propertyValue, $limit, '', $depth + 1); if ($wasHidden) { $property->setAccessible(FALSE); } echo "</div></td></tr>"; } echo "$tabs</table>$tabs</div></td></tr>"; } $methods = $ref->getMethods(); if (count($methods) > 0) { echo "$tabs<tr><td class=\"key\">METHODS</td><td class=\"values shh\"><div>"; if (isset($seen[$refHash])) { echo "<a href=\"#$refHash\">[see above for details]</a>"; } else { $seen[$refHash] = TRUE; echo "$tabs<table class=\"dump object\">"; foreach ($methods as $method) { echo "$tabs<tr><td class=\"key\">" . htmlentities($method->getName()) . "</td><td class=\"value function\"><div>"; $echoFunction($method, $tabs, $limit, '', $depth + 1); echo "</div></td></tr>"; } echo "$tabs</table>"; } echo "$tabs</div></td></tr>"; } } echo "$tabs</tbody>$tabs</table>"; } elseif (is_resource($var)) { echo "(Resource)"; } elseif (is_numeric($var)) { echo htmlentities($var); } elseif (is_scalar($var)) { echo htmlentities($var); } else { echo gettype($var); } } // dump
/** * cfdump-style debugging output * @param $var The variable to output. * @param $limit Maximum recursion depth for arrays (default 0 = all) * @param $label text to display in complex data type header * @param $depth Current depth (default 0) */ public function dump(&$var, $limit = 0, $label = '', $depth = 0) { if ($limit > 0 && $depth >= $limit) { return; } static $seen = array(); $he = function ($s) { return htmlentities($s); }; $self = $this; $echoFunction = function ($var, $tabs, $label = '') use($self) { if (!is_subclass_of($var, 'ReflectionFunctionAbstract')) { $var = new \ReflectionFunction($var); } echo "{$tabs}<table class=\"dump function\">{$tabs}<thead><tr><th>" . ($label != '' ? $label . ' - ' : '') . (is_callable(array($var, 'getModifiers')) ? htmlentities(implode(' ', \Reflection::getModifierNames($var->getModifiers()))) : '') . " function " . htmlentities($var->getName()) . "</th></tr></thead>{$tabs}<tbody>"; echo "{$tabs}<tr><td class=\"value\">{$tabs}<table class=\"dump layout\">{$tabs}<tr><th>Parameters:</th><td>"; $params = $var->getParameters(); if (count($params) > 0) { echo "</td></tr>{$tabs}<tr><td colspan=\"2\">{$tabs}<table class=\"dump param\">{$tabs}<thead><tr><th>Name</th><th>Array/Ref</th><th>Required</th><th>Default</th></tr></thead>{$tabs}<tbody>"; foreach ($params as $param) { echo "{$tabs}<tr><td>" . htmlentities($param->getName()) . "</td><td>" . ($param->isArray() ? "Array " : "") . ($param->isPassedByReference() ? "Reference" : "") . "</td><td>" . ($param->isOptional() ? "Optional" : "Required") . "</td><td>"; if ($param->isOptional()) { $self->dump($param->getDefaultValue()); } echo "</td></tr>"; } echo "{$tabs}</tbody>{$tabs}</table>"; } else { echo "none</td></tr>"; } $comment = trim($var->getDocComment()); if ($comment !== NULL && $comment !== '') { echo "{$tabs}<tr><th>Doc Comment:</th><td><kbd>" . str_replace("\n", "<br/>", htmlentities($comment)) . "</kbd></td></tr>"; } echo "</table>{$tabs}</td></tr>"; echo "{$tabs}</tbody>{$tabs}</table>"; }; $tabs = "\n" . str_repeat("\t", $depth); $depth++; $printCount = 0; if (!array_key_exists('fw1dumpstarted', $_REQUEST)) { $_REQUEST['fw1dumpstarted'] = TRUE; echo <<<DUMPCSS <style type="text/css">/* fw/1 dump */ table.dump { color: black; background-color: white; font-size: xx-small; font-family: verdana,arial,helvetica,sans-serif; border-spacing: 0; border-collapse: collapse; } table.dump th { text-indent: -2em; padding: 0.25em 0.25em 0.25em 2.25em; color: #fff; } table.dump td { padding: 0.25em; } table.dump th, table.dump td { border-width: 2px; border-style: solid; border-spacing: 0; vertical-align: top; text-align: left; } table.dump.object, table.dump.object td, table.dump.object th { border-color: #f00; } table.dump.object th { background-color: #f44; } table.dump.object .key { background-color: #fcc; } table.dump.array, table.dump.array td, table.dump.array th { border-color: #060; } table.dump.array th { background-color: #090; } table.dump.array .key { background-color: #cfc; } table.dump.struct, table.dump.struct td, table.dump.struct th { border-color: #00c; } table.dump.struct th { background-color: #44c; } table.dump.struct .key { background-color: #cdf; } table.dump.function, table.dump.function td, table.dump.function th { border-color: #a40; } table.dump.function th { background-color: #c60; } table.dump.layout, table.dump.layout td, table.dump.layout th { border-color: #fff; } table.dump.layout th { font-style: italic; background-color: #fff; color: #000; font-weight: normal; } table.dump.param, table.dump.param td, table.dump.param th { border-color: #ddd; } table.dump.param th { background-color: #eee; color: black; font-weight: bold; } </style> DUMPCSS; } if (is_array($var)) { $label = $label === '' ? $var === $_POST ? '$_POST' : ($var === $_GET ? '$_GET' : ($var === $_COOKIE ? '$_COOKIE' : ($var === $_ENV ? '$_ENV' : ($var === $_FILES ? '$_FILES' : ($var === $_REQUEST ? '$_REQUEST' : ($var === $_SERVER ? '$_SERVER' : ($var === $_SESSION ? '$_SESSION' : ''))))))) : $label; $c = count($var); if (isset($var['fw1recursionsentinel'])) { echo "(Recursion)"; } $aclass = $c > 0 && array_key_exists(0, $var) && array_key_exists($c - 1, $var) ? 'array' : 'struct'; $var['fw1recursionsentinel'] = true; echo "{$tabs}<table class=\"dump {$aclass}\">{$tabs}<thead><tr><th colspan=\"2\">" . ($label != '' ? $label . ' - ' : '') . "array" . ($c > 0 ? "" : " [empty]") . "</th></tr></thead>{$tabs}<tbody>"; foreach ($var as $index => $aval) { if ($index === 'fw1recursionsentinel') { continue; } echo "{$tabs}<tr><td class=\"key\">" . $he($index) . "</td><td class=\"value\">"; $this->dump($aval, $limit, '', $depth); echo "</td></tr>"; $printCount++; if ($limit > 0 && $printCount >= $limit && $aclass === 'array') { break; } } echo "{$tabs}</tbody>{$tabs}</table>"; // unset($var['fw1recursionsentinel']); } elseif (is_string($var)) { echo $var === '' ? '[EMPTY STRING]' : htmlentities($var); } elseif (is_bool($var)) { echo $var ? "TRUE" : "FALSE"; } elseif (is_callable($var) || is_object($var) && is_subclass_of($var, 'ReflectionFunctionAbstract')) { $echoFunction($var, $tabs, $label); } elseif (is_float($var)) { echo "(float) " . htmlentities($var); } elseif (is_int($var)) { echo "(int) " . htmlentities($var); } elseif (is_null($var)) { echo "NULL"; } elseif (is_object($var)) { $ref = new \ReflectionObject($var); $parent = $ref->getParentClass(); $interfaces = implode("<br/>implements ", $ref->getInterfaceNames()); try { $serial = serialize($var); } catch (\Exception $e) { $serial = 'hasclosure' . $ref->getName(); } $objHash = 'o' . md5($serial); $refHash = 'r' . md5($ref); echo "{$tabs}<table class=\"dump object\"" . (isset($seen[$refHash]) ? "" : "id=\"{$refHash}\"") . ">{$tabs}<thead>{$tabs}<tr><th colspan=\"2\">" . ($label != '' ? $label . ' - ' : '') . "object " . htmlentities($ref->getName()) . ($parent ? "<br/>extends " . $parent->getName() : "") . ($interfaces !== '' ? "<br/>implements " . $interfaces : "") . "</th></tr>{$tabs}<tbody>"; if (isset($seen[$objHash])) { echo "{$tabs}<tr><td colspan=\"2\"><a href=\"#{$refHash}\">[see above for details]</a></td></tr>"; } else { $seen[$objHash] = TRUE; $constants = $ref->getConstants(); if (count($constants) > 0) { echo "{$tabs}<tr><td class=\"key\">CONSTANTS</td><td class=\"values\">{$tabs}<table class=\"dump object\">"; foreach ($constants as $constant => $cval) { echo "{$tabs}<tr><td class=\"key\">" . htmlentities($constant) . "</td><td class=\"value constant\">"; $this->dump($cval, $limit, '', $depth); echo "</td></tr>"; } echo "{$tabs}</table>{$tabs}</td></tr>"; } $properties = $ref->getProperties(); if (count($properties) > 0) { echo "{$tabs}<tr><td class=\"key\">PROPERTIES</td><td class=\"values\">{$tabs}<table class=\"dump object\">"; foreach ($properties as $property) { echo "{$tabs}<tr><td class=\"key\">" . htmlentities(implode(' ', \Reflection::getModifierNames($property->getModifiers()))) . " " . $he($property->getName()) . "</td><td class=\"value property\">"; $wasHidden = $property->isPrivate() || $property->isProtected(); $property->setAccessible(TRUE); $this->dump($property->getValue($var), $limit, '', $depth); if ($wasHidden) { $property->setAccessible(FALSE); } echo "</td></tr>"; } echo "{$tabs}</table>{$tabs}</td></tr>"; } $methods = $ref->getMethods(); if (count($methods) > 0) { echo "{$tabs}<tr><td class=\"key\">METHODS</td><td class=\"values\">"; if (isset($seen[$refHash])) { echo "<a href=\"#{$refHash}\">[see above for details]</a>"; } else { $seen[$refHash] = TRUE; echo "{$tabs}<table class=\"dump object\">"; foreach ($methods as $method) { echo "{$tabs}<tr><td class=\"key\">" . htmlentities($method->getName()) . "</td><td class=\"value function\">"; $echoFunction($method, $tabs, ''); echo "</td></tr>"; } echo "{$tabs}</table>"; } echo "{$tabs}</td></tr>"; } } echo "{$tabs}</tbody>{$tabs}</table>"; } elseif (is_resource($var)) { echo "(Resource)"; } elseif (is_numeric($var)) { echo htmlentities($var); } elseif (is_scalar($var)) { echo htmlentities($var); } else { echo gettype($var); } }
/** * Resolve dependencies for a function. * * This method can be used to implement similar functionality as provided by [[invoke()]] in other * components. * * @param callable $callback callable to be invoked. * @param array $params The array of parameters for the function, can be either numeric or associative. * @return array The resolved dependencies. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. * @since 2.0.7 */ public function resolveCallableDependencies(callable $callback, $params = []) { if (is_array($callback)) { $reflection = new \ReflectionMethod($callback[0], $callback[1]); } else { $reflection = new \ReflectionFunction($callback); } $args = []; $associative = ArrayHelper::isAssociative($params); foreach ($reflection->getParameters() as $param) { $name = $param->getName(); if (($class = $param->getClass()) !== null) { $className = $class->getName(); if ($associative && isset($params[$name]) && $params[$name] instanceof $className) { $args[] = $params[$name]; unset($params[$name]); } elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) { $args[] = array_shift($params); } elseif (Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) { $args[] = $obj; } else { $args[] = $this->get($className); } } elseif ($associative && isset($params[$name])) { $args[] = $params[$name]; unset($params[$name]); } elseif (!$associative && count($params)) { $args[] = array_shift($params); } elseif ($param->isDefaultValueAvailable()) { $args[] = $param->getDefaultValue(); } elseif (!$param->isOptional()) { $funcName = $reflection->getName(); throw new InvalidConfigException("Missing required parameter \"{$name}\" when calling \"{$funcName}\"."); } } foreach ($params as $value) { $args[] = $value; } return $args; }
<?php namespace foo; $a = function () { }; $r = new \ReflectionFunction($a); var_dump($r->inNamespace()); var_dump($r->getNamespaceName()); var_dump($r->getName());
/** * Get all info about function * @param string|function $functionName Function or function name * @return array|bool */ protected static function _getFunction($functionName) { if (is_string($functionName) && !function_exists($functionName)) { return false; } elseif (empty($functionName)) { return false; } // create ReflectionFunction instance $func = new ReflectionFunction($functionName); // get basic function info $result = array(); $result['name'] = $func->getName(); $result['type'] = $func->isInternal() ? 'internal' : 'user-defined'; if (method_exists($func, 'getNamespaceName') && ($namespace = $func->getNamespaceName())) { $result['namespace'] = $namespace; } if ($func->isDeprecated()) { $result['deprecated'] = true; } if ($static = $func->getStaticVariables()) { $result['static'] = $static; } if ($reference = $func->returnsReference()) { $result['reference'] = $reference; } if ($path = $func->getFileName()) { $result['path'] = $path . ' ' . $func->getStartLine() . '/' . $func->getEndLine(); } if ($parameters = $func->getParameters()) { $result['parameters'] = self::_getParams($parameters, $func->isInternal()); } // get function source if (isset($result['path']) && $result['path']) { $result['comment'] = $func->getDocComment(); $startLine = $func->getStartLine(); $endLine = $func->getEndLine(); $source = @file($func->getFileName()); if ($startLine && $source) { $from = (int) ($startLine - 1); $to = (int) ($endLine - $startLine + 1); $slice = array_slice($source, $from, $to); $result['source::source'] = implode('', $slice); } } return $result; }
/** * Show reflection * * Show reflection * * <code> * Panda_Debug::reflect('BEAR_Form'); // Class * Panda_Debug::reflect($obj); // Objecy * Panda_Debug::reflect('p'); // Function * </code> * * @param string $target target * @param boll $cehckParent check parent class * * @return void */ public static function reflect($target, $cehckParent = false) { if (is_object($target)) { $target = get_class($target); } switch (true) { case function_exists($target): $ref = new ReflectionFunction($target); $info['name'] = $ref->isInternal() ? 'The internal ' : 'The user-defined '; $info['name'] .= $targetName = $ref->getName(); $info['declare in'] = $ref->getFileName() . ' lines ' . $ref->getStartLine() . ' to ' . $ref->getEndline(); $info['Documentation'] = $ref->getDocComment(); $statics = $ref->getStaticVariables(); if ($statics) { $info['Static variables'] = $statics; } $type = 'function'; break; case class_exists($target, false): $ref = new ReflectionClass($target); $type = 'class'; $info['name'] = $ref->isInternal() ? 'The internal ' : 'The user-defined '; $info['name'] .= $ref->isAbstract() ? ' abstract ' : ''; $info['name'] .= $ref->isFinal() ? ' final ' : ''; $info['name'] .= $ref->isInterface() ? 'interface ' : 'class '; $info['name'] .= $targetName = $ref->getName(); $info['declare in'] = $ref->getFileName() . ' lines ' . $ref->getStartLine() . ' to ' . $ref->getEndline(); $info['modifiers'] = Reflection::getModifierNames($ref->getModifiers()); $info['Documentation'] = $ref->getDocComment(); $info['Implements'] = $ref->getInterfaces(); $info['Constants'] = $ref->getConstants(); foreach ($ref->getProperties() as $prop) { // ReflectionProperty クラスのインスタンスを生成する $propRef = new ReflectionProperty($targetName, $prop->name); if ($propRef->isPublic()) { $porps[] = $prop->name; } } // $info['Public Properties'] = $porps; foreach ($ref->getMethods() as $method) { $methodRef = new ReflectionMethod($targetName, $method->name); if ($methodRef->isPublic() || $method->isStatic()) { $final = $method->isFinal() ? 'final ' : ''; $pubic = $method->isPublic() ? 'public ' : ''; $static = $method->isStatic() ? ' static ' : ''; $methods[] = sprintf("%s%s%s %s", $final, $pubic, $static, $method->name); } } $info['Public Methods'] = $methods; if ($ref->isInstantiable() && is_object($target)) { $info['isInstance ?'] = $ref->isInstance($target) ? 'yes' : 'no'; } if ($parent) { $info['parent'] .= $ref->getParentClass(); } break; default: $type = 'Invalid Object/Class'; $targetName = $target; $info = null; break; } print_a($info, "show_objects:1;label: Reflection of {$type} '{$targetName}'"); }
function show_info($function, $basic = 0) { $func = new ReflectionFunction($function); $ret = ''; $ret .= "<pre><strong>Information:</strong>\n" . var_export($func->getDocComment(), 1) . "</pre>\n"; if ($basic) { $ret .= "<pre><pre>===> The " . ($func->isInternal() ? 'internal' : 'user-defined') . " function '" . $func->getName() . "'\n" . "\tdeclared in " . $func->getFileName() . "\n\tlines " . $func->getStartLine() . " to " . $func->getEndline() . "</pre>\n"; } return $ret; }
/** * * * @param mixed $value * @return mixed */ function closure_name($closure) { $closure_ref = new ReflectionFunction($closure); return $closure_ref->getName(); }
/** * @param \ReflectionFunction $reflection */ public function __construct($reflection) { $this->reflection = $reflection; $this->location = ['class' => null, 'directory' => dirname($this->reflection->getFileName()), 'file' => $this->reflection->getFileName(), 'function' => $this->reflection->getName(), 'line' => $this->reflection->getStartLine(), 'method' => null, 'namespace' => null, 'trait' => null]; }
/** * @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); }
/** * Invoke callback with resolved dependecies parameters. * @param callable $callback callable to be invoked. * @param array $params callback paramater. * @return mixed the callback return value. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. * @since 2.0.7 */ public function invoke($callback, $params = []) { if (is_callable($callback)) { if (is_array($callback)) { $reflection = new \ReflectionMethod($callback[0], $callback[1]); } else { $reflection = new \ReflectionFunction($callback); } $args = []; foreach ($reflection->getParameters() as $param) { $name = $param->getName(); if (($class = $param->getClass()) !== null) { $className = $class->getName(); if (isset($params[0]) && $params[0] instanceof $className) { $args[] = array_shift($params); } elseif (\Yii::$app->has($name) && ($obj = \Yii::$app->get($name)) instanceof $className) { $args[] = $obj; } else { $args[] = $this->get($className); } } elseif (count($params)) { $args[] = array_shift($params); } elseif ($param->isDefaultValueAvailable()) { $args[] = $param->getDefaultValue(); } elseif (!$param->isOptional()) { $funcName = $reflection->getName(); throw new InvalidConfigException("Missing required parameter \"{$name}\" when calling \"{$funcName}\"."); } } foreach ($params as $value) { $args[] = $value; } return call_user_func_array($callback, $args); } else { return call_user_func_array($callback, $params); } }
/** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $responseHeaders = $response->headers->all(); $cookies = array(); foreach ($response->headers->getCookies() as $cookie) { $cookies[] = $this->getCookieHeader($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly()); } if (count($cookies) > 0) { $responseHeaders['Set-Cookie'] = $cookies; } $attributes = array(); foreach ($request->attributes->all() as $key => $value) { if ('_route' === $key && is_object($value)) { $attributes['_route'] = $this->varToString($value->getPath()); } elseif ('_route_params' === $key) { foreach ($value as $key => $v) { $attributes['_route_params'][$key] = $this->varToString($v); } } else { $attributes[$key] = $this->varToString($value); } } $content = null; try { $content = $request->getContent(); } catch (\LogicException $e) { // the user already got the request content as a resource $content = false; } $sessionMetadata = array(); $sessionAttributes = array(); $flashes = array(); if ($request->hasSession()) { $session = $request->getSession(); if ($session->isStarted()) { $sessionMetadata['Created'] = date(DATE_RFC822, $session->getMetadataBag()->getCreated()); $sessionMetadata['Last used'] = date(DATE_RFC822, $session->getMetadataBag()->getLastUsed()); $sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime(); $sessionAttributes = $session->all(); $flashes = $session->getFlashBag()->peekAll(); } } $statusCode = $response->getStatusCode(); $this->data = array('format' => $request->getRequestFormat(), 'content' => $content, 'content_type' => $response->headers->get('Content-Type', 'text/html'), 'status_text' => isset(Response::$statusTexts[$statusCode]) ? Response::$statusTexts[$statusCode] : '', 'status_code' => $statusCode, 'request_query' => $request->query->all(), 'request_request' => $request->request->all(), 'request_headers' => $request->headers->all(), 'request_server' => $request->server->all(), 'request_cookies' => $request->cookies->all(), 'request_attributes' => $attributes, 'response_headers' => $responseHeaders, 'session_metadata' => $sessionMetadata, 'session_attributes' => $sessionAttributes, 'flashes' => $flashes, 'path_info' => $request->getPathInfo(), 'controller' => 'n/a', 'locale' => $request->getLocale()); if (isset($this->data['request_headers']['php-auth-pw'])) { $this->data['request_headers']['php-auth-pw'] = '******'; } if (isset($this->data['request_server']['PHP_AUTH_PW'])) { $this->data['request_server']['PHP_AUTH_PW'] = '******'; } if (isset($this->controllers[$request])) { $controller = $this->controllers[$request]; if (is_array($controller)) { try { $r = new \ReflectionMethod($controller[0], $controller[1]); $this->data['controller'] = array('class' => is_object($controller[0]) ? get_class($controller[0]) : $controller[0], 'method' => $controller[1], 'file' => $r->getFilename(), 'line' => $r->getStartLine()); } catch (\ReflectionException $re) { if (is_callable($controller)) { // using __call or __callStatic $this->data['controller'] = array('class' => is_object($controller[0]) ? get_class($controller[0]) : $controller[0], 'method' => $controller[1], 'file' => 'n/a', 'line' => 'n/a'); } } } elseif ($controller instanceof \Closure) { $r = new \ReflectionFunction($controller); $this->data['controller'] = array('class' => $r->getName(), 'method' => null, 'file' => $r->getFilename(), 'line' => $r->getStartLine()); } else { $this->data['controller'] = (string) $controller ?: 'n/a'; } unset($this->controllers[$request]); } }
public static function populate_callback(array $callback) { if (is_string($callback['function']) and false !== strpos($callback['function'], '::')) { $callback['function'] = explode('::', $callback['function']); } try { if (is_array($callback['function'])) { if (is_object($callback['function'][0])) { $class = get_class($callback['function'][0]); $access = '->'; } else { $class = $callback['function'][0]; $access = '::'; } $callback['name'] = $class . $access . $callback['function'][1] . '()'; $ref = new ReflectionMethod($class, $callback['function'][1]); } else { if (is_object($callback['function'])) { if (is_a($callback['function'], 'Closure')) { $ref = new ReflectionFunction($callback['function']); $file = trim(QM_Util::standard_dir($ref->getFileName(), ''), '/'); $callback['name'] = sprintf(__('Closure on line %1$d of %2$s', 'query-monitor'), $ref->getStartLine(), $file); } else { // the object should have a __invoke() method $class = get_class($callback['function']); $callback['name'] = $class . '->__invoke()'; $ref = new ReflectionMethod($class, '__invoke'); } } else { $callback['name'] = $callback['function'] . '()'; $ref = new ReflectionFunction($callback['function']); } } $callback['file'] = $ref->getFileName(); $callback['line'] = $ref->getStartLine(); if ('__lambda_func' === $ref->getName()) { if (preg_match('|(?P<file>.*)\\((?P<line>[0-9]+)\\)|', $callback['file'], $matches)) { $callback['file'] = $matches['file']; $callback['line'] = $matches['line']; $file = trim(QM_Util::standard_dir($callback['file'], ''), '/'); $callback['name'] = sprintf(__('Anonymous function on line %1$d of %2$s', 'query-monitor'), $callback['line'], $file); } } $callback['component'] = self::get_file_component($callback['file']); } catch (ReflectionException $e) { $callback['error'] = new WP_Error('reflection_exception', $e->getMessage()); } return $callback; }