A simple class with some static methods for manipulating file paths properly regardless of system architecture
I was working on a legacy PHP project where there was all sort of code like this:
$routes = include(__DIR_ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'routes.php');
I then remembered that golang's filepath package would fluently join a url like this. So this is a port of the methods in golang's path/filepath package
composer require nelwhix/filepath
Join Method: Using the static 'join' method the code for the example earlier will look like this:
$url = \Nelwhix\Filepath\Filepath::join(__DIR__, 'src', 'routes.php');
$routes = include($url);
Base method: The base method returns the last part of any filepath passed to it. Like this:
\Nelwhix\Filepath\Filepath::base("/foo/bar/baz.js");
// this will return "baz.js"
\Nelwhix\Filepath\Filepath::abs("Filepath.php");
// this returns "\C:\Users\USER PC\Documents\Open Source contributions\filepath\src\Filepath.php"
\Nelwhix\Filepath\Filepath::dir("/foo/bar/baz.js")
// returns "/foo/bar"
\Nelwhix\Filepath\Filepath::clean("//dirty///path////");
// this returns /dirty/path
\Nelwhix\Filepath\Filepath::ext("/src/routes.php");
// returns ".php"
$split = \Nelwhix\Filepath\Filepath::split("./Documents/side-projects/filepath/composer.json");
$split->dir; // ./Documents/side-projects/filepath
$split->file; // composer.json
Filepath::walk("C:\Users\USER PC\Documents\\300L books", function (\DirectoryIterator $param) {
if($param->isDot()) return;
echo $param->getFilename() . "\n";
});
Nelwhix\Filepath\Filepath::glob(".php", "side-projects/src");
// returns an array containing the files matching the pattern