/** * Gets the line where the class definition ends * @return Integer */ public function getEndLine() { $e = $this->reflection->getEndLine(); if (!$e || !$this->getFileName()) { return NULL; } return $e; }
/** * Возвращает тело класса/интерфейса */ public function getClassBody() { $lines = $this->di->getFileLines(true, true); $firstLine = $this->rc->getStartLine(); $endLine = $this->rc->getEndLine(); if ($endLine <= $firstLine + 1) { return ''; } return trim(implode('', array_slice($lines, $firstLine, $endLine - $firstLine - 1))); }
public function reflect() { $this->load->library('calendar'); $reflect = new ReflectionClass('CI_Calendar'); echo $reflect->getStartLine(); $path = $reflect->getFileName(); $temp = @file($path); echo $reflect->getEndLine(); $len = $reflect->getEndLine() - $reflect->getStartLine() + 1; echo implode(array_slice($temp, $reflect->getStartLine() - 1, $len)); // foreach ($func->getParameters() as $param) // { // echo $param,'<br>'; // } }
public function buildAllFile() : array { $path = $this->getPath(); if (!is_file($path)) { throw new \Exception("The file {$path} not found!"); } if (!is_readable($path)) { throw new \Exception("The file {$path} not readable!"); } if (!is_writeable($path)) { throw new \Exception("The file {$path} not writable!"); } $endLine = $this->reflection->getEndLine(); $insertLine = $endLine - 1; $handle = @fopen($path, 'r'); $index = 0; $result = []; while (($buffer = fgets($handle, 4096)) !== false) { $index++; $result[] = $buffer; if ($index === $insertLine) { $result[] = $this->buildMethodBody($this->method); } } return $result; }
public function generate($withTargets = true) { $shortClassName = $this->reflectionClass->getShortName(); EntityCodeGenerator::process($this->twigEngine, $this->reflectionClass->getFileName(), $this->getMethodsStartLine($this->reflectionClass, $this->reflectionClass->getFileName()), $this->reflectionClass->getEndLine(), $this->reflectionClass->getNamespaceName(), $this->namespace, $this->getExistMethods($this->reflectionClass), $this->getExistProperties($this->reflectionClass), $this->properties); if (!$withTargets) { return; } foreach ($this->usedTargets as $targetName) { $target = $this->targets[$targetName]; /* @var $target Target */ $namespace = $target->getNamespace() . ($this->localNamespace ? '\\' . $this->localNamespace : ''); $filename = $this->srcDir . '/' . str_replace('\\', '/', $namespace) . '/' . $shortClassName . '.php'; $className = $namespace . '\\' . $shortClassName; if (is_readable($filename)) { if (!class_exists($className)) { throw $this->getClassException('Filename "' . $filename . '" exists but class "$s" not. Fix it or remove class file before generation.'); } $isNew = false; } else { if (class_exists($className)) { throw $this->getClassException('Filename "' . $filename . '" not exists but class "$s" is. Fix it before generating.'); } $isNew = true; } $properties = $this->getPropertiesForTarget($target->getName()); if ($isNew) { EntityCodeGenerator::processNew($this->twigEngine, $filename, $namespace, $target->getNamespace(), $shortClassName, $properties, $target->isWithAnnotations(), $target->isUseClassNotations(), $target->isWithInitFunction()); } else { $reflectionClass = new \ReflectionClass($className); EntityCodeGenerator::process($this->twigEngine, $reflectionClass->getFileName(), $this->getMethodsStartLine($reflectionClass, $reflectionClass->getFileName()), $reflectionClass->getEndLine(), $reflectionClass->getNamespaceName(), $target->getNamespace(), $this->getExistMethods($reflectionClass), $this->getExistProperties($reflectionClass), $properties, $target->isWithAnnotations(), $target->isUseClassNotations()); } } }
static function getClassSource(ReflectionClass $class) { $path = $class->getFileName(); $lines = @file($path); $from = $class->getStartLine(); $to = $class->getEndLine(); $len = $to - $from + 1; return implode(array_slice($lines, $from - 1, $len)); }
public function appendContent($class, $content) { $reflection = new ReflectionClass($class); $lastLine = $reflection->getEndLine() - 1; $file = file($reflection->getFileName()); $beginning = array_slice($file, 0, $lastLine); $end = array_slice($file, $lastLine); unset($file); return (bool) file_put_contents($reflection->getFileName(), implode('', $beginning) . PHP_EOL . $content . PHP_EOL . implode('', $end)); }
/** * @param ReflectionClass $reflection */ protected function _createFromReflection($reflection) { $this->_className = $reflection->getName(); $this->_endLine = $reflection->getEndLine(); $this->_filePath = $reflection->getFileName(); foreach ($reflection->getMethods() as $method) { //Method::create($this, $method); $this->addMethod(Method::create($this, $method)); } }
public function getCodeInClass($className) { $class = new \ReflectionClass($className); $startLine = $class->getStartLine() - 1; // getStartLine() seems to start after the {, we want to include the signature $endLine = $class->getEndLine(); $numLines = $endLine - $startLine; $namespace = $this->getNamespaceOfClass($className); $classCode = "namespace {$namespace};\n\n" . implode("\n", array_slice(explode("\n", $this->fileContent), $startLine, $numLines)) . "\n"; return $classCode; }
static function getClassSource(ReflectionClass $class) { // принимаем объект класса ReflectionClass $path = $class->getFileName(); // получаем путь к файлу $lines = @file($path); // получаем массив с кодом $from = $class->getStartLine(); // получаем строку где начинается нужный код $to = $class->getEndLine(); //получаем строку где заканчивается нужный код $len = $to - $from + 1; // получаем длинну return implode(array_slice($lines, $from - 1, $len)); // обрезаем массив, и переводим в строку }
/** * method for making a single file of most used doctrine runtime components * including the compiled file instead of multiple files (in worst * cases dozens of files) can improve performance by an order of magnitude * * @throws Doctrine_Compiler_Exception if something went wrong during the compile operation * @return void */ public static function compile($target = null) { $path = Doctrine::getPath(); $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($it as $file) { $e = explode('.', $file->getFileName()); // we don't want to require versioning files if (end($e) === 'php' && strpos($file->getFileName(), '.inc') === false) { require_once $file->getPathName(); } } $classes = array_merge(get_declared_classes(), get_declared_interfaces()); $ret = array(); foreach ($classes as $class) { $e = explode('_', $class); if ($e[0] !== 'Doctrine') { continue; } $refl = new ReflectionClass($class); $file = $refl->getFileName(); print 'Adding ' . $file . PHP_EOL; $lines = file($file); $start = $refl->getStartLine() - 1; $end = $refl->getEndLine(); $ret = array_merge($ret, array_slice($lines, $start, $end - $start)); } if ($target == null) { $target = $path . DIRECTORY_SEPARATOR . 'Doctrine.compiled.php'; } // first write the 'compiled' data to a text file, so // that we can use php_strip_whitespace (which only works on files) $fp = @fopen($target, 'w'); if ($fp === false) { throw new Doctrine_Compiler_Exception("Couldn't write compiled data. Failed to open {$target}"); } fwrite($fp, "<?php " . implode('', $ret)); fclose($fp); $stripped = php_strip_whitespace($target); $fp = @fopen($target, 'w'); if ($fp === false) { throw new Doctrine_Compiler_Exception("Couldn't write compiled data. Failed to open {$file}"); } fwrite($fp, $stripped); fclose($fp); }
var_dump($rb->getConstant('C1')); print "\n"; print "--- getConstants() ---\n"; var_dump($rb->getConstants()); print "\n"; print "--- getConstructor() ---\n"; var_dump($rb->getConstructor()); print "\n"; print "--- getDocComment() ---\n"; var_dump($rb->getDocComment()); print "\n"; print "--- getStartLine() ---\n"; var_dump($rb->getStartLine()); print "\n"; print "--- getEndLine() ---\n"; var_dump($rb->getEndLine()); print "\n"; print "--- getFileName() ---\n"; var_dump($rb->getFileName()); print "\n"; print "--- getInterfaceNames() ---\n"; var_dump($rb->getInterfaceNames()); print "\n"; print "--- getInterfaces() ---\n"; # Very verbose. #var_dump( $rb->getInterfaces(); print "\n"; print "--- getMethod() ---\n"; print "\n"; print "--- getMethods() ---\n";
/** * Copies the given method and all needed use statements into an existing class. The target class name will be * built based on the given $replace argument. * @param string $sourceClassName * @param string $methodName * @param array $replace */ protected function copyTemplateMethodToExisitingClass($sourceClassName, $methodName, $replace) { $targetClassName = $this->replaceContent($replace, $sourceClassName); if (Development::methodExists($targetClassName, $methodName)) { // we do not want to add the same method twice return; } Development::checkMethodExists($sourceClassName, $methodName, 'Cannot copy template method: '); $targetClass = new \ReflectionClass($targetClassName); $file = new \SplFileObject($targetClass->getFileName()); $methodCode = Development::getMethodSourceCode($sourceClassName, $methodName); $methodCode = $this->replaceContent($replace, $methodCode); $methodLine = $targetClass->getEndLine() - 1; $sourceUses = Development::getUseStatements($sourceClassName); $targetUses = Development::getUseStatements($targetClassName); $usesToAdd = array_diff($sourceUses, $targetUses); if (empty($usesToAdd)) { $useCode = ''; } else { $useCode = "\nuse " . implode("\nuse ", $usesToAdd) . "\n"; } // search for namespace line before the class starts $useLine = 0; foreach (new \LimitIterator($file, 0, $targetClass->getStartLine()) as $index => $line) { if (0 === strpos(trim($line), 'namespace ')) { $useLine = $index + 1; break; } } $newClassCode = ''; foreach (new \LimitIterator($file) as $index => $line) { if ($index == $methodLine) { $newClassCode .= $methodCode; } if (0 !== $useLine && $index == $useLine) { $newClassCode .= $useCode; } $newClassCode .= $line; } file_put_contents($targetClass->getFileName(), $newClassCode); }
/** * Create a syntax highlighted diagram of a class, including parent dependencies, memebers and functions. * * @param object $obj The object to explore. * @return string The formatted diagram of the object. */ public static function classes($obj) { echo self::$is_themed ? '' : self::$theme; $current_class = new \ReflectionObject($obj); $class = new \ReflectionClass($current_class->getName()); $parents = array(); while ($parent = $class->getParentClass()) { $mod = "<h3><b class='rtn'>{$parstr}</b>" . implode(' ', \Reflection::getModifierNames($class->getModifiers())); $nam = "Class <b class='nam'>" . $class->getName() . "</b></h3>"; $lin = self::get_func_url($class->getStartLine(), $class->getEndLine(), $class->getFileName()); $doc = self::clean_docblok($class->getdocComment(), false, "Undocumented {$parstr}" . "Class"); $parents[] = "<div class='method'>"; $parents[] = $lin; $parents[] = Syntax::php(trim($mod . $nam), 'all'); $parents[] = "<b class='com'>{$doc}</b>"; $properties = implode($class->getProperties()); $properties = str_replace('<default>', '', $properties); $properties = str_replace('Property [ ', '', $properties); $properties = str_replace(' ]', '', $properties); $properties = explode(' ', $properties); $len = 0; foreach ($properties as $k => $v) { if ($k % 2 !== 0) { $test = strlen($v); $len = $test > $len ? $test + 1 : $len; } } foreach ($properties as $k => $v) { $properties[$k] = ltrim(sprintf("%-{$len}s", $v)); } $properties = implode('', $properties); $properties = explode("\n", $properties); asort($properties); $properties = "<h4>Properties:</h4>" . implode("\n", $properties); $parents[] = Syntax::php($properties, 'all'); if ($parstr !== 'Parent ') { $parents[] = self::build_func_list($obj); } $parents[] = "</div>"; $parstr = "Parent "; $class = $parent; } $class_info = "Parents: " . implode(", ", $parents); $class_info = Syntax::php($class_info, 'all'); $classinfo = implode($parents); echo $classinfo; /* $class = new \ReflectionObject($obj); ReflectionObject::export($obj); $test = new \ReflectionClass($obj); print_r($test->getProperties()); echo 'getConstants() '; print_r( $class->getConstants() ) .PHP_EOL; echo 'getDefaultProperties()'; print_r( $class->getDefaultProperties() ) .PHP_EOL; echo 'getInterfaceNames() '; print_r( $class->getInterfaceNames() ) .PHP_EOL; echo 'getInterfaces() '; print_r( $class->getInterfaces() ) .PHP_EOL; echo 'getMethods() '; print_r( $class->getMethods() ) .PHP_EOL; echo 'getProperties() '; print_r( $class->getProperties() ) .PHP_EOL; echo 'getStaticProperties() '; print_r( $class->getStaticProperties() ) .PHP_EOL; echo 'getTraitAliases() '; print_r( $class->getTraitAliases() ) .PHP_EOL; echo 'getTraitNames() '; print_r( $class->getTraitNames() ) .PHP_EOL; echo 'getTraits() '; print_r( $class->getTraits() ) .PHP_EOL; echo 'hasConstant() '. AT::boolstr( $class->hasConstant($class->getName())) .PHP_EOL; echo 'inNamespace() '. AT::boolstr( $class->inNamespace() ) .PHP_EOL; echo 'isAbstract() '. AT::boolstr( $class->isAbstract() ) .PHP_EOL; echo 'isCloneable() '. AT::boolstr( $class->isCloneable() ) .PHP_EOL; echo 'isFinal() '. AT::boolstr( $class->isFinal() ) .PHP_EOL; echo 'isInstantiable() '. AT::boolstr( $class->isInstantiable() ) .PHP_EOL; echo 'isInterface() '. AT::boolstr( $class->isInterface() ) .PHP_EOL; echo 'isInternal() '. AT::boolstr( $class->isInternal() ) .PHP_EOL; echo 'isIterateable() '. AT::boolstr( $class->isIterateable() ) .PHP_EOL; echo 'isTrait() '. AT::boolstr( $class->isTrait() ) .PHP_EOL; echo 'isUserDefined() '. AT::boolstr( $class->isUserDefined() ) .PHP_EOL; echo 'getEndLine() '. $class->getEndLine() .PHP_EOL; echo 'getModifiers() '. $class->getModifiers() .PHP_EOL; echo 'getStartLine() '. $class->getStartLine() .PHP_EOL; echo 'getDocComment() '. $class->getDocComment() .PHP_EOL; echo 'getExtensionName() '. $class->getExtensionName() .PHP_EOL; echo 'getFileName() '. $class->getFileName() .PHP_EOL; echo 'getName() '. $class->getName() .PHP_EOL; echo 'getNamespaceName() '. $class->getNamespaceName() .PHP_EOL; echo 'getShortName() '. $class->getShortName() .PHP_EOL; */ }
/** * Add all methods in a module override to the override class * * @param string $classname * @return bool */ public function addOverride($classname) { $path = Autoload::getInstance()->getClassPath($classname . 'Core'); // Check if there is already an override file, if not, we just need to copy the file if (Autoload::getInstance()->getClassPath($classname)) { // Check if override file is writable $override_path = _PS_ROOT_DIR_ . '/' . Autoload::getInstance()->getClassPath($classname); if (!file_exists($override_path) && !is_writable(dirname($override_path)) || file_exists($override_path) && !is_writable($override_path)) { throw new Exception(sprintf(Tools::displayError('file (%s) not writable'), $override_path)); } // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration do { $uniq = uniqid(); } while (class_exists($classname . 'OverrideOriginal_remove', false)); // Make a reflection of the override class and the module override class $override_file = file($override_path); eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array(' ', 'class ' . $classname . 'OverrideOriginal' . $uniq), implode('', $override_file))); $override_class = new ReflectionClass($classname . 'OverrideOriginal' . $uniq); $module_file = file($this->getLocalPath() . 'override' . DIRECTORY_SEPARATOR . $path); eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class ' . $classname . 'Override' . $uniq), implode('', $module_file))); $module_class = new ReflectionClass($classname . 'Override' . $uniq); // Check if none of the methods already exists in the override class foreach ($module_class->getMethods() as $method) { if ($override_class->hasMethod($method->getName())) { throw new Exception(sprintf(Tools::displayError('The method %1$s in the class %2$s is already overriden.'), $method->getName(), $classname)); } } // Check if none of the properties already exists in the override class foreach ($module_class->getProperties() as $property) { if ($override_class->hasProperty($property->getName())) { throw new Exception(sprintf(Tools::displayError('The property %1$s in the class %2$s is already defined.'), $property->getName(), $classname)); } } // Insert the methods from module override in override $copy_from = array_slice($module_file, $module_class->getStartLine() + 1, $module_class->getEndLine() - $module_class->getStartLine() - 2); array_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from); $code = implode('', $override_file); file_put_contents($override_path, $code); } else { $override_src = $this->getLocalPath() . 'override' . DIRECTORY_SEPARATOR . $path; $override_dest = _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'override' . DIRECTORY_SEPARATOR . $path; if (!is_writable(dirname($override_dest))) { throw new Exception(sprintf(Tools::displayError('directory (%s) not writable'), dirname($override_dest))); } copy($override_src, $override_dest); // Re-generate the class index Autoload::getInstance()->generateIndex(); } return true; }
protected static function weaveMock($classNameMock_, \ReflectionClass $mock_, \ReflectionClass $type_) { $mock = @file_get_contents($mock_->getFileName()); $type = @file_get_contents($type_->getFileName()); $typeMTime = @filemtime($type_->getFileName()); $method = []; $methods = []; foreach (token_get_all($type) as $token) { if (count($method) && ('{' == $token || ';' == $token)) { $methods[] = $method; $method = []; } else { if (count($method)) { $method[] = $token; } } if (T_FUNCTION == $token[0]) { $method[] = $token; } } $signatures = []; foreach ($methods as $tokens) { $tokens = array_slice($tokens, 2); $nameToken = array_shift($tokens); $name = $nameToken[1]; $signature = ''; foreach ($tokens as $token) { if (false === is_array($token)) { $signature .= $token; continue; } if (T_WHITESPACE == $token[0]) { continue; } if (in_array($token[0], self::$m_tokensMethodSignature)) { $signature .= $token[1]; if (T_STRING == $token[0]) { $signature .= ' '; } } } $signatures[$name] = $signature; } $source = explode(Io::LINE_SEPARATOR_DEFAULT, $mock); $source = array_slice($source, 0, $mock_->getEndLine() - 1); foreach ($signatures as $methodName => $signature) { $method = $type_->getMethod($methodName); if ($method->isStatic() || $method->isFinal()) { continue; } $parameters = []; foreach ($method->getParameters() as $parameter) { $parameters[] = '$' . $parameter->name; } if ($method->isConstructor()) { $source[] = "public function {$methodName}{$signature} {parent::{$methodName}(" . implode(', ', $parameters) . ");}"; continue; } $visibility = 'public'; if ($method->isPrivate()) { $visibility = 'private'; } else { if ($method->isProtected()) { $visibility = 'protected'; } } $sourceMethod = "{$visibility} function {$methodName}{$signature} {if(\$this->mocked('{$methodName}')) return \$this->__call('{$methodName}', func_get_args());"; if (false === $type_->isInterface() && false === $method->isAbstract()) { $sourceMethod .= " return parent::{$methodName}(" . implode(', ', $parameters) . ");"; } $source[] = $sourceMethod . "}"; } $source = implode(Io::LINE_SEPARATOR_DEFAULT, $source) . Io::LINE_SEPARATOR_DEFAULT . ' }' . Io::LINE_SEPARATOR_DEFAULT . '?>'; $inheritance = $type_->isInterface() ? 'implements' : 'extends'; return str_replace('class Mock', "class {$classNameMock_} {$inheritance} \\{$type_->name}", $source); }
public static final function common_has_code($module_name, $version) { $class_name = $module_name . 'Common'; $file = 'modules/' . self::get_module_dir_path($module_name) . '/' . self::get_module_file_name($module_name) . 'Common_' . $version . '.php'; if (!class_exists($class_name, false)) { self::include_common($module_name, $version); } if (!file_exists($file)) { return false; } $start = $end = -1; if (class_exists($class_name, false)) { $rc = new ReflectionClass($class_name); $start = $rc->getStartLine() - 1; $end = $rc->getEndLine(); } $file_content = ''; $file_lines = file($file); $VA_regex = '/Direct access forbidden/i'; foreach ($file_lines as $i => $line) { if ($i >= $start && $i < $end) { continue; } if (preg_match($VA_regex, $line)) { continue; } $file_content .= $line; } $tmp_file = tmpfile(); fwrite($tmp_file, $file_content); $info = stream_get_meta_data($tmp_file); $stripped_file = php_strip_whitespace($info['uri']); fclose($tmp_file); // heuristic to get info about code. Some very short code can be ommited. if (strlen($stripped_file) > 20) { return true; } return false; }
/** * Add all methods in a module override to the override class * * @param string $classname * @return bool */ public function addOverride($classname) { $orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname . 'Core'); if (!$path) { $path = 'modules' . DIRECTORY_SEPARATOR . $classname . DIRECTORY_SEPARATOR . $classname . '.php'; } $path_override = $this->getLocalPath() . 'override' . DIRECTORY_SEPARATOR . $path; if (!file_exists($path_override)) { return false; } else { file_put_contents($path_override, preg_replace('#(\\r|\\r\\n)#ism', "\n", file_get_contents($path_override))); } $pattern_escape_com = '#(\\/\\/.*?\\n|\\/\\*(?!\\n\\s+\\* module:.*?\\* date:.*?\\* version:.*?\\*\\/).*?\\*\\/)#ism'; // Check if there is already an override file, if not, we just need to copy the file if ($file = PrestaShopAutoload::getInstance()->getClassPath($classname)) { // Check if override file is writable $override_path = _PS_ROOT_DIR_ . '/' . $file; if (!file_exists($override_path) && !is_writable(dirname($override_path)) || file_exists($override_path) && !is_writable($override_path)) { throw new Exception(sprintf(Tools::displayError('file (%s) not writable'), $override_path)); } // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration do { $uniq = uniqid(); } while (class_exists($classname . 'OverrideOriginal_remove', false)); // Make a reflection of the override class and the module override class $override_file = file($override_path); eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array(' ', 'class ' . $classname . 'OverrideOriginal' . $uniq), implode('', $override_file))); $override_class = new ReflectionClass($classname . 'OverrideOriginal' . $uniq); $module_file = file($path_override); eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class ' . $classname . 'Override' . $uniq), implode('', $module_file))); $module_class = new ReflectionClass($classname . 'Override' . $uniq); // Check if none of the methods already exists in the override class foreach ($module_class->getMethods() as $method) { if ($override_class->hasMethod($method->getName())) { $method_override = $override_class->getMethod($method->getName()); if (preg_match('/module: (.*)/ism', $override_file[$method_override->getStartLine() - 5], $name) && preg_match('/date: (.*)/ism', $override_file[$method_override->getStartLine() - 4], $date) && preg_match('/version: ([0-9.]+)/ism', $override_file[$method_override->getStartLine() - 3], $version)) { throw new Exception(sprintf(Tools::displayError('The method %1$s in the class %2$s is already overridden by the module %3$s version %4$s at %5$s.'), $method->getName(), $classname, $name[1], $version[1], $date[1])); } throw new Exception(sprintf(Tools::displayError('The method %1$s in the class %2$s is already overridden.'), $method->getName(), $classname)); } else { $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b' . $method->getName() . '\\b))/ism', "/*\n\t* module: " . $this->name . "\n\t* date: " . date('Y-m-d H:i:s') . "\n\t* version: " . $this->version . "\n\t*/\n\t\$1", $module_file); } } // Check if none of the properties already exists in the override class foreach ($module_class->getProperties() as $property) { if ($override_class->hasProperty($property->getName())) { throw new Exception(sprintf(Tools::displayError('The property %1$s in the class %2$s is already defined.'), $property->getName(), $classname)); } else { $module_file = preg_replace('/(:?public|private|protected|const)\\s+(static\\s+)?(\\$?\\b' . $property->getName() . '\\b)/ism', "/*\n\t* module: " . $this->name . "\n\t* date: " . date('Y-m-d H:i:s') . "\n\t* version: " . $this->version . "\n\t*/\n\t\$1 \$2\$3", $module_file); } } // Insert the methods from module override in override $copy_from = array_slice($module_file, $module_class->getStartLine() + 1, $module_class->getEndLine() - $module_class->getStartLine() - 2); array_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from); $code = implode('', $override_file); file_put_contents($override_path, preg_replace($pattern_escape_com, '', $code)); } else { $override_src = $path_override; $override_dest = _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'override' . DIRECTORY_SEPARATOR . $path; $dir_name = dirname($override_dest); if (!$orig_path && !is_dir($dir_name)) { $oldumask = umask(00); @mkdir($dir_name, 0777); umask($oldumask); } if (!is_writable($dir_name)) { throw new Exception(sprintf(Tools::displayError('directory (%s) not writable'), $dir_name)); } $module_file = file($override_src); if ($orig_path) { do { $uniq = uniqid(); } while (class_exists($classname . 'OverrideOriginal_remove', false)); eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class ' . $classname . 'Override' . $uniq), implode('', $module_file))); $module_class = new ReflectionClass($classname . 'Override' . $uniq); // Add foreach function a comment with the module name and the module version foreach ($module_class->getMethods() as $method) { $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b' . $method->getName() . '\\b))/ism', "/*\n\t* module: " . $this->name . "\n\t* date: " . date('Y-m-d H:i:s') . "\n\t* version: " . $this->version . "\n\t*/\n\t\$1", $module_file); } // same as precedent but for variable foreach ($module_class->getProperties() as $property) { $module_file = preg_replace('/(:?public|private|protected|const)\\s+(static\\s+)?(\\$?\\b' . $property->getName() . '\\b)/ism', "/*\n\t* module: " . $this->name . "\n\t* date: " . date('Y-m-d H:i:s') . "\n\t* version: " . $this->version . "\n\t*/\n\t\$1 \$2\$3", $module_file); } } file_put_contents($override_dest, preg_replace($pattern_escape_com, '', $module_file)); // Re-generate the class index Tools::generateIndex(); } return true; }
/** * 构造函数 * * @param mixed $class */ private function __construct($class) { if (!$class instanceof ReflectionClass) { $class = new ReflectionClass($class); } $this->name = $class->getName(); $this->filename = $class->getFilename(); $this->is_interface = $class->isInterface(); $this->is_abstract = $class->isAbstract(); $this->is_final = $class->isFinal(); $this->is_iterateable = $class->isIterateable(); $this->start_line = $class->getStartLine(); $this->end_line = $class->getEndLine(); $this->_reflection_class = $class; }
/** * method for making a single file of most used doctrine runtime components * including the compiled file instead of multiple files (in worst * cases dozens of files) can improve performance by an order of magnitude * * @throws Doctrine_Compiler_Exception if something went wrong during the compile operation * @return $target Path the compiled file was written to */ public static function compile($target = null, $includedDrivers = array()) { if (!is_array($includedDrivers)) { $includedDrivers = array($includedDrivers); } $excludedDrivers = array(); // If we have an array of specified drivers then lets determine which drivers we should exclude if (!empty($includedDrivers)) { $drivers = array('db2', 'mssql', 'mysql', 'oracle', 'pgsql', 'sqlite'); $excludedDrivers = array_diff($drivers, $includedDrivers); } $path = Doctrine_Core::getPath(); $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path . '/Doctrine'), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($it as $file) { $e = explode('.', $file->getFileName()); //@todo what is a versioning file? do we have these anymore? None //exists in my version of doctrine from svn. // we don't want to require versioning files if (end($e) === 'php' && strpos($file->getFileName(), '.inc') === false && strpos($file->getFileName(), 'sfYaml') === false) { require_once $file->getPathName(); } } $classes = array_merge(get_declared_classes(), get_declared_interfaces()); $ret = array(); foreach ($classes as $class) { $e = explode('_', $class); if ($e[0] !== 'Doctrine') { continue; } // Exclude drivers if (!empty($excludedDrivers)) { foreach ($excludedDrivers as $excludedDriver) { $excludedDriver = ucfirst($excludedDriver); if (in_array($excludedDriver, $e)) { continue 2; } } } $refl = new ReflectionClass($class); $file = $refl->getFileName(); $lines = file($file); $start = $refl->getStartLine() - 1; $end = $refl->getEndLine(); $ret = array_merge($ret, array_slice($lines, $start, $end - $start)); } if ($target == null) { $target = $path . DIRECTORY_SEPARATOR . 'Doctrine.compiled.php'; } // first write the 'compiled' data to a text file, so // that we can use php_strip_whitespace (which only works on files) $fp = @fopen($target, 'w'); if ($fp === false) { throw new Doctrine_Compiler_Exception("Couldn't write compiled data. Failed to open {$target}"); } fwrite($fp, "<?php " . implode('', $ret)); fclose($fp); $stripped = php_strip_whitespace($target); $fp = @fopen($target, 'w'); if ($fp === false) { throw new Doctrine_Compiler_Exception("Couldn't write compiled data. Failed to open {$file}"); } fwrite($fp, $stripped); fclose($fp); return $target; }
/** * Get all info about class (object) * @param string|object $data Object or class name * @return JBDump */ protected static function _getClass($data) { // check arg if (is_object($data)) { $className = get_class($data); } elseif (is_string($data)) { $className = $data; } else { return false; } if (!class_exists($className) && !interface_exists($className)) { return false; } // create ReflectionClass object $class = new ReflectionClass($data); // get basic class info $result['name'] = $class->name; $result['type'] = $class->isInterface() ? 'interface' : 'class'; if ($classComment = $class->getDocComment()) { $result['comment'] = $classComment; } if ($classPath = $class->getFileName()) { $result['path'] = $classPath . ' ' . $class->getStartLine() . '/' . $class->getEndLine(); } if ($classExtName = $class->getExtensionName()) { $result['extension'] = $classExtName; } if ($class->isAbstract()) { $result['abstract'] = true; } if ($class->isFinal()) { $result['final'] = true; } // get all parents of class $class_tmp = $class; $result['parents'] = array(); while ($parent = $class_tmp->getParentClass()) { if (isset($parent->name)) { $result['parents'][] = $parent->name; $class_tmp = $parent; } } if (count($result['parents']) == 0) { unset($result['parents']); } // reflecting class interfaces $interfaces = $class->getInterfaces(); if (is_array($interfaces)) { foreach ($interfaces as $property) { $result['interfaces'][] = $property->name; } } // reflection class constants $constants = $class->getConstants(); if (is_array($constants)) { foreach ($constants as $key => $property) { $result['constants'][$key] = $property; } } // reflecting class properties $properties = $class->getProperties(); if (is_array($properties)) { foreach ($properties as $key => $property) { if ($property->isPublic()) { $visible = "public"; } elseif ($property->isProtected()) { $visible = "protected"; } elseif ($property->isPrivate()) { $visible = "private"; } else { $visible = "public"; } $propertyName = $property->getName(); $result['properties'][$visible][$propertyName]['comment'] = $property->getDocComment(); $result['properties'][$visible][$propertyName]['static'] = $property->isStatic(); $result['properties'][$visible][$propertyName]['default'] = $property->isDefault(); $result['properties'][$visible][$propertyName]['class'] = $property->class; } } // get source $source = null; if (isset($result['path']) && $result['path']) { $source = @file($class->getFileName()); if (!empty($source)) { $result['source::source'] = implode('', $source); } } // reflecting class methods foreach ($class->getMethods() as $key => $method) { if ($method->isPublic()) { $visible = "public"; } elseif ($method->isProtected()) { $visible = "protected"; } elseif ($method->isPrivate()) { $visible = "protected"; } else { $visible = "public"; } $result['methods'][$visible][$method->name]['name'] = $method->getName(); if ($method->isAbstract()) { $result['methods'][$visible][$method->name]['abstract'] = true; } if ($method->isFinal()) { $result['methods'][$visible][$method->name]['final'] = true; } if ($method->isInternal()) { $result['methods'][$visible][$method->name]['internal'] = true; } if ($method->isStatic()) { $result['methods'][$visible][$method->name]['static'] = true; } if ($method->isConstructor()) { $result['methods'][$visible][$method->name]['constructor'] = true; } if ($method->isDestructor()) { $result['methods'][$visible][$method->name]['destructor'] = true; } $result['methods'][$visible][$method->name]['declaringClass'] = $method->getDeclaringClass()->name; if ($comment = $method->getDocComment()) { $result['methods'][$visible][$method->name]['comment'] = $comment; } $startLine = $method->getStartLine(); $endLine = $method->getEndLine(); if ($startLine && $source) { $from = (int) ($startLine - 1); $to = (int) ($endLine - $startLine + 1); $slice = array_slice($source, $from, $to); $phpCode = implode('', $slice); $result['methods'][$visible][$method->name]['source::source'] = $phpCode; } if ($params = self::_getParams($method->getParameters(), $method->isInternal())) { $result['methods'][$visible][$method->name]['parameters'] = $params; } } // get all methods $result['all_methods'] = get_class_methods($className); sort($result['all_methods']); // sorting properties and methods if (isset($result['properties']['protected'])) { ksort($result['properties']['protected']); } if (isset($result['properties']['private'])) { ksort($result['properties']['private']); } if (isset($result['properties']['public'])) { ksort($result['properties']['public']); } if (isset($result['methods']['protected'])) { ksort($result['methods']['protected']); } if (isset($result['methods']['private'])) { ksort($result['methods']['private']); } if (isset($result['methods']['public'])) { ksort($result['methods']['public']); } return $result; }
/** * {@inheritdoc} */ public function getEndLine() { return $this->reflectionClass->getEndLine(); }
<?php # Recipe 2-19 # More involved Reflection API example $class = 'myUser'; //require_once("./$class.class.php"); require_once "C:\\web\\registry\\apps\\frontend\\lib\\myUser.class.php"; $rc = new ReflectionClass($class); printf("<p>Name: *%s*<br />\n", $rc->getName()); printf("Defined in file '%s', lines %d - %d<br />\n", $rc->getFileName(), $rc->getStartLine(), $rc->getEndLine()); printf("<p>Contains the comments:<pre>%s</pre></p>", $rc->getDocComment()); printf("%s is %san interface.<br />\n", $rc->getName(), $rc->isInterface() ? '' : 'not '); printf("%s is %sinstantiable.<br />\n", $rc->getName(), $rc->isInstantiable() ? '' : 'not '); printf("%s is %sabstract.<br />\n", $rc->getName(), $rc->isAbstract() ? '' : 'not '); printf("%s is %sfinal.</p>\n", $rc->getName(), $rc->isFinal() ? '' : 'not '); $constants = $rc->getConstants(); $num_constants = count($constants); printf("%s defines %d constant%s", $rc->getName(), $num_constants == 0 ? 'no' : $num_constants, $num_constants != 1 ? 's' : ''); if ($num_constants > 0) { printf(":<pre>%s</pre>", print_r($constants, TRUE)); } $props = $rc->getProperties(); $num_props = count($props); printf("%s defines %d propert%s", $rc->getName(), $num_props == 0 ? 'no' : $num_props, $num_props == 1 ? 'y' : 'ies'); if ($num_props > 0) { print ':'; foreach ($props as $prop) { print "<pre>"; Reflection::export($prop); print "</pre>"; }
public function IspatchedOverrides($classname) { switch ($classname) { case 'Order': $path = Autoload::getInstance()->getClassPath($classname . 'Core'); // Check if there is already an override file, if not, we just need to copy the file if (Autoload::getInstance()->getClassPath($classname)) { // Check if override file is writable $override_path = _PS_ROOT_DIR_ . '/' . Autoload::getInstance()->getClassPath($classname); if (file_exists($override_path) && !is_writable($override_path)) { throw new Exception(sprintf(Tools::displayError('file (%s) not writable'), $override_path)); } // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration do { $uniq = uniqid(); } while (class_exists($classname . 'OverrideOriginal_remove', false)); // Make a reflection of the override class and the module override class $override_file = file($override_path); eval(preg_replace(array('#^\\s*<\\?php#', '#class\\s+' . $classname . '\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array('', 'class ' . $classname . 'OverrideOriginal' . $uniq), implode('', $override_file))); $override_class = new ReflectionClass($classname . 'OverrideOriginal' . $uniq); $module_file = file($this->getLocalPath() . 'override' . DIRECTORY_SEPARATOR . $path); eval(preg_replace(array('#^\\s*<\\?php#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array('', 'class ' . $classname . 'Override' . $uniq), implode('', $module_file))); $module_class = new ReflectionClass($classname . 'Override' . $uniq); // Check if none of the methods already exists in the override class $methodpatched = array('add' => array('patched' => false, 'method' => ' public function add($autodate = true, $null_values = true) { $cart = new Cart($this->id_cart); Hook::exec(\'actionBeforeAddOrder\', array(\'order\'=>$this,\'cart\'=>$cart)); if (ObjectModel::add($autodate, $null_values)) return SpecificPrice::deleteByIdCart($this->id_cart); return false; } '), 'setLastInvoiceNumber' => array('patched' => false, 'method' => ' public static function setLastInvoiceNumber($order_invoice_id, $id_shop) { if (!$order_invoice_id) return false; $number = Configuration::get(\'PS_INVOICE_START_NUMBER\', null, null, $id_shop); // If invoice start number has been set, you clean the value of this configuration if ($number) Configuration::updateValue(\'PS_INVOICE_START_NUMBER\', false, false, null, $id_shop); $order_invoice = new OrderInvoice($order_invoice_id); $order = new Order($order_invoice->id_order); $cart = new Cart($order->id_cart); if($ref = Hook::exec(\'actionBeforeAddOrderInvoice\', array(\'order_invoice\'=>$order_invoice,\'order\'=>$order,\'cart\'=>$cart))) $number = $ref; $sql = \'UPDATE `\'._DB_PREFIX_.\'order_invoice` SET number =\'; if ($number) $sql .= (int)$number; else $sql .= \'(SELECT new_number FROM (SELECT (MAX(`number`) + 1) AS new_number FROM `\'._DB_PREFIX_.\'order_invoice`) AS result)\'; $sql .=\' WHERE `id_order_invoice` = \'.(int)$order_invoice_id; return Db::getInstance()->execute($sql); } '), 'setDeliveryNumber' => array('patched' => false, 'method' => ' public function setDeliveryNumber($order_invoice_id, $id_shop) { if (!$order_invoice_id) return false; $number = Configuration::get(\'PS_DELIVERY_NUMBER\', null, null, $id_shop); // If invoice start number has been set, you clean the value of this configuration if ($number) Configuration::updateValue(\'PS_DELIVERY_NUMBER\', false, false, null, $id_shop); $order_invoice = new OrderInvoice($order_invoice_id); $order = new Order($order_invoice->id_order); $cart = new Cart($order->id_cart); if($ref = Hook::exec(\'actionBeforeAddDeliveryNumber\', array(\'order\'=>$order,\'cart\'=>$cart,\'number\'=>$number))) $number = $ref; $sql = \'UPDATE `\'._DB_PREFIX_.\'order_invoice` SET delivery_number =\'; if ($number) $sql .= (int)$number; else $sql .= \'(SELECT new_number FROM (SELECT (MAX(`delivery_number`) + 1) AS new_number FROM `\'._DB_PREFIX_.\'order_invoice`) AS result)\'; $sql .=\' WHERE `id_order_invoice` = \'.(int)$order_invoice_id; return Db::getInstance()->execute($sql); } ')); foreach ($module_class->getMethods() as $method) { if ($override_class->hasMethod($method->getName())) { $methodpatched[$method->getName()]['patched'] = true; } } // Insert the methods from module override in override foreach ($methodpatched as $patched) { if (!$patched['patched']) { $copy_from[] = $patched['method']; } } array_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from); $code = implode('', $override_file); file_put_contents($override_path, $code); return true; } else { return false; } break; case 'OrderInvoice': if (file_exists(_PS_OVERRIDE_DIR_ . 'classes/Order/OrderInvoice.php')) { $cont = file_get_contents(_PS_OVERRIDE_DIR_ . 'classes/Order/OrderInvoice.php'); if (strpos($cont, 'actionBeforeAddOrderInvoice') === false) { return false; } else { return true; } } else { return false; } break; case 'OrderPayment': if (file_exists(_PS_OVERRIDE_DIR_ . 'classes/Order/OrderPayment.php')) { $cont = file_get_contents(_PS_OVERRIDE_DIR_ . 'classes/Order/OrderPayment.php'); if (strpos($cont, '\'order_reference\' => array(\'type\' => self::TYPE_STRING, \'validate\' => \'isAnything\', \'size\' => 100),') === false) { return false; } else { return true; } } else { return false; } break; default: return false; } }
private static function get_reflection_source(\ReflectionClass $r) { return implode(array_slice(file($r->getFileName()), $r->getStartLine(), $r->getEndLine() - $r->getStartLine() - 1)); }
/** Tells weeDocumentor to get data of the specified class. The class must be declared before calling this method. @param $sClassName The class to get data from. @return $this For chained calls. */ public function docClass($sClassName) { $oClass = new ReflectionClass($sClassName); $a = array('name' => $oClass->getName(), 'parent' => $oClass->getParentClass() == null ? null : $oClass->getParentClass()->getName(), 'type' => $oClass->isInterface() ? 'interface' : ($oClass->isAbstract() ? 'abstract' : ($oClass->isFinal() ? 'final' : null)), 'filename' => substr($oClass->getFileName(), strlen(getcwd()) + 1), 'startline' => $oClass->getStartLine(), 'endline' => $oClass->getEndLine(), 'consts' => $oClass->getConstants()); // Get DocComment data $this->parseDocComment($this->trimDocComment($oClass->getDocComment()), $aParsedData); $a = array_merge($a, $aParsedData); // Interfaces $aImplement = $oClass->getInterfaces(); $a['implements'] = array(); foreach ($aImplement as $o) { $a['implements'][] = $o->getName(); } // Methods $aMethods = $oClass->getMethods(); $a['methods'] = array(); foreach ($aMethods as $o) { $aMethod = array('name' => $o->getName(), 'type' => $o->isStatic() ? 'static' : ($o->isAbstract() ? 'abstract' : ($o->isFinal() ? 'final' : null)), 'visibility' => $o->isPublic() ? 'public' : ($o->isPrivate() ? 'private' : 'protected'), 'internal' => $o->isInternal(), 'startline' => $o->getStartLine(), 'endline' => $o->getEndLine(), 'numreqparams' => $o->getNumberOfRequiredParameters()); if (!$aMethod['internal']) { $aHints = self::getParametersTypeHints($o); } $sFilename = substr($o->getFileName(), strlen(getcwd()) + 1); if (!empty($sFilename) && $sFilename != $a['filename']) { $aMethod['filename'] = $sFilename; } // Get DocComment data $this->parseDocComment($this->trimDocComment($o->getDocComment()), $aParsedData); $aMethod = array_merge($aMethod, $aParsedData); if (!empty($aFunc['return'])) { $aFunc['return']['ref'] = $o->returnsReference(); } $aMethod['params'] = array(); foreach ($o->getParameters() as $oParameter) { $aParameter = array('name' => $oParameter->getName(), 'ref' => $oParameter->isPassedByReference(), 'null' => $oParameter->allowsNull(), 'default' => $oParameter->isDefaultValueAvailable() ? var_export($oParameter->getDefaultValue(), true) : null); if (isset($aMethod['paramscomment'][$aParameter['name']])) { $aParameter['comment'] = $aMethod['paramscomment'][$aParameter['name']]; } if ($aMethod['internal']) { if ($oParameter->isArray()) { $aParameter['hint'] = 'array'; } } else { $aParameter['type'] = $this->getVariableType($aParameter['name']); if (isset($aHints[$aParameter['name']])) { $aParameter['hint'] = $aHints[$aParameter['name']]; } } $aMethod['params'][] = $aParameter; } unset($aMethod['paramscomment']); $a['methods'][] = $aMethod; } // Properties $aProperties = $oClass->getProperties(); $a['properties'] = array(); foreach ($aProperties as $o) { $aProperty = array('name' => $o->getName(), 'static' => $o->isStatic(), 'visibility' => $o->isPublic() ? 'public' : ($o->isPrivate() ? 'private' : 'protected')); // Get DocComment data $this->parseDocComment($this->trimDocComment($o->getDocComment()), $aParsedData); $aProperty = array_merge($aProperty, $aParsedData); $a['properties'][] = $aProperty; } // Sort child arrays usort($a['implements'], 'weeDocumentor::nameCmp'); usort($a['methods'], 'weeDocumentor::nameCmp'); usort($a['properties'], 'weeDocumentor::nameCmp'); // Finally store the data $this->aClasses[] = $a; return $this; }
/** * Applies the @covers annotation filtering. * * @param array $data * @param mixed $id */ protected function applyCoversAnnotationFilter(&$data, $id) { if ($id instanceof PHPUnit_Framework_TestCase) { $testClassName = get_class($id); $linesToBeCovered = PHP_CodeCoverage_Util::getLinesToBeCovered($testClassName, $id->getName()); if ($this->mapTestClassNameToCoveredClassName && empty($linesToBeCovered)) { $testedClass = substr($testClassName, 0, -4); if (class_exists($testedClass)) { $class = new ReflectionClass($testedClass); $linesToBeCovered = array($class->getFileName() => range($class->getStartLine(), $class->getEndLine())); } } } else { $linesToBeCovered = array(); } if (!empty($linesToBeCovered)) { $data = array_intersect_key($data, $linesToBeCovered); foreach (array_keys($data) as $filename) { $data[$filename] = array_intersect_key($data[$filename], array_flip($linesToBeCovered[$filename])); } } else { if ($this->forceCoversAnnotation) { $data = array(); } } }
public static function AnalyzeClass($ClassName) { if (!isset(self::$AnalyzeClassCache[$ClassName])) { $RefClass = new ReflectionClass($ClassName); if ($RefClass->isInternal()) { throw new Exception('SCAD_Analyze: cant analyze internal classes'); } $RefClassMethods = $RefClass->getMethods(); $RefClassInterfaces = $RefClass->getInterfaces(); $Constants = $RefClass->getConstants(); $RefClassProperties = $RefClass->getProperties(); if ($RefClassParent = $RefClass->getParentClass()) { $ParentMethods = $RefClassParent->getMethods(); $ParentMethodsList = array(); foreach ($ParentMethods as $ParentMethod) { $ParentMethodsList[] = $ParentMethod->getName(); } foreach ($RefClassMethods as $Key => $RefClassMethod) { if (in_array($RefClassMethod->getName(), $ParentMethodsList)) { unset($RefClassMethods[$Key]); } } $ParentConstants = $RefClassParent->getConstants(); foreach ($Constants as $ConstantName => $ConstantValue) { if (key_exists($ConstantName, $ParentConstants)) { unset($Constants[$ConstantName]); } } $ParentProperties = $RefClassParent->getProperties(); $ParentPropertiesList = array(); foreach ($ParentProperties as $ParentProperty) { $ParentPropertiesList[] = $ParentProperty->getName(); } foreach ($RefClassProperties as $Key => $RefClassProperty) { if (in_array($RefClassProperty->getName(), $ParentPropertiesList)) { unset($RefClassProperties[$Key]); } } $ParentInterfaces = $RefClassParent->getInterfaces(); $ParentInterfacesList = array(); foreach ($ParentInterfaces as $ParentInterface) { $ParentInterfacesList[] = $ParentInterface->getName(); } foreach ($RefClassInterfaces as $Key => $RefClassInterface) { if (in_array($RefClassInterface->getName(), $ParentInterfacesList)) { unset($RefClassInterface[$Key]); } } } $ClassFileName = $RefClass->getFileName(); $ClassFileArray = file($ClassFileName); $Methods = array(); foreach ($RefClassMethods as $RefMethod) { $NewMethod = array(); $Code = ""; foreach (range($RefMethod->getStartLine(), $RefMethod->getEndLine()) as $Line) { $Code .= $ClassFileArray[$Line - 1]; } $NewMethod['Code'] = $Code; $NewMethod['Name'] = $RefMethod->getName(); $NewMethod['Constructor'] = $RefMethod->isConstructor(); $NewMethod['Destructor'] = $RefMethod->isDestructor(); $NewMethod['Final'] = $RefMethod->isFinal(); $NewMethod['Start'] = $RefMethod->getStartLine(); $NewMethod['End'] = $RefMethod->getEndLine(); if ($RefMethod->isPrivate()) { $NewMethod['Scope'] = self::SCOPE_PRIVATE; } elseif ($RefMethod->isProtected()) { $NewMethod['Scope'] = self::SCOPE_PROTECTED; } else { $NewMethod['Scope'] = self::SCOPE_PUBLIC; } $Methods[$RefMethod->getName()] = $NewMethod; } $Properties = array(); if (!empty($RefClassProperties)) { $MagicInstance = self::generateMagicInstance($ClassName, $RefClass->getStartLine() - 1, $RefClass->getEndLine() - 1, $Methods, $RefClassProperties, $ClassFileArray); foreach ($RefClassProperties as $RefProperty) { $NewProperty = array(); if ($RefProperty->isPrivate()) { $NewProperty['Scope'] = self::SCOPE_PRIVATE; } elseif ($RefProperty->isProtected()) { $NewProperty['Scope'] = self::SCOPE_PROTECTED; } else { $NewProperty['Scope'] = self::SCOPE_PUBLIC; } // This value is totally useless for our situation // $NewProperty['Default'] = $RefProperty->isDefault(); $NewProperty['Static'] = $RefProperty->isStatic(); $NewProperty['Value'] = $MagicInstance->get($RefProperty->getName()); $NewProperty['Name'] = $RefProperty->getName(); $Properties[$RefProperty->getName()] = $NewProperty; } } if (!empty($RefClassInterfaces)) { $Interfaces = array(); foreach ($RefClassInterfaces as $RefClassInterface) { $Interfaces[] = $RefClassInterface->getName(); } $Result['Interfaces'] = $Interfaces; } $Result = array(); $Result['Methods'] = $Methods; $Result['Properties'] = $Properties; $Result['Constants'] = $Constants; $Result['FileName'] = $RefClass->getFileName(); $Result['Start'] = $RefClass->getStartLine(); $Result['End'] = $RefClass->getEndLine(); if ($RefClassParent) { $Result['Extends'] = $RefClassParent->getName(); } $Result['Abstract'] = $RefClass->isAbstract(); $Result['Final'] = $RefClass->isFinal(); $Result['Interface'] = $RefClass->isInterface(); $Result['Instantiable'] = $RefClass->isInstantiable(); $Result['Name'] = $RefClass->getName(); self::$AnalyzeClassCache[$ClassName] = $Result; } return self::$AnalyzeClassCache[$ClassName]; }
public function getSource() { $reflector = new ReflectionClass($this); $file = $reflector->getFileName(); if (!file_exists($file)) { return; } $source = file($file, FILE_IGNORE_NEW_LINES); array_splice($source, 0, $reflector->getEndLine()); $i = 0; while (isset($source[$i]) && '/* */' === substr_replace($source[$i], '', 3, -2)) { $source[$i] = str_replace('*//* ', '*/', substr($source[$i], 3, -2)); ++$i; } array_splice($source, $i); return implode("\n", $source); }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $kernel = $this->getApplication()->getKernel(); $bundle = $kernel->getBundle('App'); $name = $input->getArgument('name'); $twig = $this->createTwig(); $dialog = $this->getHelperSet()->get('dialog'); $controller = $name; $action = null; if (2 === count($parts = explode(':', $name))) { list($controller, $action) = $parts; } $class = sprintf('%sController', str_replace('/', '\\', $controller)); $subns = dirname(str_replace('\\', '/', $class)); $namespace = sprintf('%s\\Controller%s', $bundle->getNamespace(), '.' !== $subns ? '\\' . $subns : ''); $classPath = sprintf('%s/Controller/%s.php', $bundle->getPath(), str_replace('\\', '/', $class)); $class = basename(str_replace('\\', '/', $class)); $fqcn = sprintf('%s\\%s', $namespace, $class); $name = basename(str_replace('\\', '/', $controller)); $output->writeLn(sprintf('- <comment>App:%s</comment> controller:', str_replace('/', '\\', $controller))); if (!class_exists($fqcn)) { $this->writeFile($classPath, $twig->render('controller.php.twig', array('namespace' => $namespace, 'class' => $class, 'name' => $name))); $output->writeLn(' class <info>generated</info>'); } else { $output->writeLn(' class <info>already exists</info>'); } if (null === $action) { return; } $output->writeLn(sprintf("\n" . '- <comment>App:%s:%s</comment> action:', str_replace('/', '\\', $controller), $action)); $refl = new \ReflectionClass($fqcn); if (!$refl->hasMethod($action)) { $prefix = ''; $lineToAppend = $refl->getEndLine(); foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { if ($refl->getName() !== $method->getDeclaringClass()->getName()) { continue; } $prefix = "\n"; $lineToAppend = $method->getEndLine() + 1; } $this->appendToFile($refl->getFileName(), $lineToAppend - 2, $prefix . $twig->render('action.php.twig', array('action' => $action))); $output->writeLn(' method <info>generated</info>'); } else { $output->writeLn(' method <info>already exists</info>'); } $viewPath = sprintf('%s/Resources/views/%s/%s.html.twig', $bundle->getPath(), str_replace('\\', '/', $controller), $action); $output->writeLn(sprintf("\n" . '- <comment>App:%s:%s.html.twig</comment> view:', str_replace('\\', '/', $controller), $action)); if (!file_exists($viewPath)) { $this->writeFile($viewPath, $twig->render('view.html.twig')); $output->writeLn(' view <info>generated</info>'); } else { $output->writeLn(' view <info>already exists</info>'); } $routingPath = sprintf('%s/Resources/config/routing.yml', $bundle->getPath()); $routeName = $this->underscore($name) . '_' . $this->underscore($action); $routePath = '/' . $this->underscore($name) . '/' . $this->underscore($action); $controller = 'App:' . str_replace('/', '\\', $controller) . ':' . $action; $output->writeLn(sprintf("\n" . '- <comment>%s</comment> route:', $routePath)); if (!file_exists($routingPath)) { $output->writeLn(sprintf(' file <info>%s</info> does not exist.', $routingPath)); if (!$dialog->askConfirmation($output, ' do you want me to create it? [Y/n] ', 'y')) { return; } $this->writeFile($routingPath, ''); } $content = file_get_contents($routingPath); if (!preg_match('/' . preg_quote($controller, '/') . '[^a-zA-Z0-9]/', $content)) { $this->appendToFile($routingPath, null, $twig->render('routing.yml.twig', array('routeName' => $routeName, 'routePath' => $routePath, 'controller' => $controller))); $output->writeLn(' route <info>added</info>'); } else { $output->writeLn(' route <info>already exists</info>'); } }