function add_internal($internal_classes) { global $functions, $internal_arginfo; foreach ($internal_classes as $class_name) { add_class($class_name, 0); } foreach (get_declared_interfaces() as $class_name) { add_class($class_name); } foreach (get_declared_traits() as $class_name) { add_class($class_name); } foreach (get_defined_functions()['internal'] as $function_name) { $function = new \ReflectionFunction($function_name); $required = $function->getNumberOfRequiredParameters(); $optional = $function->getNumberOfParameters() - $required; $functions[strtolower($function_name)] = ['file' => 'internal', 'namespace' => $function->getNamespaceName(), 'avail' => true, 'conditional' => false, 'flags' => 0, 'lineno' => 0, 'endLineno' => 0, 'name' => $function_name, 'docComment' => '', 'required' => $required, 'optional' => $optional, 'ret' => null, 'params' => []]; add_param_info($function_name); } foreach (array_keys($internal_arginfo) as $function_name) { if (strpos($function_name, ':') !== false) { continue; } $ln = strtolower($function_name); $functions[$ln] = ['file' => 'internal', 'avail' => false, 'conditional' => false, 'flags' => 0, 'lineno' => 0, 'endLineno' => 0, 'name' => $function_name, 'docComment' => '', 'ret' => null, 'params' => []]; add_param_info($function_name); } }
/** * {@inheritdoc} */ protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null) { // bail early if current PHP doesn't know about traits. if (!function_exists('trait_exists')) { return; } // only list traits when no Reflector is present. // // TODO: make a NamespaceReflector and pass that in for commands like: // // ls --traits Foo // // ... for listing traits in the Foo namespace if ($reflector !== null || $target !== null) { return; } // only list traits if we are specifically asked if (!$input->getOption('traits')) { return; } $traits = $this->prepareTraits(get_declared_traits()); if (empty($traits)) { return; } return array('Traits' => $traits); }
/** * Global variables dump : dump all variables and resource we can found : * - $GLOBALS * - $_SERVER * - all static property values from classes * * I don't know where I could found those : help me if you can ! * - all static variables declared into functions * - all opened resources (ie files or mysql links) * * @param $display boolean|string true or 'pre' if you want to displaying it * @return array returns the result array */ public static function globalDump($display = 'pre') { $dump['$GLOBALS'] = $GLOBALS; $dump['$_SERVER'] = $_SERVER; foreach (array_merge(get_declared_classes(), get_declared_traits()) as $class) { foreach ((new Reflection_Class($class))->getProperties([T_EXTENDS, T_USE]) as $property) { if ($property->isStatic()) { if (!$property->isPublic()) { $property->setAccessible(true); $not_accessible = true; } else { $not_accessible = false; } $dump['STATIC'][$class][$property->name] = $property->getValue(); if ($not_accessible) { $property->setAccessible(false); } } } } if ($display) { $pre = $display === 'pre'; echo ($pre ? '<pre>' : '') . print_r($dump, true) . ($pre ? '</pre>' : ''); } return $dump; }
/** * Allow traits to have custom initialization built in. * * @return void */ protected function bootTraits() { foreach (get_declared_traits() as $trait) { if (method_exists($this, 'boot' . class_basename($trait))) { $this->{'boot' . class_basename($trait)}(); } } }
/** * Loads a list of classes and caches them in one big file. * * @param array $classes An array of classes to load * @param string $cacheDir A cache directory * @param string $name The cache name prefix * @param bool $autoReload Whether to flush the cache when the cache is stale or not * @param bool $adaptive Whether to remove already declared classes or not * @param string $extension File extension of the resulting file * * @throws \InvalidArgumentException When class can't be loaded */ public static function load($classes, $cacheDir, $name, $autoReload, $adaptive = false, $extension = '.php') { // each $name can only be loaded once per PHP process if (isset(self::$loaded[$name])) { return; } self::$loaded[$name] = true; if ($adaptive) { $declared = array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits()); // don't include already declared classes $classes = array_diff($classes, $declared); // the cache is different depending on which classes are already declared $name = $name . '-' . substr(hash('sha256', implode('|', $classes)), 0, 5); } $classes = array_unique($classes); // cache the core classes if (!is_dir($cacheDir) && !@mkdir($cacheDir, 0777, true) && !is_dir($cacheDir)) { throw new \RuntimeException(sprintf('Class Collection Loader was not able to create directory "%s"', $cacheDir)); } $cacheDir = rtrim(realpath($cacheDir) ?: $cacheDir, '/' . DIRECTORY_SEPARATOR); $cache = $cacheDir . DIRECTORY_SEPARATOR . $name . $extension; // auto-reload $reload = false; if ($autoReload) { $metadata = $cache . '.meta'; if (!is_file($metadata) || !is_file($cache)) { $reload = true; } else { $time = filemtime($cache); $meta = unserialize(file_get_contents($metadata)); sort($meta[1]); sort($classes); if ($meta[1] != $classes) { $reload = true; } else { foreach ($meta[0] as $resource) { if (!is_file($resource) || filemtime($resource) > $time) { $reload = true; break; } } } } } if (!$reload && file_exists($cache)) { require_once $cache; return; } if (!$adaptive) { $declared = array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits()); } $files = self::inline($classes, $cache, $declared); if ($autoReload) { // save the resources self::writeCacheFile($metadata, serialize(array(array_values($files), $classes))); } }
/** * All declared traits can have their own initialisation method. This function * iterates over the declared traits and initialises them if necessary. * * NB - order of initialisation is order of declaration * * This function should be called from the contructor and it passes those * same variables used for construction to the traits' init methods. * * @param null|array $options An array of options */ private function initialiseTraits($options) { foreach (get_declared_traits() as $trait) { $fn = "{$trait}_Init"; if (method_exists($this, $fn)) { $this->{$fn}($options); } } }
/** * Make cache file from current loaded classes * */ public function cache() { set_time_limit(120); $swpLockFile = $this->getConfig()->getSwapFile() . '.lock'; if (is_file($swpLockFile)) { return; } file_put_contents($swpLockFile, ''); // Open working file if (is_file($this->getConfig()->getSwapFile()) === false) { file_put_contents($this->getConfig()->getSwapFile(), ''); } $this->handle = fopen($this->getConfig()->getSwapFile(), 'r+'); // Lock the file if (flock($this->handle, LOCK_EX) === false) { return; } // Clear the file ftruncate($this->handle, 0); // Traits first, then interfaces at last the classes $classes = array_merge(get_declared_traits(), get_declared_interfaces(), get_declared_classes()); // We only want to cache classes once $classes = array_unique($classes); $this->classList = array_flip($classes); $this->classList = array_fill_keys($classes, false); // Write PHP open tag fwrite($this->handle, '<?php' . PHP_EOL); // Walk through the classes foreach ($this->classList as $class => &$used) { $this->processClassIntoCacheFile(new Reflection\ClassReflection($class)); } // Flush last contents to the file fflush($this->handle); // Release the swap lock flock($this->handle, LOCK_UN); // Close cache file handle fclose($this->handle); // Minify cache file file_put_contents($this->getConfig()->getSwapFile(), php_strip_whitespace($this->getConfig()->getSwapFile())); $fileLock = $this->getConfig()->getFile() . '.lock'; file_put_contents($fileLock, ''); if (is_file($this->getConfig()->getFile())) { unlink($this->getConfig()->getFile()); } // Replace old cache file copy($this->getConfig()->getSwapFile(), $this->getConfig()->getFile()); if (is_file($this->getConfig()->getSwapFile())) { // Hotfix for Windows environments if (@unlink($this->getConfig()->getSwapFile()) === false) { unlink($this->getConfig()->getSwapFile()); } } // Unlink Locks unlink($swpLockFile); unlink($fileLock); }
/** * @return string[] internal symbols */ public function internalSymbolsProvider() { $allSymbols = array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits()); $indexedSymbols = array_combine($allSymbols, $allSymbols); return array_map(function ($symbol) { return [$symbol]; }, array_filter($indexedSymbols, function ($symbol) { $reflection = new PhpReflectionClass($symbol); return $reflection->isInternal(); })); }
function get_declared_user_traits() { $ret = array(); foreach (get_declared_traits() as $v) { // exclude system traits $rc = new ReflectionClass($v); if ($rc->getFileName() !== false) { $ret[] = $v; } } return $ret; }
/** * Warms up the cache. * * @param string $cacheDir The cache directory */ public function warmUp($cacheDir) { $classmap = $cacheDir . '/classes.map'; if (!is_file($classmap)) { return; } if (file_exists($cacheDir . '/classes.php')) { return; } $declared = null !== $this->declaredClasses ? $this->declaredClasses : array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits()); ClassCollectionLoader::inline(include $classmap, $cacheDir . '/classes.php', $declared); }
protected function processElementsItems() { $items = []; foreach (array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits()) as $name) { $reflection = new \ReflectionClass($name); if ($reflection->isInternal() || mb_substr($name, 0, 11) === 'FixinTools\\') { continue; } $items[$reflection->name] = new Item($this, $reflection); } ksort($items); $this->items = $items; }
private function processClassesAndTraits() { foreach (array_merge(get_declared_classes(), get_declared_traits()) as $classOrTrait) { if (isset($this->processedClasses[$classOrTrait])) { continue; } $reflector = new \ReflectionClass($classOrTrait); foreach ($reflector->getMethods() as $method) { $this->processFunctionOrMethod($method); } $this->processedClasses[$classOrTrait] = true; } }
/** * Load class in the source directory */ protected function loadClasses() { if (!is_dir($this->srcDirectory)) { throw new \Exception('Source directory not found : ' . $this->srcDirectory); } $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->srcDirectory), \RecursiveIteratorIterator::SELF_FIRST); $Regex = new \RegexIterator($objects, '/^.+\\.php$/i', \RecursiveRegexIterator::GET_MATCH); foreach ($Regex as $name => $object) { if (!empty($name)) { require_once $name; } } $classes = get_declared_classes(); $traits = get_declared_traits(); $interfaces = get_declared_interfaces(); $this->loadedClasses = array_merge($classes, $traits, $interfaces); }
/** * @param string[] $fileNames * @throws MetaException * @return boolean */ public function processFiles(array $fileNames) { $types = array(); foreach ($fileNames as $fileName) { require_once $fileName; } foreach (array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits()) as $typeName) { $rc = new \ReflectionClass($typeName); if ($rc->getFileName() && in_array(realpath($rc->getFileName()), $fileNames)) { $types[] = Type::fromReflection($rc); } } $matched = false; foreach ($types as $type) { $result = $this->compile($type); if ($result === null) { continue; } $matched = true; $outputFileName = $this->createOutputFileName($type, $result->getClass()); $outputDirectory = dirname($outputFileName); if (!is_dir($outputDirectory)) { if (!mkdir($outputDirectory, 0777, true)) { throw new MetaException("Could not create output directory '{$outputDirectory}'."); } } $content = (string) $result->getFile(); // do not overwrite files with same content if (!file_exists($outputFileName) || md5_file($outputFileName) !== md5($content)) { if (!file_put_contents($outputFileName, $content)) { throw new MetaException("Could not write output to file '{$outputFileName}'."); } } } return $matched; }
#!/usr/bin/php <?php /** * Tool to auto insert use statements into PHP */ $ignore = get_defined_functions()['internal']; $ignore = array_merge($ignore, get_declared_classes()); $ignore = array_merge($ignore, get_declared_interfaces()); $ignore = array_merge($ignore, get_declared_traits()); $ignore = array_merge($ignore, array_keys(get_defined_constants())); $ignore[] = 'parent'; $ignore[] = 'self'; $inputFile = $argv[1]; require dirname(__FILE__) . '/vendor/autoload.php'; /** * Returns project root path. The root is where composer.json is defined */ function findProject($filename) { $filename = realpath($filename); if ($filename == '/') { return null; } if (file_exists(dirname($filename) . '/composer.json')) { return dirname($filename); } return findProject(dirname($filename)); } /** * Returns the parsed AST */
<?php declare (strict_types=1); namespace Phan\Tests\Language; // Grab these before we define our own classes $internal_class_name_list = get_declared_classes(); $internal_interface_name_list = get_declared_interfaces(); $internal_trait_name_list = get_declared_traits(); $internal_function_name_list = get_defined_functions()['internal']; use Phan\CodeBase; use Phan\Config; use Phan\Language\Context; use Phan\Language\UnionType; class UnionTypeTest extends \PHPUnit_Framework_TestCase { /** @var Context|null */ protected $context = null; /** @var CodeBase */ protected $code_base = null; protected function setUp() { global $internal_class_name_list; global $internal_interface_name_list; global $internal_trait_name_list; global $internal_function_name_list; $this->code_base = new CodeBase($internal_class_name_list, $internal_interface_name_list, $internal_trait_name_list, $internal_function_name_list); $this->context = new Context(); } public function tearDown() {
<?php //======================================================================== // Author: Pascal KISSIAN // Resume: http://pascal.kissian.net // // Copyright (c) 2015 Pascal KISSIAN // // Published under the MIT License // Consider it as a proof of concept! // No warranty of any kind. // Use and abuse at your own risks. //======================================================================== $t_pre_defined_classes = array_flip(array_map('strtolower', get_declared_classes())); $t_pre_defined_interfaces = array_flip(array_map('strtolower', get_declared_interfaces())); $t_pre_defined_traits = function_exists('get_declared_traits') ? array_flip(array_map('strtolower', get_declared_traits())) : array(); $t_pre_defined_classes = array_merge($t_pre_defined_classes, $t_pre_defined_interfaces, $t_pre_defined_traits); $t_pre_defined_class_methods = array(); $t_pre_defined_class_methods_by_class = array(); $t_pre_defined_class_properties = array(); $t_pre_defined_class_properties_by_class = array(); $t_pre_defined_class_constants = array(); $t_pre_defined_class_constants_by_class = array(); foreach ($t_pre_defined_classes as $pre_defined_class_name => $dummy) { $t = array_flip(array_map('strtolower', get_class_methods($pre_defined_class_name))); if (count($t)) { $t_pre_defined_class_methods_by_class[$pre_defined_class_name] = $t; } $t_pre_defined_class_methods = array_merge($t_pre_defined_class_methods, $t); $t = get_class_vars($pre_defined_class_name); if (count($t)) {
function getUserDefinedTraits() { static $traitCutoff; $traits = get_declared_traits(); if (!isset($traitCutoff)) { $traitCutoff = count($traits); for ($i = 0; $i < count($traits); $i++) { $methods = get_class_methods($traits[$i]); if (empty($methods)) { continue; } list($first) = $methods; if ((new \ReflectionMethod($traits[$i], $first))->isUserDefined()) { $traitCutoff = $i; break; } } } return array_slice($traits, $traitCutoff); }
$fp = fopen('tags', 'wb'); $build = function (array $arr) { $b = array(); foreach ($arr as $key => $val) { if ($val) { $b[] = "{$key}:{$val}"; } } return implode("\t", $b); }; $base = dirname(__DIR__) . '/'; $it = new AppendIterator(); $it->append(new ArrayIterator(get_declared_classes())); $it->append(new ArrayIterator(get_declared_interfaces())); if (function_exists('get_declared_traits')) { $it->append(new ArrayIterator(get_declared_traits())); } foreach ($it as $class) { $pathes = explode('\\', $class); if ('Test' === substr($class, -4) || 'Spec' === substr($class, -4) || 'PHP_Token_' === substr($class, 0, 10) || 'Double' === $pathes[0] || in_array('Test', $pathes) || in_array('Spec', $pathes)) { continue; } $rc = new ReflectionClass($class); if ($rc->isInternal()) { continue; } if ($rc->isInterface()) { $kind = 'i'; } elseif (method_exists($rc, 'isTrait')) { if ($rc->isTrait()) { $kind = 't';
/** * Creates a snapshot of the current global state. * * @param Blacklist $blacklist * @param boolean $includeGlobalVariables * @param boolean $includeStaticAttributes * @param boolean $includeConstants * @param boolean $includeFunctions * @param boolean $includeClasses * @param boolean $includeInterfaces * @param boolean $includeTraits * @param boolean $includeIniSettings * @param boolean $includeIncludedFiles */ public function __construct(Blacklist $blacklist = null, $includeGlobalVariables = true, $includeStaticAttributes = true, $includeConstants = true, $includeFunctions = true, $includeClasses = true, $includeInterfaces = true, $includeTraits = true, $includeIniSettings = true, $includeIncludedFiles = true) { if ($blacklist === null) { $blacklist = new Blacklist(); } $this->blacklist = $blacklist; if ($includeConstants) { $this->snapshotConstants(); } if ($includeFunctions) { $this->snapshotFunctions(); } if ($includeClasses || $includeStaticAttributes) { $this->snapshotClasses(); } if ($includeInterfaces) { $this->snapshotInterfaces(); } if ($includeGlobalVariables) { $this->setupSuperGlobalArrays(); $this->snapshotGlobals(); } if ($includeStaticAttributes) { $this->snapshotStaticAttributes(); } if ($includeIniSettings) { $this->iniSettings = ini_get_all(null, false); } if ($includeIncludedFiles) { $this->includedFiles = get_included_files(); } if (function_exists('get_declared_traits')) { $this->traits = get_declared_traits(); } }
/* Prototype : proto array get_declared_traits() * Description: Returns an array of all declared traits. * Source code: Zend/zend_builtin_functions.c * Alias to functions: */ echo "*** Testing get_declared_traits() : basic functionality ***\n"; trait MyTrait { } // Zero arguments echo "\n-- Testing get_declared_traits() function with Zero arguments --\n"; var_dump(get_declared_traits()); foreach (get_declared_traits() as $trait) { if (!trait_exists($trait)) { echo "Error: {$trait} is not a valid trait.\n"; } } echo "\n-- Ensure trait is listed --\n"; var_dump(in_array('MyTrait', get_declared_traits())); echo "\n-- Ensure userspace interfaces are not listed --\n"; interface I { } var_dump(in_array('I', get_declared_traits())); echo "\n-- Ensure userspace classes are not listed --\n"; class MyClass { } var_dump(in_array('MyClass', get_declared_traits())); echo "Done";
/** * Indexes built-in PHP classes. */ protected function indexBuiltinClasses() { foreach (get_declared_traits() as $trait) { $element = new ReflectionClass($trait); if ($element->isInternal()) { $this->indexBuiltinStructuralElement($element); } } foreach (get_declared_interfaces() as $interface) { $element = new ReflectionClass($interface); if ($element->isInternal()) { $this->indexBuiltinStructuralElement($element); } } foreach (get_declared_classes() as $class) { $element = new ReflectionClass($class); if ($element->isInternal()) { $this->indexBuiltinStructuralElement($element); } } }
<?php class a { } interface b { } trait c { } abstract class d { } final class e { } var_dump(get_declared_classes()); var_dump(get_declared_traits());
public function declaredTraits() : array { return get_declared_traits(); }
/** * All declared traits can have their own initialisation method. This function * iterates over the declared traits and initialises them if necessary. * * NB - order of initialisation is order of declaration * * This function should be called from the contructor and it passes those * same variables used for construction to the traits' init methods. * * @param object $request See Parent class constructor * @param object $response See Parent class constructor * @param object $invokeArgs See Parent class constructor */ private function initialiseTraits($request, $response, $invokeArgs) { foreach (get_declared_traits() as $trait) { $fn = "{$trait}_Init"; if (method_exists($this, $fn)) { $this->{$fn}($request, $response, $invokeArgs); } } }
<?php include_once __DIR__ . '/vendor/autoload.php'; $appConfig = $appConfig = array('modules' => array(), 'module_listener_options' => array('module_paths' => array('./vendor'), 'config_glob_paths' => array('config/autoload/{,*.}{global,local}.php'))); for ($t = 0; $t < 50; $t++) { $app = \Zend\Mvc\Application::init($appConfig); \Zend\EventManager\StaticEventManager::resetInstance(); $app = null; } class Foo { private static $bar; } class Bar { private static $bar; } var_dump(array_map(function ($symbol) { return array_map(function (\ReflectionProperty $property) { return $property->getDeclaringClass()->getName() . '::$' . $property->getName(); }, array_filter((new \ReflectionClass($symbol))->getProperties(), function (\ReflectionProperty $property) { return $property->isStatic(); })); }, array_filter(array_merge(get_declared_classes(), get_declared_traits()), function ($symbol) { return !(new \ReflectionClass($symbol))->isInternal(); })));
/** * An array of file paths retrieved from {@see files()}. * * @param array $files A list of file paths. * @return array A list of classes. */ public static function classes(array $files) { $loader = new UniversalClassLoader(); // Support PSR-0 autoloading with a composer.json file // @todo: Add support for Composer's classmap autoloading. if (file_exists(VANITY_PROJECT_WORKING_DIR . '/vendor/composer/autoload_namespaces.php')) { // Register namespaces with the class loader $loader->registerNamespaces(include VANITY_PROJECT_WORKING_DIR . '/vendor/composer/autoload_namespaces.php'); } elseif (file_exists(VANITY_PROJECT_WORKING_DIR . '/composer.json')) { // Register namespaces with the class loader $composer = json_decode(file_get_contents(VANITY_PROJECT_WORKING_DIR . '/composer.json'), true); if (isset($composer['autoload']) && isset($composer['autoload']['psr-0'])) { $loader->registerNamespaces($composer['autoload']['psr-0']); } } $loader->register(); $class_list = array(); // Collect all current classes, interfaces and traits if (SystemStore::get('_.php54')) { $before = array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits()); } else { $before = array_merge(get_declared_classes(), get_declared_interfaces()); } foreach ($files as $file) { include_once $file; } // Handle traits if this version of PHP supports them. if (SystemStore::get('_.php54')) { $after = array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits()); } else { $after = array_merge(get_declared_classes(), get_declared_interfaces()); } // We should be able to document ourselves if (defined('VANITY_AM_I')) { $after = array_filter($after, function ($class) { return substr($class, 0, 7) !== 'Vanity\\'; }); } $class_list = array_values(array_unique(array_diff($after, $before))); sort($class_list); return $class_list; }
/** * Tells the class we're defining to implement interfaces, creating it if it does not * exist. * * @access public * @param string $interface The interface to implement * @return Mime The mime for method chaining */ public function implementing($interface) { foreach (func_get_args() as $interface) { $file = str_replace('\\', self::DS, $interface) . '.php'; $path = implode(self::DS, [__DIR__, self::INTERFACE_EXTENSIONS_DIR, $file]); if (isset(self::$registry[$interface]) || file_exists($path)) { if (!isset(self::$registry[$interface])) { $existing_traits = get_declared_traits(); $extension = (include $path); self::$extensions = array_merge(self::$extensions, $extension); self::$registry[$interface] = array_diff(get_declared_traits(), $existing_traits); return $this->implementing($interface); } else { foreach (self::$registry[$interface] as $trait) { $this->using($trait); } } } // // We want to create the interface if it doesn't exist yet. We don't want to // qualify the namespace until below. // if (!interface_exists($interface)) { $fqin = ltrim($interface, '\\'); $parts = explode('\\', $fqin); $interface = array_pop($parts); $ns = implode('\\', $parts); eval(call_user_func(function () use($ns, $interface) { ob_start(); ?> namespace <?php echo $ns; ?> { interface <?php echo $interface; ?> {} } <?php return ob_get_clean(); })); } self::$interfaces[$this->class][] = self::qualify($ns . '\\' . $interface); } return $this; }
/** * Loads a list of classes and caches them in one big file. * * @param array $classes An array of classes to load * @param string $cacheDir A cache directory * @param string $name The cache name prefix * @param bool $autoReload Whether to flush the cache when the cache is stale or not * @param bool $adaptive Whether to remove already declared classes or not * @param string $extension File extension of the resulting file * * @throws InvalidArgumentException When class can't be loaded */ public static function load($classes, $cacheDir, $name, $autoReload, $adaptive = false, $extension = '.php') { // each $name can only be loaded once per PHP process if (isset(self::$loaded[$name])) { return; } self::$loaded[$name] = true; $declared = array_merge(get_declared_classes(), get_declared_interfaces()); if (function_exists('get_declared_traits')) { $declared = array_merge($declared, get_declared_traits()); } if ($adaptive) { // don't include already declared classes $classes = array_diff($classes, $declared); // the cache is different depending on which classes are already declared $name = $name . '-' . substr(hash('sha256', implode('|', $classes)), 0, 5); } $classes = array_unique($classes); $cache = $cacheDir . '/' . $name . $extension; // auto-reload $reload = false; if ($autoReload) { $metadata = $cache . '.meta'; if (!is_file($metadata) || !is_file($cache)) { $reload = true; } else { $time = filemtime($cache); $meta = unserialize(file_get_contents($metadata)); sort($meta[1]); sort($classes); if ($meta[1] != $classes) { $reload = true; } else { foreach ($meta[0] as $resource) { if (!is_file($resource) || filemtime($resource) > $time) { $reload = true; break; } } } } } if (!$reload && is_file($cache)) { require_once $cache; return; } $files = array(); $content = ''; foreach (self::getOrderedClasses($classes) as $class) { if (in_array($class->getName(), $declared)) { continue; } $files[] = $class->getFileName(); $c = preg_replace(array('/^\\s*<\\?php/', '/\\?>\\s*$/'), '', file_get_contents($class->getFileName())); // fakes namespace declaration for global code if (!$class->inNamespace()) { $c = "\nnamespace\n{\n" . $c . "\n}\n"; } $c = self::fixNamespaceDeclarations('<?php ' . $c); $c = preg_replace('/^\\s*<\\?php/', '', $c); $content .= $c; } // cache the core classes if (!is_dir(dirname($cache))) { mkdir(dirname($cache), 0777, true); } self::writeCacheFile($cache, '<?php ' . $content); if ($autoReload) { // save the resources self::writeCacheFile($metadata, serialize(array($files, $classes))); } }
/** * Process declared elements */ protected function processElements() { foreach (array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits()) as $name) { $reflection = new \ReflectionClass($name); if ($reflection->isInternal() || mb_substr($name, 0, 11) === 'FixinTools\\') { continue; } $namespace = implode('\\', explode('\\', $name, -1)); $shortName = $this->classShortName($name); $this->namespaces[$namespace][$shortName] = $reflection; $this->shortNameResolve[$shortName] = $name; } ksort($this->namespaces); }