Skip to content

Instantly share code, notes, and snippets.

@danbettles
Created September 1, 2022 13:05
Show Gist options
  • Save danbettles/32892e26a94d983e83311ae457873c3a to your computer and use it in GitHub Desktop.
Save danbettles/32892e26a94d983e83311ae457873c3a to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace DanBettles\Marigold\Utils;
use function array_replace;
use function pathinfo;
use const null;
use const PATHINFO_EXTENSION;
class FilesystemUtils
{
/**
* `PATHINFO_ALL`:
* The array will always contain the `extension` element: the value will be `null` if the pathname contains no
* extension, or an empty string if the pathname has a blank extension.
*
* `PATHINFO_EXTENSION`:
* `null` if the pathname contains no extension, or an empty string if the pathname has a blank extension.
*
* @return array|string|null
*/
public static function pathinfo(
string $path,
int $flags = null
) {
if (null === $flags || PATHINFO_EXTENSION === $flags) {
$all = array_replace([
'extension' => null,
], pathinfo($path));
return PATHINFO_EXTENSION === $flags
? $all['extension']
: $all
;
}
return pathinfo($path, $flags);
}
}
<?php
declare(strict_types=1);
namespace DanBettles\Marigold\Tests\Utils;
use DanBettles\Marigold\AbstractTestCase;
use DanBettles\Marigold\Utils\FilesystemUtils;
use const null;
use const PATHINFO_EXTENSION;
class FilesystemUtilsTest extends AbstractTestCase
{
public function testPathinfoReturnsInformationAboutAFilePath()
{
$this->assertEquals(
[
'dirname' => $this->getFixturesDir(),
'basename' => 'hello_world.txt',
'filename' => 'hello_world',
'extension' => 'txt',
],
FilesystemUtils::pathinfo($this->createFixturePathname('hello_world.txt'))
);
$this->assertSame(
'txt',
FilesystemUtils::pathinfo($this->createFixturePathname('hello_world.txt'), PATHINFO_EXTENSION)
);
$this->assertEquals(
[
'dirname' => $this->getFixturesDir(),
'basename' => 'no_extension',
'filename' => 'no_extension',
'extension' => null,
],
FilesystemUtils::pathinfo($this->createFixturePathname('no_extension'))
);
$this->assertNull(
FilesystemUtils::pathinfo($this->createFixturePathname('no_extension'), PATHINFO_EXTENSION)
);
$this->assertEquals(
[
'dirname' => $this->getFixturesDir(),
'basename' => 'blank_extension.',
'filename' => 'blank_extension',
'extension' => '',
],
FilesystemUtils::pathinfo($this->createFixturePathname('blank_extension.'))
);
$this->assertSame(
'',
FilesystemUtils::pathinfo($this->createFixturePathname('blank_extension.'), PATHINFO_EXTENSION)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment