27
Oct '14

Many of you may have already noticed that PHP’s ‘class_exists’ and similar methods don’t give you any help when you’ve got Composer (or most other autoloader solutions for that matter) loading your classes.
I was looking for a way to check for the existence of a class that was a little more clever than simply trying to look for files in folders so I came up with this little function to extract the information directly from Composer’s class map.

/**
 * Check if a class is autoloaded
 * @param string $class_name Class name
 * @return boolean
 */
public static function isAutoloaded($class_name) {
    $class_loader = require(base_path() . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php');
    $class_map = $class_loader->getClassMap();

    //Remove any preceding slashes in the class name (they may be there due to namespacing but composer doesn't store them in the class map entries)
    $class_name = preg_replace('/^\\\\+/', '', $class_name);

    return isset($class_map[$class_name]);
}