I'm writing a class to check all my dependencies. One of those dependencies are inherited classes.
//File: A.php (For this example, file doesn't exist)
abstract class A{
}
//File: B.php
class B extends A{
}
//File: index.php
$files = scandir("/var/www");
foreach( $files as $class ) {
// Whole script fails here because file A.php doesn't exist.
// Need a graceful check to let the developer know a file is missing.
if( !class_exists($class) ) return false;
// Do other dependency checks.
}
I'm having trouble working out how to test if a parent class exists, Without the fatal error
Class 'A' not found
I have error handling for for my common classes. But for this test case, I need to be able to test for extended classes without knowing their name.
Using pomeh's suggestion, I've created a function to search for "class" and "extends" on the same line. It'll need some optimizing, but it works, so can work on that later.
function is_inherited($filePath) {
$classFileArray = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($classFileArray as $line) {
if( strpos($line, "class") === false ) continue;
if( strpos($line, "extends") === false ) continue;
$extendName = explode('extends', $line);
$extendName = explode( ' ', $extendName[1]);
return $extendName[1];
}
return false;
}
The library suggested by hakre sounds interesting, but overkill I think when a single function will work fine.