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; }
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; }
/** * @param \ReflectionMethod $reflectionMethod * @param int $methodStartLine * @param int $methodEndLine * * @return \ReflectionClass */ private function getMethodOwner(\ReflectionMethod $reflectionMethod, $methodStartLine, $methodEndLine) { $reflectionClass = $reflectionMethod->getDeclaringClass(); $fileName = $reflectionMethod->getFileName(); $trait = $this->getDeclaringTrait($reflectionClass->getTraits(), $fileName, $methodStartLine, $methodEndLine); return $trait === null ? $reflectionClass : $trait; }
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)); }
/** * Returns the filename of the file this function was declared in * * @return string Filename of the file this function was declared in */ public function getFileName() { if ($this->reflectionSource instanceof ReflectionMethod) { return $this->reflectionSource->getFileName(); } else { return parent::getFileName(); } }
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()); }
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)); }
/** * 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))); }
/** * @param ReflectionMethod[] $methods */ private function checkMethodsInNewClasses($methods) { foreach ($methods as $method) { list($expectedMethod, $class) = $this->explodeCamel($method->getName()); $this->assertTrue(method_exists($class, $expectedMethod), 'Method ' . $expectedMethod . ' is not found in class ' . $class); $newMethod = new ReflectionMethod($class, $expectedMethod); $this->assertEquals($method->getModifiers(), $newMethod->getModifiers(), 'Incorrect modifier for ' . $class . '::' . $expectedMethod); $this->assertEquals(substr_count(file_get_contents($method->getFileName()), $method->getName()), substr_count(file_get_contents($newMethod->getFileName()), $newMethod->getName()), 'Incorrect usage for ' . $class . '::' . $expectedMethod); } }
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; }
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); }
/** * @param \ReflectionMethod $reflectionMethod * @param int $methodStartLine * @param int $methodEndLine * * @return \ReflectionClass */ private function getMethodOwner(\ReflectionMethod $reflectionMethod, $methodStartLine, $methodEndLine) { $reflectionClass = $reflectionMethod->getDeclaringClass(); // PHP <=5.3 does not handle traits if (version_compare(PHP_VERSION, '5.4.0', '<')) { return $reflectionClass; } $fileName = $reflectionMethod->getFileName(); $trait = $this->getDeclaringTrait($reflectionClass->getTraits(), $fileName, $methodStartLine, $methodEndLine); return $trait === null ? $reflectionClass : $trait; }
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']); }
/** * 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]; } } }
/** * 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); }
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"; }
/** * @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)); } }
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); }
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)); // обрезаем массив, и переводим в строку }
private function getMethodComments(ReflectionMethod $reflectionMethod) { $contentPhpFile = file_get_contents($reflectionMethod->getFileName()); $contentPhpFile = explode(chr(10), $contentPhpFile); $commentsArray = array(); for ($i = $reflectionMethod->getStartLine() - 2; $i > 0; $i--) { $contentPhpFile[$i] = trim($contentPhpFile[$i]); $commentsArray[] = $contentPhpFile[$i]; if ($contentPhpFile[$i] == '/**') { break; } } $commentsArray = array_reverse($commentsArray); $commentsString = implode(chr(10), $commentsArray); return $commentsString; }
/** * 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; }
/** * Displays the source code of the given action name. * * @param string $actionName Name of the controller's action method. */ public function doDebugViewAction($actionName) { if (RPG::config('debug') === true and strpos($actionName, 'do') === 0) { $method = new ReflectionMethod($this, $actionName); $out = '<h2>' . $method->getDeclaringClass()->getName() . "::{$actionName}()</h2>\n" . '<a href="' . RPG::url('*/debug-list-actions') . '">« Action List</a><br /><br />'; $start = $method->getStartLine() - 1; $end = $method->getEndLine(); $file = file($method->getFileName()); $lines = array_slice($file, $start, $end - $start); $out .= "<pre>\n " . str_replace("\t", ' ', $method->getDocComment()) . "\n"; foreach ($lines as $line) { $out .= htmlentities(str_replace("\t", ' ', $line)); } $out .= '</pre>'; RPG::view()->setLayout('layouts/empty.php')->setContent($out); } }
/** * Test the complete Drupal migration. */ public function testDrupal() { $dumps = $this->getDumps(); $this->loadDumps($dumps); $classes = $this->getTestClassesList(); 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(); } 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]; } } }
/** * @param $methodName * * @return array|string */ protected function getMethodCode($methodName) { $method = is_a($methodName, '\\ReflectionMethod') ? $methodName : new \ReflectionMethod($this->targetClass, $methodName); $declaringClass = $method->getDeclaringClass(); $notTargetClass = $declaringClass->name != $this->targetClass; if ($notTargetClass) { $method = new \ReflectionMethod($declaringClass->name, $methodName); $contents = file_get_contents($method->getFileName()); } else { $contents = $this->contents; } $startLine = $method->getStartLine(); $endLine = $method->getEndLine(); $classAliases = []; $lines = explode(PHP_EOL, $contents); foreach ($lines as $line) { $frags = explode(' ', $line); if (!empty($frags) && $frags[0] == 'use') { $fullClassName = $frags[1]; // use Acme\Class as Alias if (count($frags) > 2) { $alias = $frags[3]; } else { if (strpos($frags[1], '\\')) { $classNameFrags = explode('\\', $frags[1]); $alias = array_pop($classNameFrags); } else { $alias = $frags[1]; } } $alias = trim($alias, ';'); $classAliases[$alias] = trim($fullClassName, ';'); } } $lines = array_map(function ($line) use($classAliases) { foreach ($classAliases as $classAlias => $fullClassName) { $line = str_replace($classAlias, $fullClassName, $line); } return trim($line); }, $lines); $code = array_splice($lines, $startLine - 1, $endLine - $startLine + 1); $code[0] = preg_replace('/\\s*abstract\\s*/', '', $code[0]); $code = implode(" ", $code); return $code; }
public static final function getService(&$instances, $class) { $class = get_called_class(); // Class struct check : if (($rc = new ReflectionClass($class)) && $rc->isAbstract()) { throw new Exception('Class "' . $class . '", extending "Clap_ServiceSingleton", cannot be called as a "Service" if it is "Abstract"'); } if (!method_exists($class, '__construct')) { throw new Exception('Class "' . $class . '" extending "Clap_ServiceSingleton", require "' . $class . '" to implement 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_ServiceSingleton", in "' . $rm->getFileName() . '" on line "' . $rm->getStartLine() . '"'); } // Class instance creation : $rc = new ReflectionClass($class); $object = $rc->newInstanceWithoutConstructor(); $instances[$class] = $object; call_user_func(array($object, '__construct')); return $object; }
private static function getMethodCode($class, $method) { $method = new ReflectionMethod($class, $method); $methodname = $method->name; $classname = $method->class; if (!($filename = self::getTrackedMethodFilename($classname, $methodname))) { $filename = $method->getFileName(); self::trackModifiedMethod($classname, $methodname, $filename); } $source = file_get_contents($filename); //This regex will find the method body $regex = '/function ' . $methodname . '*?[\\s\\S]*?\\{([\\s\\S]*?)\\}/'; $body = array(); preg_match($regex, $source, $body); if (empty($body)) { $body = ''; } else { $body = $body[1]; } return $body; }
function document_method($class, $methods) { $rclass = new ReflectionClass($class); $definition = implode("", array_slice(file($rclass->getFileName()), $rclass->getStartLine() - 1, 1)); $code = "\n" . $definition . "\n....\n\n"; if (!is_array($methods)) { $methods = array($methods); } foreach ($methods as $method) { $method = new ReflectionMethod($class, $method); $filename = $method->getFileName(); $start_line = $method->getStartLine() - 1; $end_line = $method->getEndLine(); $length = $end_line - $start_line; $source = file($filename); $content = implode("", array_slice($source, $start_line, $length)); $code .= $content . "\n\n"; } $code = highlight_string("<?php " . $code, true); $code = str_replace('<?php ', '', $code); return "<pre>\n" . $code . "\n</pre>"; }
public function get_component() { $components = array(); foreach ($this->trace as $item) { try { if (isset($item['class'])) { if (!is_object($item['class']) and !class_exists($item['class'], false)) { continue; } if (!method_exists($item['class'], $item['function'])) { continue; } $ref = new ReflectionMethod($item['class'], $item['function']); $file = $ref->getFileName(); } else { if (function_exists($item['function'])) { $ref = new ReflectionFunction($item['function']); $file = $ref->getFileName(); } else { if (isset($item['file'])) { $file = $item['file']; } else { continue; } } } $comp = QM_Util::get_file_component($file); $components[$comp->type] = $comp; } catch (ReflectionException $e) { # nothing } } foreach (QM_Util::get_file_dirs() as $type => $dir) { if (isset($components[$type])) { return $components[$type]; } } # This should not happen }
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 $r = new ReflectionMethod($class, $function); $doc = $r->getDocComment(); if (!preg_match_all('~[\\r\\n]++ [\\x20\\t]++ \\* [\\x20\\t]++ @param [\\x20\\t]++ ( [_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)) { return true; } foreach ($args as $i => $value) { if (!isset($params[$i])) { return true; } #$name = $params[$i][2]; $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; }
public static function setDocument($document, $class, $func = NULL) { if ($func == NULL) { $reflect = new \ReflectionClass($class); } else { $reflect = new \ReflectionMethod($class, $func); } $filePath = $reflect->getFileName(); $startLine = $reflect->getStartLine(); $doc = $reflect->getDocComment(); //获取注释内容 $array = file($filePath); preg_match("/(\\s*)[\\w]/", $array[$startLine - 1], $spaceMatch); $space = $spaceMatch[1]; $flag = preg_match('/.*@name(.*)/', $doc, $match); //查看是否有注释 if ($flag) { /*有注释就替换*/ $docLine = explode("\n", $doc); //查看注释有几行内容 $docStartLine = $startLine - count($docLine); //注释起始 行数 for ($i = $docStartLine - 1; $i < $startLine - 1; $i++) { $theDoc = $array[$i]; if (preg_match('/@name/', $theDoc, $theMatch)) { $array[$i] = preg_replace('/@name.*/', '@name ' . $document, $array[$i]); break; } } } else { //插入注释 array_splice($array, $startLine - 1, 0, "{$space}/**\n {$space}* @name " . $document . "\n {$space}*/\n"); } $handle = fopen($filePath, 'w+'); fwrite($handle, implode("", $array)); }