ClassCollectionLoader.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\ClassLoader;
  11. /**
  12. * ClassCollectionLoader.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class ClassCollectionLoader
  17. {
  18. static private $loaded;
  19. /**
  20. * Loads a list of classes and caches them in one big file.
  21. *
  22. * @param array $classes An array of classes to load
  23. * @param string $cacheDir A cache directory
  24. * @param string $name The cache name prefix
  25. * @param Boolean $autoReload Whether to flush the cache when the cache is stale or not
  26. * @param Boolean $adaptive Whether to remove already declared classes or not
  27. * @param string $extension File extension of the resulting file
  28. *
  29. * @throws \InvalidArgumentException When class can't be loaded
  30. */
  31. static public function load($classes, $cacheDir, $name, $autoReload, $adaptive = false, $extension = '.php')
  32. {
  33. // each $name can only be loaded once per PHP process
  34. if (isset(self::$loaded[$name])) {
  35. return;
  36. }
  37. self::$loaded[$name] = true;
  38. if ($adaptive) {
  39. // don't include already declared classes
  40. $classes = array_diff($classes, get_declared_classes(), get_declared_interfaces());
  41. // the cache is different depending on which classes are already declared
  42. $name = $name.'-'.substr(md5(implode('|', $classes)), 0, 5);
  43. }
  44. $cache = $cacheDir.'/'.$name.$extension;
  45. // auto-reload
  46. $reload = false;
  47. if ($autoReload) {
  48. $metadata = $cacheDir.'/'.$name.$extension.'.meta';
  49. if (!is_file($metadata) || !is_file($cache)) {
  50. $reload = true;
  51. } else {
  52. $time = filemtime($cache);
  53. $meta = unserialize(file_get_contents($metadata));
  54. if ($meta[1] != $classes) {
  55. $reload = true;
  56. } else {
  57. foreach ($meta[0] as $resource) {
  58. if (!is_file($resource) || filemtime($resource) > $time) {
  59. $reload = true;
  60. break;
  61. }
  62. }
  63. }
  64. }
  65. }
  66. if (!$reload && is_file($cache)) {
  67. require_once $cache;
  68. return;
  69. }
  70. $files = array();
  71. $content = '';
  72. foreach ($classes as $class) {
  73. if (!class_exists($class) && !interface_exists($class) && (!function_exists('trait_exists') || !trait_exists($class))) {
  74. throw new \InvalidArgumentException(sprintf('Unable to load class "%s"', $class));
  75. }
  76. $r = new \ReflectionClass($class);
  77. $files[] = $r->getFileName();
  78. $c = preg_replace(array('/^\s*<\?php/', '/\?>\s*$/'), '', file_get_contents($r->getFileName()));
  79. // add namespace declaration for global code
  80. if (!$r->inNamespace()) {
  81. $c = "\nnamespace\n{\n".self::stripComments($c)."\n}\n";
  82. } else {
  83. $c = self::fixNamespaceDeclarations('<?php '.$c);
  84. $c = preg_replace('/^\s*<\?php/', '', $c);
  85. }
  86. $content .= $c;
  87. }
  88. // cache the core classes
  89. if (!is_dir(dirname($cache))) {
  90. mkdir(dirname($cache), 0777, true);
  91. }
  92. self::writeCacheFile($cache, '<?php '.$content);
  93. if ($autoReload) {
  94. // save the resources
  95. self::writeCacheFile($metadata, serialize(array($files, $classes)));
  96. }
  97. }
  98. /**
  99. * Adds brackets around each namespace if it's not already the case.
  100. *
  101. * @param string $source Namespace string
  102. *
  103. * @return string Namespaces with brackets
  104. */
  105. static public function fixNamespaceDeclarations($source)
  106. {
  107. if (!function_exists('token_get_all')) {
  108. return $source;
  109. }
  110. $output = '';
  111. $inNamespace = false;
  112. $tokens = token_get_all($source);
  113. for ($i = 0, $max = count($tokens); $i < $max; $i++) {
  114. $token = $tokens[$i];
  115. if (is_string($token)) {
  116. $output .= $token;
  117. } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  118. // strip comments
  119. continue;
  120. } elseif (T_NAMESPACE === $token[0]) {
  121. if ($inNamespace) {
  122. $output .= "}\n";
  123. }
  124. $output .= $token[1];
  125. // namespace name and whitespaces
  126. while (($t = $tokens[++$i]) && is_array($t) && in_array($t[0], array(T_WHITESPACE, T_NS_SEPARATOR, T_STRING))) {
  127. $output .= $t[1];
  128. }
  129. if (is_string($t) && '{' === $t) {
  130. $inNamespace = false;
  131. --$i;
  132. } else {
  133. $output .= "\n{";
  134. $inNamespace = true;
  135. }
  136. } else {
  137. $output .= $token[1];
  138. }
  139. }
  140. if ($inNamespace) {
  141. $output .= "}\n";
  142. }
  143. return $output;
  144. }
  145. /**
  146. * Writes a cache file.
  147. *
  148. * @param string $file Filename
  149. * @param string $content Temporary file content
  150. *
  151. * @throws \RuntimeException when a cache file cannot be written
  152. */
  153. static private function writeCacheFile($file, $content)
  154. {
  155. $tmpFile = tempnam(dirname($file), basename($file));
  156. if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
  157. chmod($file, 0644);
  158. return;
  159. }
  160. throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
  161. }
  162. /**
  163. * Removes comments from a PHP source string.
  164. *
  165. * We don't use the PHP php_strip_whitespace() function
  166. * as we want the content to be readable and well-formatted.
  167. *
  168. * @param string $source A PHP string
  169. *
  170. * @return string The PHP string with the comments removed
  171. */
  172. static private function stripComments($source)
  173. {
  174. if (!function_exists('token_get_all')) {
  175. return $source;
  176. }
  177. $output = '';
  178. foreach (token_get_all($source) as $token) {
  179. if (is_string($token)) {
  180. $output .= $token;
  181. } elseif (!in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  182. $output .= $token[1];
  183. }
  184. }
  185. // replace multiple new lines with a single newline
  186. $output = preg_replace(array('/\s+$/Sm', '/\n+/S'), "\n", $output);
  187. return $output;
  188. }
  189. }