/** * get Closure info * @param Closure $c * @return array */ function closure_dump(Closure $c) { $str = 'function ('; $r = new ReflectionFunction($c); $params = array(); foreach ($r->getParameters() as $p) { $s = ''; if ($p->isArray()) { $s .= 'array '; } else { if ($p->getClass()) { $s .= $p->getClass()->name . ' '; } } if ($p->isPassedByReference()) { $s .= '&'; } $s .= '$' . $p->name; if ($p->isOptional()) { $s .= ' = ' . var_export($p->getDefaultValue(), TRUE); } $params[] = $s; } $str .= implode(', ', $params); $str .= '){' . PHP_EOL; $lines = file($r->getFileName()); for ($l = $r->getStartLine(); $l < $r->getEndLine(); $l++) { $str .= $lines[$l]; } $arr = ['file' => $r->getFileName(), 'line' => $r->getStartLine() . '-' . $r->getEndLine(), 'source' => $str]; return $arr; }
/** * @link http://php.net/manual/en/serializable.serialize.php */ public function serialize() { // prepare code $file = new SplFileObject($this->reflection->getFileName()); $file->seek($this->reflection->getStartLine() - 1); $code = ''; while ($file->key() < $this->reflection->getEndLine()) { $code .= $file->current(); $file->next(); } $start = strpos($code, 'function'); $code = substr($code, $start, strpos($code, '}') - $start + 1); // prepare variables $variables = []; $index = stripos($code, 'use'); // if 'use' keyword found if (false !== $index) { // get the names of the variables inside the use statement $start = strpos($code, '(', $index) + 1; $end = strpos($code, ')', $start); $use_variables = explode(',', substr($code, $start, $end - $start)); $static_variables = $this->reflection->getStaticVariables(); // keep only the variables that appeared in both scopes foreach ($use_variables as $variable) { $variable = trim($variable, '$&'); $variables[$variable] = $static_variables[$variable]; } } return serialize(['code' => $code, 'variables' => $variables]); }
private function parseClosure(\Closure $callback) { $refl = new \ReflectionFunction($callback); // var_dump($refl->getFileName()); // var_dump($refl->getStartLine()); // var_dump($refl->getEndLine()); $body = trim(implode(array_slice(file($refl->getFileName()), $refl->getStartLine(), $refl->getEndLine() - $refl->getStartLine() - 1))); $spec = $this->createSpecification($body, $refl->getFileName(), $refl->getStartLine(), $refl->getEndLine()); return $spec; }
/** * Extract the code from the Closure's file. * * @return string */ protected function getCodeFromFile() { $file = $this->getFile(); $code = ''; // Next, we will just loop through the lines of the file until we get to the end // of the Closure. Then, we will return the complete contents of this Closure // so it can be serialized with these variables and stored for later usage. while ($file->key() < $this->reflection->getEndLine()) { $code .= $file->current(); $file->next(); } $begin = strpos($code, 'function('); return substr($code, $begin, strrpos($code, '}') - $begin + 1); }
protected function export($var, $return = false) { if ($var instanceof Closure) { /* dump anonymous function in to plain code.*/ $ref = new ReflectionFunction($var); $file = new SplFileObject($ref->getFileName()); $file->seek($ref->getStartLine() - 1); $result = ''; while ($file->key() < $ref->getEndLine()) { $result .= $file->current(); $file->next(); } $begin = strpos($result, 'function'); $end = strrpos($result, '}'); $result = substr($result, $begin, $end - $begin + 1); } elseif (is_object($var)) { /* dump object with construct function. */ $result = 'new ' . get_class($var) . '(' . $this->export(get_object_vars($var), true) . ')'; } elseif (is_array($var)) { /* dump array in plain array.*/ $array = array(); foreach ($var as $k => $v) { $array[] = var_export($k, true) . ' => ' . $this->export($v, true); } $result = 'array(' . implode(', ', $array) . ')'; } else { $result = var_export($var, true); } if (!$return) { print $result; } return $result; }
function executeInSubprocess($includeStderr = false) { // Get the path to the ErrorControlChain class $classpath = SS_ClassLoader::instance()->getItemPath('ErrorControlChain'); $suppression = $this->suppression ? 'true' : 'false'; // Start building a PHP file that will execute the chain $src = '<' . "?php\nrequire_once '{$classpath}';\n\n\$chain = new ErrorControlChain();\n\n\$chain->setSuppression({$suppression});\n\n\$chain\n"; // For each step, use reflection to pull out the call, stick in the the PHP source we're building foreach ($this->steps as $step) { $func = new ReflectionFunction($step['callback']); $source = file($func->getFileName()); $start_line = $func->getStartLine() - 1; $end_line = $func->getEndLine(); $length = $end_line - $start_line; $src .= implode("", array_slice($source, $start_line, $length)) . "\n"; } // Finally add a line to execute the chain $src .= "->execute();"; // Now stick it in a temporary file & run it $codepath = TEMP_FOLDER . '/ErrorControlChainTest_' . sha1($src) . '.php'; if ($includeStderr) { $null = '&1'; } else { $null = is_writeable('/dev/null') ? '/dev/null' : 'NUL'; } file_put_contents($codepath, $src); exec("php {$codepath} 2>{$null}", $stdout, $errcode); unlink($codepath); return array(implode("\n", $stdout), $errcode); }
static function castClosure($c) { $a = array(); if (!class_exists('ReflectionFunction', false)) { return $a; } $c = new \ReflectionFunction($c); foreach ($c->getParameters() as $p) { $n = ($p->isPassedByReference() ? '&$' : '$') . $p->getName(); if ($p->isDefaultValueAvailable()) { $a[$n] = $p->getDefaultValue(); } else { $a[] = $n; } } $m = self::META_PREFIX; $a = array($m . 'returnsRef' => true, $m . 'args' => $a); if (!$c->returnsReference()) { unset($a[$m . 'returnsRef']); } $a[$m . 'use'] = array(); if (false === ($a[$m . 'file'] = $c->getFileName())) { unset($a[$m . 'file']); } else { $a[$m . 'lines'] = $c->getStartLine() . '-' . $c->getEndLine(); } if (!($c = $c->getStaticVariables())) { unset($a[$m . 'use']); } else { foreach ($c as $p => &$c) { $a[$m . 'use']['$' . $p] =& $c; } } return $a; }
function loadTemplate($func = null) { if (!$func) { $func = $this->func; } $ref = new \ReflectionFunction($func); $codes = file_get_contents($ref->getFileName()); $parser = PHPTokenParser::getParser($codes); $tmp = file($ref->getFileName()); $start_template = false; $template = ""; for ($i = $ref->getEndLine();; $i++) { if (!isset($tmp[$i])) { break; } $line = $tmp[$i]; //宣言部分の終了 if (!$start_template && strpos($line, "?>") !== false) { $start_template = true; $diff = substr($line, strpos($line, "?>") + strlen("?>")); $template .= ltrim($diff); continue; } if ($start_template) { $template .= $tmp[$i]; } } $template = $parser->cleanup($template); $this->setTemplate($template); }
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); }
public static function updateClassMethodHash($className, $methodName, $closure) { $methodName = strtolower($methodName); if (isset(self::$specialMethods[$methodName]) && self::$specialMethods[$methodName] == 1) { $methodName = "phlexmock_" . $methodName; } $closureRF = new \ReflectionFunction($closure); $paramStr = "()"; $params = []; $closureParams = $closureRF->getParameters(); if (count($closureParams) > 0) { foreach ($closureParams as $closureParam) { $params[] = '$' . $closureParam->getName(); } $paramStr = "(" . implode(",", $params) . ")"; } $sl = $closureRF->getStartLine(); $el = $closureRF->getEndLine(); $closureContainerScript = $closureRF->getFileName(); if (!isset(self::$closureContainerScriptLines[$closureContainerScript])) { self::$closureContainerScriptLines[$closureContainerScript] = explode("\n", file_get_contents($closureRF->getFileName())); } $lines = self::$closureContainerScriptLines[$closureContainerScript]; $code = '$func = function' . $paramStr . ' { ' . implode("\n", array_slice($lines, $sl, $el - $sl - 1)) . ' };'; self::$classMethodHash[$className][$methodName] = $code; }
/** * Get the route information for a given route. * * @param \Illuminate\Routing\Route $route * @return array */ protected function getRouteInformation($route) { if (!is_a($route, 'Illuminate\\Routing\\Route')) { return array(); } $uri = head($route->methods()) . ' ' . $route->uri(); $action = $route->getAction(); $result = array('uri' => $uri ?: '-'); $result = array_merge($result, $action); if (isset($action['controller']) && strpos($action['controller'], '@') !== false) { list($controller, $method) = explode('@', $action['controller']); if (class_exists($controller) && method_exists($controller, $method)) { $reflector = new \ReflectionMethod($controller, $method); } unset($result['uses']); } elseif (isset($action['uses']) && $action['uses'] instanceof \Closure) { $reflector = new \ReflectionFunction($action['uses']); $result['uses'] = $this->formatVar($result['uses']); } if (isset($reflector)) { $filename = ltrim(str_replace(base_path(), '', $reflector->getFileName()), '/'); $result['file'] = $filename . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine(); } if ($before = $this->getBeforeFilters($route)) { $result['before'] = $before; } if ($after = $this->getAfterFilters($route)) { $result['after'] = $after; } return $result; }
/** * Returns the line this function's declaration ends at * * @return integer Line this function's declaration ends at */ public function getEndLine() { if ($this->reflectionSource instanceof ReflectionFunction) { return $this->reflectionSource->getEndLine(); } else { return parent::getEndLine(); } }
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()); }
/** * 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)); }
/** * Get source code of function * * @param string|\Closure $function * @return string */ public static function functionSource($function) : string { // File content $reflection = new \ReflectionFunction($function); $file = file($reflection->getFileName()); $lines = array_slice($file, $startLine = $reflection->getStartLine(), $reflection->getEndLine() - $startLine); // Last row $last = array_pop($lines); array_push($lines, rtrim(mb_substr($last, 0, mb_strrpos($last, '}')))); return static::removeIndent($lines); }
/** * 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)); }
protected function execute(InputInterface $input, OutputInterface $output) { $term = $input->getArgument('search_term'); $listeners = $this->get('event.dispatcher')->getListeners(); $events = array(); foreach ($listeners as $eventName => $handlers) { foreach ($handlers as $order => $listener) { if (is_array($listener)) { list($object, $methodName) = $listener; $priority = 0; $object = get_class($object); // get the priority $objectEvents = $object::getSubscribedEvents(); $eventMethods = $objectEvents[$eventName]; if (is_array($eventMethods)) { foreach ($eventMethods as $eventMethod) { if ($eventMethod[0] == $methodName) { $priority = isset($eventMethod[1]) ? $eventMethod[1] : 0; } } } } else { $reflection = new \ReflectionFunction($listener); $file = new \Message\Cog\Filesystem\File($reflection->getFileName()); $object = $reflection->getNamespaceName() . '\\' . $file->getFilenameWithoutExtension(); $methodName = 'Closure (L:' . $reflection->getStartLine() . ' - L:' . $reflection->getEndLine() . ')'; $priority = ''; } // look for the search term if ($term && strpos(strtolower($object), strtolower($term)) === false && strpos(strtolower($methodName), strtolower($term)) === false && strpos(strtolower($eventName), strtolower($term)) === false) { continue; } $events[] = array($object, $methodName, $eventName, $priority, $order); } } // Sort events by event name, then by order of execution. uasort($events, function ($a, $b) { if ($a[2] == $b[2]) { if ($a[4] == $b[4]) { return 0; } return $a[4] < $b[4] ? -1 : 1; } return $a[2] < $b[2] ? -1 : 1; }); $output->writeln('<info>Found ' . count($events) . ' registered event listeners.</info>'); $table = $this->_getTable($output)->setHeaders(array('Class', 'Method', 'Event', 'Priority')); foreach ($events as $event) { $table->addRow(array($event[0], $event[1], $event[2], $event[3])); } $table->render($output); }
/** * Retrieve instance of service * * @return mixed */ public function getInstance() { $reflectionFunction = new \ReflectionFunction($this->factory); $key = preg_replace_callback("@\\\\(.)@", function ($matches) { return \strtoupper($matches[1]); }, get_class($this)) . '_' . md5($reflectionFunction->getFileName() . $reflectionFunction->getEndLine()); $storedContent = $this->storage->read($key); if ($storedContent !== null) { $service = unserialize($storedContent); } else { $service = call_user_func($this->factory); $this->storage->write($key, serialize($service)); } return $service; }
/** * Makes key from event hook. * * @param callable $hook * * @return string */ private static function make_key($hook) { if (is_array($hook)) { return implode('#', $hook); } if ($hook instanceof \Closure) { $reflection = new \ReflectionFunction($hook); return $reflection->getFileName() . '#' . $reflection->getStartLine() . '#' . $reflection->getEndLine(); } if (is_object($hook)) { /* @var $hook object */ return spl_object_hash($hook); } /* @var $hook string */ return $hook; }
private function getClosureCode(\Closure $closure) { $reflection = new \ReflectionFunction($closure); // Open file and seek to the first line of the closure $file = new \SplFileObject($reflection->getFileName()); $file->seek($reflection->getStartLine() - 1); // Retrieve all of the lines that contain code for the closure $code = ''; while ($file->key() < $reflection->getEndLine()) { $line = $file->current(); $line = ltrim($line); $code .= $line; $file->next(); } return $code; }
/** * Get PHP code string from a closure of function as string * * @param array<string,array|string|integer> $context current compile context * @param object $closure Closure object * * @return string * * @expect 'function($a) {return;}' when input array('flags' => array('standalone' => 0)), function ($a) {return;} * @expect 'function($a) {return;}' when input array('flags' => array('standalone' => 0)), function ($a) {return;} */ protected static function closure($context, $closure) { if (is_string($closure) && preg_match('/(.+)::(.+)/', $closure, $matched)) { $ref = new \ReflectionMethod($matched[1], $matched[2]); } else { $ref = new \ReflectionFunction($closure); } $fname = $ref->getFileName(); $lines = file_get_contents($fname); $file = new \SplFileObject($fname); $file->seek($ref->getStartLine() - 2); $spos = $file->ftell(); $file->seek($ref->getEndLine() - 1); $epos = $file->ftell(); return preg_replace('/^.*?function(\\s+[^\\s\\(]+?)?\\s*\\((.+)\\}.*?\\s*$/s', 'function($2}', static::replaceSafeString($context, substr($lines, $spos, $epos - $spos))); }
function getSourceCode($function = "") { /* (Plugin) Source code from here: https://gist.github.com/engine-andre/5772769 */ $func = new ReflectionFunction($function); $filename = $func->getFileName(); $start_line = $func->getStartLine() - 1; // it's actually - 1, otherwise you wont get the function() block $end_line = $func->getEndLine(); $length = $end_line - $start_line; $source = file($filename); $body = implode("", array_slice($source, $start_line, $length)); return $body; }
protected function buildClosure(&$value) { if ($value instanceof \Closure) { $reflection = new \ReflectionFunction($value); $startLine = $reflection->getStartLine(); $endLine = $reflection->getEndLine(); $file = $reflection->getFileName(); $item = file($file); $content = ''; for ($i = $startLine - 1; $i <= $endLine - 1; $i++) { $content .= $item[$i]; } $start = strpos($content, 'function'); $end = strrpos($content, '}'); $value = '[__start__' . substr($content, $start, $end - $start + 1) . '__end__]'; } }
/** * Evaluates the closure and the code in the reset of the file. This sets * the code for the closure, the namespace it is declared in (if any) and * any applicable namespace imports * @param ReflectionFunction The reflected function of the closure * @return String The code the closure runs */ private function evaluate(\ReflectionFunction $reflection) { $code = ''; $full = ''; $file = new \SplFileObject($reflection->getFileName()); while (!$file->eof()) { if ($file->key() >= $reflection->getStartLine() - 1 && $file->key() < $reflection->getEndLine()) { $code .= $file->current(); } $full .= $file->current(); $file->next(); } //@todo this assumes the function will be the only one on that line $begin = strpos($code, 'function'); //@todo this assumes the } will be the only one on that line $end = strrpos($code, '}'); $this->code = substr($code, $begin, $end - $begin + 1); $this->extractDetail($full); }
function plugininterface_outputfunc($interface_name, $closure) { $str = ''; try { $func = new ReflectionFunction($closure); } catch (ReflectionException $e) { echo $e->getMessage(); return; } $start = $func->getStartLine() - 1; $end = $func->getEndLine() - 1; $filename = $func->getFileName(); $str .= 'Interface: ' . $interface_name . "\n"; $str .= 'FilePath: ' . $filename . "\n"; $str .= 'StartLine: ' . $start . "\n"; $str .= 'EndLine: ' . $end . "\n"; $str .= implode("", array_slice(file($filename), $start, $end - $start + 1)); return $str; }
/** * Get's the next string of hook code to process. * * @return string */ public function getHook() { foreach ($this->hooks as $value) { $hook = '<?php function ' . $value[1] . '(){'; $reflection = new \ReflectionFunction($value[2]); $file = new \SplFileObject($reflection->getFileName()); $file->seek($reflection->getStartLine() - 1); $code = ''; while ($file->key() < $reflection->getEndLine()) { $code .= $file->current(); $file->next(); } $begin = strpos($code, 'function') + 8; $begin = strrpos($code, '{', $begin) + 1; $end = strrpos($code, '}'); $hook .= substr($code, $begin, $end - $begin); $hook .= '}' . PHP_EOL; (yield $value[0] => $hook); } }
/** * Returns the sourcecode of a user-defined class. * * @param string $className * @param string $methodName * @return mixed */ public static function getMethodSource($className, $methodName) { if ($className != 'global') { $function = new ReflectionMethod($className, $methodName); } else { $function = new ReflectionFunction($methodName); } $filename = $function->getFileName(); if (file_exists($filename)) { $file = file($filename); $result = ''; $start = $function->getStartLine() - 1; $end = $function->getEndLine() - 1; for ($line = $start; $line <= $end; $line++) { $result .= $file[$line]; } return $result; } else { return FALSE; } }
static $staticX = 4; static $staticY; print "In f()\n"; $staticX++; $x = $staticX; return $x; } $rf = new ReflectionFunction("f"); print "--- getDocComment(\"f\") ---\n"; var_dump($rf->getDocComment()); print "\n"; print "--- getStartLine(\"f\") ---\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());
private function determinePotentialTokens(\ReflectionFunction $reflection) { // Load the file containing the code for the function. $fileName = $reflection->getFileName(); if (!is_readable($fileName)) { throw new ClosureAnalysisException("Cannot read the file containing the closure: \"{$fileName}\"."); } $code = ''; $file = new \SplFileObject($fileName); $file->seek($reflection->getStartLine() - 1); while ($file->key() < $reflection->getEndLine()) { $code .= $file->current(); $file->next(); } $code = trim($code); if (strpos($code, '<?php') !== 0) { $code = "<?php\n" . $code; } return token_get_all($code); }
public function extract(callable $callback) { $ref = new \ReflectionFunction($callback); $file = new \SplFileObject($ref->getFileName()); $file->seek($ref->getStartLine() - 1); $content = ''; while ($file->key() < $ref->getEndLine()) { $content .= $file->current(); $file->next(); } if (fnmatch('*function*', $content)) { list($dummy, $code) = explode('function', $content, 2); $code = 'function' . $code; $tab = explode('}', $code); $last = end($tab); $code = str_replace('}' . $last, '}', $code); return $code; } return null; }