/** * @param \ReflectionMethod $reflectionMethod * * @return string */ private function getCodeBody(\ReflectionMethod $reflectionMethod) { $reflectionClass = $reflectionMethod->getDeclaringClass(); $length = $reflectionMethod->getEndLine() - $reflectionMethod->getStartLine(); $lines = file($reflectionClass->getFileName()); $code = join(PHP_EOL, array_slice($lines, $reflectionMethod->getStartLine() - 1, $length + 1)); return preg_replace('/.*function[^{]+{/s', '', $code); }
private function parseMethod($class, $method) { $refl = new \ReflectionMethod($class, $method); // 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; }
/** * @param ReflectionMethod $reflectionMethod * * @return string */ private function getCodeBody(\ReflectionMethod $reflectionMethod) { $reflectionClass = $reflectionMethod->getDeclaringClass(); $length = $reflectionMethod->getEndLine() - $reflectionMethod->getStartLine(); $lines = file($reflectionClass->getFileName()); if ($length == 0) { return preg_replace('/.*function.*{/', '', $lines[$reflectionMethod->getStartLine() - 1]); } return join("\n", array_slice($lines, $reflectionMethod->getStartLine(), $length)); }
public function provideControllerCallables() { // make sure we always match the line number $r1 = new \ReflectionMethod($this, 'testControllerInspection'); $r2 = new \ReflectionMethod($this, 'staticControllerMethod'); $r3 = new \ReflectionClass($this); // test name, callable, expected return array(array('"Regular" callable', array($this, 'testControllerInspection'), array('class' => __NAMESPACE__ . '\\RequestDataCollectorTest', 'method' => 'testControllerInspection', 'file' => __FILE__, 'line' => $r1->getStartLine())), array('Closure', function () { return 'foo'; }, array('class' => __NAMESPACE__ . '\\{closure}', 'method' => null, 'file' => __FILE__, 'line' => __LINE__ - 5)), array('Static callback as string', __NAMESPACE__ . '\\RequestDataCollectorTest::staticControllerMethod', array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'staticControllerMethod', 'file' => __FILE__, 'line' => $r2->getStartLine())), array('Static callable with instance', array($this, 'staticControllerMethod'), array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'staticControllerMethod', 'file' => __FILE__, 'line' => $r2->getStartLine())), array('Static callable with class name', array('Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'staticControllerMethod'), array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'staticControllerMethod', 'file' => __FILE__, 'line' => $r2->getStartLine())), array('Callable with instance depending on __call()', array($this, 'magicMethod'), array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'magicMethod', 'file' => 'n/a', 'line' => 'n/a')), array('Callable with class name depending on __callStatic()', array('Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'magicMethod'), array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'magicMethod', 'file' => 'n/a', 'line' => 'n/a')), array('Invokable controller', $this, array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => null, 'file' => __FILE__, 'line' => $r3->getStartLine()))); }
public function testImplementationsAreSynchronized() { $adapterReflector = new ReflectionMethod('ehough_finder_adapter_PhpAdapter', 'searchInDirectory'); $finderReflector = new ReflectionMethod('ehough_finder_Finder', 'searchInDirectory'); $adapterSource = array_slice(file($adapterReflector->getFileName()), $adapterReflector->getStartLine() + 1, $adapterReflector->getEndLine() - $adapterReflector->getStartLine() - 1); $adapterSource = implode('', $adapterSource); $adapterSource = str_replace(array('$this->minDepth', '$this->maxDepth'), array('$minDepth', '$maxDepth'), $adapterSource); $finderSource = array_slice(file($finderReflector->getFileName()), $finderReflector->getStartLine() + 1, $finderReflector->getEndLine() - $finderReflector->getStartLine() - 1); $finderSource = implode('', $finderSource); $this->assertStringEndsWith($adapterSource, $finderSource); }
public static function isValid() { if (!assert_options(ASSERT_ACTIVE)) { return true; } $bt = self::debugBacktrace(null, 1); extract($bt); //to $file, $line, $function, $class, $object, $type, $args if (!$args) { return true; } #speed improve $r = new ReflectionMethod($class, $function); $doc = $r->getDocComment(); $cache_id = $class . $type . $function; preg_match_all('~ [\\r\\n]++ [\\x20\\t]++ \\* [\\x20\\t]++ @param [\\x20\\t]++ \\K #memory reduce ( [_a-z]++[_a-z\\d]*+ (?>[|/,][_a-z]+[_a-z\\d]*)*+ ) #1 types [\\x20\\t]++ &?+\\$([_a-z]++[_a-z\\d]*+) #2 name ~sixSX', $doc, $params, PREG_SET_ORDER); $parameters = $r->getParameters(); //d($args, $params, $parameters); if (count($parameters) > count($params)) { $message = 'phpDoc %d piece(s) @param description expected in %s%s%s(), %s given, ' . PHP_EOL . 'called in %s on line %d ' . PHP_EOL . 'and defined in %s on line %d'; $message = sprintf($message, count($parameters), $class, $type, $function, count($params), $file, $line, $r->getFileName(), $r->getStartLine()); trigger_error($message, E_USER_NOTICE); } foreach ($args as $i => $value) { if (!isset($params[$i])) { return true; } if ($parameters[$i]->name !== $params[$i][2]) { $param_num = $i + 1; $message = 'phpDoc @param %d in %s%s%s() must be named as $%s, $%s given, ' . PHP_EOL . 'called in %s on line %d ' . PHP_EOL . 'and defined in %s on line %d'; $message = sprintf($message, $param_num, $class, $type, $function, $parameters[$i]->name, $params[$i][2], $file, $line, $r->getFileName(), $r->getStartLine()); trigger_error($message, E_USER_NOTICE); } $hints = preg_split('~[|/,]~sSX', $params[$i][1]); if (!self::checkValueTypes($hints, $value)) { $param_num = $i + 1; $message = 'Argument %d passed to %s%s%s() must be an %s, %s given, ' . PHP_EOL . 'called in %s on line %d ' . PHP_EOL . 'and defined in %s on line %d'; $message = sprintf($message, $param_num, $class, $type, $function, implode('|', $hints), (is_object($value) ? get_class($value) . ' ' : '') . gettype($value), $file, $line, $r->getFileName(), $r->getStartLine()); trigger_error($message, E_USER_WARNING); return false; } } return true; }
protected function getOriginalBody(\ReflectionMethod $originalMethod) { $lines = array_slice(file($originalMethod->getDeclaringClass()->getFileName(), FILE_IGNORE_NEW_LINES), $originalMethod->getStartLine(), $originalMethod->getEndLine() - $originalMethod->getStartLine(), true); $firstLine = array_shift($lines); if (trim($firstLine) !== '{') { array_unshift($lines, $firstLine); } $lastLine = array_pop($lines); if (trim($lastLine) !== '}') { array_push($lines, $lastLine); } $body = rtrim(ltrim(implode("\n", $lines), '{'), '}'); return $body; }
/** * Gets Observers for specified Event. * * @return $this|array */ public function AjaxobserversAction() { $eventName = $this->getRequest()->getPost('event', false); // If no event name provided, if (!$eventName) { return array(); } // Ensure Event Name is all lowercase $eventName = strtolower($eventName); // Set up $areas array and $observers array $areas = array('global', 'adminhtml', 'frontend'); $observers = array(); // Cycle Through Areas and get config information foreach ($areas as $area) { $eventConfig = Mage::app()->getConfig()->getEventConfig($area, $eventName); if (!$eventConfig) { $this->_events[$area][$eventName] = false; continue; } try { foreach ($eventConfig->observers->children() as $obsName => $obsConfig) { $methodReflection = new ReflectionMethod($obsConfig->getClassName(), $obsConfig->method); $observers[$obsName] = array('area' => $area, 'type' => (string) $obsConfig->type, 'model' => $obsConfig->class ? (string) $obsConfig->class : $obsConfig->getClassName(), 'class' => $obsConfig->getClassName(), 'method' => (string) $obsConfig->method, 'line' => $methodReflection->getStartLine(), 'path' => $this->getClassPath($obsConfig->getClassName())); } } catch (Exception $e) { echo $e->getMessage(); } } // Create Block to Display Results $block = Mage::app()->getLayout()->createBlock('bronto_verify/adminhtml_system_config_advanced_observersearch'); $block->setObservers($observers); // Set Response Body $this->getResponse()->setBody($block->toHtml()); return $this; }
/** * Test various types of controller callables. * * @dataProvider provider */ public function testControllerInspection(Request $request, Response $response) { // make sure we always match the line number $r1 = new \ReflectionMethod($this, 'testControllerInspection'); $r2 = new \ReflectionMethod($this, 'staticControllerMethod'); // test name, callable, expected $controllerTests = array(array('"Regular" callable', array($this, 'testControllerInspection'), array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'testControllerInspection', 'file' => __FILE__, 'line' => $r1->getStartLine())), array('Closure', function () { return 'foo'; }, array('class' => __NAMESPACE__ . '\\{closure}', 'method' => null, 'file' => __FILE__, 'line' => __LINE__ - 5)), array('Static callback as string', 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest::staticControllerMethod', 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest::staticControllerMethod'), array('Static callable with instance', array($this, 'staticControllerMethod'), array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'staticControllerMethod', 'file' => __FILE__, 'line' => $r2->getStartLine())), array('Static callable with class name', array('Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'staticControllerMethod'), array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'staticControllerMethod', 'file' => __FILE__, 'line' => $r2->getStartLine())), array('Callable with instance depending on __call()', array($this, 'magicMethod'), array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'magicMethod', 'file' => 'n/a', 'line' => 'n/a')), array('Callable with class name depending on __callStatic()', array('Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'magicMethod'), array('class' => 'Symfony\\Component\\HttpKernel\\Tests\\DataCollector\\RequestDataCollectorTest', 'method' => 'magicMethod', 'file' => 'n/a', 'line' => 'n/a'))); $c = new RequestDataCollector(); foreach ($controllerTests as $controllerTest) { $this->injectController($c, $controllerTest[1], $request); $c->collect($request, $response); $this->assertEquals($controllerTest[2], $c->getController(), sprintf('Testing: %s', $controllerTest[0])); } }
public function getMethod($filePath, $ext = '') { $fileName = dirname($filePath); $className = basename(dirname(dirname($filePath))); if (!class_exists($className)) { helper::import($fileName); } $methodName = basename($filePath); $method = new ReflectionMethod($className . $ext, $methodName); $data = new stdClass(); $data->startLine = $method->getStartLine(); $data->endLine = $method->getEndLine(); $data->comment = $method->getDocComment(); $data->parameters = $method->getParameters(); $data->className = $className; $data->methodName = $methodName; $data->fileName = $fileName; $data->post = false; $file = file($fileName); for ($i = $data->startLine - 1; $i <= $data->endLine; $i++) { if (strpos($file[$i], '$this->post') or strpos($file[$i], 'fixer::input') or strpos($file[$i], '$_POST')) { $data->post = true; } } return $data; }
/** * Process the exception. Calls the Exception::getTrace() method to * get the backtrace. Gets the relevant lines of code for each step * in the backtrace. */ public function getTrace($e) { $trace = $e->getTrace(); foreach ($trace as $i => &$entry) { if (isset($entry['class'])) { try { $refl = new ReflectionMethod($entry['class'], $entry['function']); if (isset($trace[$i - 1]) && isset($trace[$i - 1]['line'])) { $entry['caller'] = (int) $trace[$i - 1]['line'] - 1; } else { if ($i === 0) { $entry['caller'] = (int) $e->getLine() - 1; } } $start = $entry['caller'] - self::BACKTRACE_CONTEXT; if ($start < $refl->getStartLine()) { $start = $refl->getStartLine() - 1; } $end = $entry['caller'] + self::BACKTRACE_CONTEXT; if ($end > $refl->getEndLine()) { $end = $refl->getEndLine(); } $entry['source'] = $this->getSourceFromFile($refl->getFileName(), $start, $end); } catch (Exception $e) { $entry['caller'] = null; $entry['source'] = ''; } } if (isset($entry['args'])) { // Duplicate so we don't overwrite by-reference variables $args = array(); foreach ($entry['args'] as $i => $arg) { $args[$i] = gettype($arg); } $entry['args'] = $args; } } $exceptionParams = array(); if (method_exists($e, 'getParams')) { $exceptionParams = $e->getParams(); } $d = array('backtrace' => $trace, 'message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'name' => api_helpers_class::getBaseName($e), 'params' => $exceptionParams); if (!empty($e->userInfo)) { $d['userInfo'] = $e->userInfo; } return $d; }
/** * Returns the line this method's declaration starts at * * @return integer Line this methods's declaration starts at */ public function getStartLine() { if ($this->reflectionSource instanceof ReflectionMethod) { return $this->reflectionSource->getStartLine(); } else { return parent::getStartLine(); } }
public static function getMethodBodyAndDocComment($cls, $mtd) { $func = new \ReflectionMethod($cls, $mtd); $start_line = $func->getStartLine() + 1; $length = $func->getEndLine() - $start_line - 1; $lines = array_slice(file($func->getFileName()), $start_line, $length); return array(implode('', $lines), $func->getDocComment()); }
public function getRawBody() { $method = new \ReflectionMethod($this->testClassInstance, $this->testMethod); $start_line = $method->getStartLine() - 1; // it's actually - 1, otherwise you wont get the function() block $end_line = $method->getEndLine(); $source = file($method->getFileName()); return implode("", array_slice($source, $start_line, $end_line - $start_line)); }
/** * {@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)) { $value = $value->getPattern(); } $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(); } } $this->data = array('format' => $request->getRequestFormat(), 'content' => $content, 'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html', 'status_code' => $response->getStatusCode(), '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->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) { $this->data['controller'] = 'Closure'; } else { $this->data['controller'] = (string) $controller ?: 'n/a'; } unset($this->controllers[$request]); } }
/** * Get the source code for the method * * @param \ReflectionMethod $method * * @return string */ protected function _getCode(\ReflectionMethod $method) { $filename = $method->getFileName(); $start_line = $method->getStartLine() + 1; $end_line = $method->getEndLine() - 1; $length = $end_line - $start_line; $source = file($filename); return preg_replace('/^\\s{4}/m', '', implode("", array_slice($source, $start_line, $length))); }
/** * Get start line (position) of method * * @param bool $includeDocComment * @return int */ public function getStartLine($includeDocComment = false) { if ($includeDocComment) { if ($this->getDocComment() != '') { return $this->getDocblock()->getStartLine(); } } return parent::getStartLine(); }
static function getMethodSource(ReflectionMethod $method) { $path = $method->getFileName(); $lines = @file($path); $from = $method->getStartLine(); $to = $method->getEndLine(); $len = $to - $from + 1; return implode(array_slice($lines, $from - 1, $len)); }
/** * @param \ReflectionMethod $reflectionMethod * * @return string */ private function getCodeBody(\ReflectionMethod $reflectionMethod) { $endLine = $reflectionMethod->getEndLine(); $startLine = $reflectionMethod->getStartLine(); $reflectionClass = $this->getMethodOwner($reflectionMethod, $startLine, $endLine); $length = $endLine - $startLine; $lines = file(StreamWrapper::wrapPath($reflectionClass->getFileName())); $code = join(PHP_EOL, array_slice($lines, $startLine - 1, $length + 1)); return preg_replace('/.*function[^{]+{/s', '', $code); }
public function test_populate_callback_static_method_string() { $function = 'QM_Test_Object::hello'; $callback = self::get_callback($function); $ref = new ReflectionMethod('QM_Test_Object', 'hello'); $actual = QM_Util::populate_callback($callback); $this->assertEquals(array('QM_Test_Object', 'hello'), $actual['function']); $this->assertEquals('QM_Test_Object::hello()', $actual['name']); $this->assertEquals($ref->getFileName(), $actual['file']); $this->assertEquals($ref->getStartLine(), $actual['line']); }
function sourceMethod(\ReflectionMethod $method) { $filename = $method->getFileName(); $start_line = $method->getStartLine() - 1; // it's actually - 1, otherwise you wont get the function() block $end_line = $method->getEndLine(); $length = $end_line - $start_line; $source = file($filename); $body = implode("", array_slice($source, $start_line, $length)); return $method->getDocComment() . PHP_EOL . $body; }
/** * Test the complete Drupal migration. */ public function testDrupal() { $dumps = $this->getDumps(); $this->loadDumps($dumps); $classes = $this->getTestClassesList(); $extension_install_storage = new ExtensionInstallStorage(\Drupal::service('config.storage'), InstallStorage::CONFIG_OPTIONAL_DIRECTORY, StorageInterface::DEFAULT_COLLECTION, TRUE); foreach ($classes as $class) { if (is_subclass_of($class, '\\Drupal\\migrate\\Tests\\MigrateDumpAlterInterface')) { $class::migrateDumpAlter($this); } } // Run every migration in the order specified by the storage controller. foreach (entity_load_multiple('migration', static::$migrations) as $migration) { (new MigrateExecutable($migration, $this))->import(); // Ensure that the default migration has the correct dependencies. list($base_name, ) = explode(':', $migration->id(), 2); $default_configuration = $extension_install_storage->read('migrate.migration.' . $base_name); $default_dependencies = isset($default_configuration['dependencies']) ? $default_configuration['dependencies'] : []; $this->assertEqual($default_dependencies, $migration->getDependencies(), SafeMarkup::format('Dependencies in @id match after installing. Default configuration @first is equal to active configuration @second.', array('@id' => $migration->id(), '@first' => var_export($default_dependencies, TRUE), '@second' => var_export($migration->getDependencies(), TRUE)))); } foreach ($classes as $class) { $test_object = new $class($this->testId); $test_object->databasePrefix = $this->databasePrefix; $test_object->container = $this->container; // run() does a lot of setup and tear down work which we don't need: // it would setup a new database connection and wouldn't find the // Drupal dump. Also by skipping the setUp() methods there are no id // mappings or entities prepared. The tests run against solely migrated // data. foreach (get_class_methods($test_object) as $method) { if (strtolower(substr($method, 0, 4)) == 'test') { // Insert a fail record. This will be deleted on completion to ensure // that testing completed. $method_info = new \ReflectionMethod($class, $method); $caller = array('file' => $method_info->getFileName(), 'line' => $method_info->getStartLine(), 'function' => $class . '->' . $method . '()'); $completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller); // Run the test method. try { $test_object->{$method}(); } catch (\Exception $e) { $this->exceptionHandler($e); } // Remove the completion check record. TestBase::deleteAssert($completion_check_id); } } // Add the pass/fail/exception/debug results. foreach ($this->results as $key => &$value) { $value += $test_object->results[$key]; } } }
function reflectMethod($class, $method) { $methodInfo = new ReflectionMethod($class, $method); echo "**********************************\n"; echo "Reflecting on method {$class}::{$method}()\n\n"; echo "\ngetFileName():\n"; var_dump($methodInfo->getFileName()); echo "\ngetStartLine():\n"; var_dump($methodInfo->getStartLine()); echo "\ngetEndLine():\n"; var_dump($methodInfo->getEndLine()); echo "\n**********************************\n"; }
/** * Called by the DebugBar when data needs to be collected * @return array Collected data */ function collect() { $dispatcher = $this->di['dispatcher']; $router = $this->di['router']; $route = $router->getMatchedRoute(); if (!$route) { return array(); } $uri = $route->getPattern(); $paths = $route->getPaths(); $result['uri'] = $uri ?: '-'; $result['paths'] = $this->formatVar($paths); if ($params = $router->getParams()) { $result['params'] = $this->formatVar($params); } $result['HttpMethods'] = $route->getHttpMethods(); $result['RouteName'] = $route->getName(); $result['hostname'] = $route->getHostname(); if ($this->di->has('app') && ($app = $this->di['app']) instanceof Micro) { if (($handler = $app->getActiveHandler()) instanceof \Closure || is_string($handler)) { $reflector = new \ReflectionFunction($handler); } elseif (is_array($handler)) { $reflector = new \ReflectionMethod($handler[0], $handler[1]); } } else { $result['Moudle'] = $router->getModuleName(); $result['Controller'] = get_class($controller_instance = $dispatcher->getActiveController()); $result['Action'] = $dispatcher->getActiveMethod(); $reflector = new \ReflectionMethod($controller_instance, $result['Action']); } if (isset($reflector)) { $start = $reflector->getStartLine() - 1; $stop = $reflector->getEndLine(); $filename = substr($reflector->getFileName(), mb_strlen(realpath(dirname($_SERVER['DOCUMENT_ROOT'])))); $code = array_slice(file($reflector->getFileName()), $start, $stop - $start); $result['file'] = $filename . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine() . " [CODE]: \n" . implode("", $code); } return array_filter($result); }
/** * @param ReflectionMethod $method * @return string */ function generateMethodArguments(ReflectionMethod $method) { if ($method->isInternal()) { // This code can`t handle constants, it replaces its with value return implode(', ', array_map(array($this, 'generateMethodArgument'), $method->getParameters())); } else { $lines = $this->getFileLines($method->getFileName()); $start_line = $method->getStartLine() - 1; $function_lines = array_slice($lines, $start_line, $method->getEndLine() - $start_line); // todo: use code beautifier? return $this->parseFunctionArgs(implode(PHP_EOL, $function_lines)); } }
/** * @param $class * @param $method * * @return array * * @throws \ReflectionException */ public function getMethodData($class, $method) { $class = is_object($class) ? get_class($class) : $class; $data = []; try { $reflectedMethod = new \ReflectionMethod($class, $method); $data = ['class' => $class, 'method' => $method, 'file' => $reflectedMethod->getFilename(), 'line' => $reflectedMethod->getStartLine()]; } catch (\ReflectionException $re) { // TODO: handle the exception. } finally { return $data; } }
public static final function getService() { $class = get_called_class(); if (($rc = new ReflectionClass($class)) && $rc->isAbstract()) { throw new Exception('Class "' . $class . '", extending "Clap_ServiceInstance", cannot be called as a "Service" if it is "Abstract"'); } if (!method_exists($class, '__construct')) { throw new Exception('Class "' . $class . '" extending "Clap_ServiceInstance", require "' . $class . '" to implement the method "protected function __construct()"'); } if (($rm = new ReflectionMethod($class, '__construct')) && !$rm->isProtected()) { throw new Exception('Access type for method "' . $class . '::__construct()" must be declared as "protected" to be compatible with "Clap_ServiceInstance", in "' . $rm->getFileName() . '" on line "' . $rm->getStartLine() . '"'); } return new self($class); }
protected function _getMethodSource($fileSource) { $className = $this->_findDefinedClasses(); //find method name to copy $matches = []; preg_match_all('/function(.*?)\\(/', $this->file->current(), $matches); $fnName = trim($matches[1][0]); $rc = new \ReflectionMethod($className, $fnName); //zero-indexed start line of function $startLine = $rc->getStartLine() - 1; $endLine = $rc->getEndLine(); $length = $endLine - $startLine; return implode("", array_slice($fileSource, $startLine, $length)); }
public static function add($className, $methodName, $executionTime, $annotations) { if (empty(self::$methods[$methodName])) { // normalize time $executionTime = round($executionTime, self::TEST_EXECUTION_TIME_RESOLUTION); $classReflector = new ReflectionClass($className); $methodReflector = new ReflectionMethod($className, $methodName); $lineNumber = $methodReflector->getStartLine(); $docComment = $methodReflector->getDocComment(); $filePath = $classReflector->getFileName(); $alreadyMarkedAsSlow = self::isMarkedAsSlow($annotations); self::$methods[$methodName] = ['filePath' => $filePath, 'lineNumber' => $lineNumber, 'docComment' => $docComment, 'alreadyMarkedAsSlow' => $alreadyMarkedAsSlow, 'executionTime' => $executionTime]; } }
static function getMethodSource(ReflectionMethod $method) { // принимаем объект класса ReflectionMethod $path = $method->getFileName(); // получаем путь к файлу $lines = @file($path); // получаем массив с кодом $from = $method->getStartLine(); // получаем строку где начинается нужный код $to = $method->getEndLine(); //получаем строку где заканчивается нужный код $len = $to - $from + 1; // получаем длинну return implode(array_slice($lines, $from - 1, $len)); // обрезаем массив, и переводим в строку }