Jason Demitri
Jason Demitri

Reputation: 13

php function to search paths for filename WITHOUT extension

Right so i'm making a configuration class that will use an array of different file types in 4 main locations. Now I want to make it so that the configuration class will search these locations in order at the moment i'm using the following

if (file_exists(ROOT . DS . 'Application/Config/' . APP_ENV . DS . $file)) {
        $this->filePath = ROOT . DS . 'Application/Config/' . APP_ENV . DS . $file;
        echo $this->filePath;
    } else {
        if (file_exists(ROOT . DS . "Application/Config/$file")) {
            $this->filePath = ROOT . DS . "Application/Config/$file";
            echo $this->filePath;
        } else {
            if (file_exists(CARBON_PATH . 'Config' . DS . APP_ENV . DS . $file)) {
                $this->filePath = CARBON_PATH . 'Config' . DS . APP_ENV . DS . $file;
                echo $this->filePath;
            } else {
                if (file_exists(CARBON_PATH . "Config/$file")) {
                    $this->filePath = CARBON_PATH . "Config/$file";
                    echo $this->filePath;
                } else {
                    throw new \Exception("Unable to locate: $file, Please check it exists");
                }
            }
        }
    }

pretty messy and not very flexible.

What I want to be able to do is search the locations in the same order BY FILE NAME ONLY after finding the first match It would then return the file with the extension for the configuration class to use the correct method to parse into a php array and so on.

What is the best way to search these locations for a file name

Example Say we want a database configuration file as you can see there are 2

ConfigLocation1/Dev/
   /file.php
   /database.json
ConfigLocation1/
   /database.ini
   /anotherfile.json

I would want to use the function like so

config::findFile('database');

and it return

$result = ConfigLocation1/Dev/database.json

but if it wasnt found here then then

$result = ConfigLocation1/database.ini

Not very good at explaining things so hope the example helps

Upvotes: 0

Views: 75

Answers (1)

kamal pal
kamal pal

Reputation: 4207

As you mentioned you need to check for file in 4 locations, so instead of if conditions, create an array of directories and loop through.

and you can use glob, to find a file irrespective of extension. see my example below:-

//Make a array of directory where you want to look for files.
$dirs = array(
    ROOT . DS . 'Application/Config/' . APP_ENV . DS,
    CARBON_PATH . 'Config' . DS . APP_ENV . DS
);

function findFiles($directory, $filename){
    $match = array();

    foreach ($directory => $dir) {
        $files = glob($dir.$filename);
        foreach ($files as $file) {
             $match[] = $file;
        }

    }

    return $match;
} 

// to find database
$results = findFiles($dirs, 'database.*');

Upvotes: 1

Related Questions