<?php

class PHPUnitAutoload
{
    protected static 
$instance;

    
/**
     * Wrapper method to register this autoloader
     *
     * @throws Exception
     */
    
public static function register()
    {
        if (!(
self::$instance instanceof PHPUnitAutoload)) {
            if (
false === spl_autoload_register(array(self::getInstance(), 'autoload'))) {
                throw new 
Exception(sprintf('Unable to register %s::autoload as an autoloading method.'get_class(self::getInstance())));
            }
        }
    }

    
/**
     * Getter for singleton
     *
     * @return PHPUnitAutoload
     */
    
protected static function getInstance()
    {
        if (!isset(
self::$instance)) {
            
self::$instance = new PHPUnitAutoload();
        }

        return 
self::$instance;
    }

    
/**
     * Wrapper method for unregistering autloader     *
     */
    
public static function unregister()
    {
        
spl_autoload_unregister(array(self::getInstance(), 'autoload'));
    }

    
/**
     * Autoloader
     *
     * @param string
     * @throws Exception
     */
    
protected function autoload($class)
    {
        
// Set basepath to test/lib directory so we can build uri
        
$baseDir substr(__FILE__0strpos(__FILE__'/test')) . '/test/lib';

        
// Compare class name with known PHPUnit libs, if match found, replace theirs with ours
        
if (stripos($class'PHP_CodeCoverage') !== false) {
            
$class str_replace('PHP''PHPCodeCoverage'$class);
        } elseif (
stripos($class'PHP_Timer') !== false) {
            
$class str_replace('PHP''PHPTimer'$class);
        } elseif (
stripos($class'File_Iterator') !== false) {
            
$class str_replace('File''PHPFileIterator'$class);
        }

        
// Make class a path
        
$classAsDir str_ireplace('_'DIRECTORY_SEPARATOR$class);

        
$classUri $baseDir DIRECTORY_SEPARATOR $classAsDir '.php';

        if (
is_file($classUri)) {
            require_once 
$classUri;
        } else {
            throw new 
Exception(sprintf('Unable to load class (%s)'$classUri)); exit;
        }
    }
}