Created
December 22, 2012 16:54
-
-
Save bamarni/4359881 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Symfony\Component\ClassLoader; | |
class LazyClassMapLoader | |
{ | |
private $classMap = array(); | |
private $collectedClasses = array(); | |
private $loader; | |
private $path; | |
private $registered; | |
public function __construct($path, $loader) | |
{ | |
if (!method_exists($loader, 'findFile')) { | |
throw new \InvalidArgumentException('The class finder must implement a "findFile" method.'); | |
} | |
if (file_exists($path)) { | |
$classMap = require $path; | |
if ($classMap && is_array($classMap)) { | |
$this->classMap = $classMap; | |
} | |
} | |
$this->path = $path; | |
$this->loader = $loader; | |
} | |
public function register($prepend = true) | |
{ | |
spl_autoload_register(array($this, 'loadClass'), true, $prepend); | |
register_shutdown_function(array($this, 'dump')); | |
$this->registered = true; | |
} | |
public function unregister() | |
{ | |
spl_autoload_unregister(array($this, 'loadClass')); | |
$this->registered = false; | |
} | |
public function loadClass($class) | |
{ | |
if ($file = $this->findFile($class)) { | |
include $file; | |
return true; | |
} | |
} | |
public function findFile($class) | |
{ | |
if (isset($this->classMap[$class])) { | |
return $this->classMap[$class]; | |
} | |
if ($file = $this->loader->findFile($class)) { | |
return $this->collectedClasses[$class] = $file; | |
} | |
return false; | |
} | |
public function dump() | |
{ | |
if (!$this->registered || !$this->collectedClasses) { | |
return; | |
} | |
$tmpFile = tempnam(dirname($this->path), basename($this->path)); | |
$handle = @fopen($tmpFile, 'w'); | |
$classes = array_merge($this->classMap, $this->collectedClasses); | |
@fwrite($handle, sprintf('<?php return %s;', var_export($classes, true))); | |
@fclose($handle); | |
if ($classes != file_get_contents($tmpFile)) { | |
return; | |
} | |
if (false === @rename($tmpFile, $this->path)) { | |
return; | |
} | |
@chmod($this->path, 0666 & ~umask()); | |
} | |
public function __call($method, $arguments) | |
{ | |
return call_user_func_array(array($this->loader, $method), $arguments); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment