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:
commit
d5fb2dcee6
12
composer.json
Normal file
12
composer.json
Normal 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
51
src/ClassFinder.php
Normal 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;
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user