1
0
mirror of https://github.com/danog/class-finder.git synced 2025-01-23 06:11:26 +01:00

Initial commit - copy content from Stack Overflow

This commit is contained in:
Hayden Pierce 2018-07-14 08:27:13 -05:00
commit d5fb2dcee6
2 changed files with 63 additions and 0 deletions

12
composer.json Normal file
View File

@ -0,0 +1,12 @@
{
"name": "hpierce1102/class-finder",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Hayden Pierce",
"email": "hayden@haydenpierce.com"
}
],
"require": {}
}

51
src/ClassFinder.php Normal file
View File

@ -0,0 +1,51 @@
<?php
namespace HaydenPierce\ClassFinder;
class ClassFinder
{
//This value should be the directory that contains composer.json
const appRoot = __DIR__ . "/../../";
public static function getClassesInNamespace($namespace)
{
$files = scandir(self::getNamespaceDirectory($namespace));
$classes = array_map(function($file) use ($namespace){
return $namespace . '\\' . str_replace('.php', '', $file);
}, $files);
return array_filter($classes, function($possibleClass){
return class_exists($possibleClass);
});
}
private static function getDefinedNamespaces()
{
$composerJsonPath = self::appRoot . 'composer.json';
$composerConfig = json_decode(file_get_contents($composerJsonPath));
//Apparently PHP doesn't like hyphens, so we use variable variables instead.
$psr4 = "psr-4";
return (array) $composerConfig->autoload->$psr4;
}
private static function getNamespaceDirectory($namespace)
{
$composerNamespaces = self::getDefinedNamespaces();
$namespaceFragments = explode('\\', $namespace);
$undefinedNamespaceFragments = [];
while($namespaceFragments) {
$possibleNamespace = implode('\\', $namespaceFragments) . '\\';
if(array_key_exists($possibleNamespace, $composerNamespaces)){
return realpath(self::appRoot . $composerNamespaces[$possibleNamespace] . implode('/', $undefinedNamespaceFragments));
}
$undefinedNamespaceFragments[] = array_pop($namespaceFragments);
}
return false;
}
}