Files
php-bsrutils/src/Utils/FileSystem/FileSystem.php
Guillermo Dev 762e6ace96 tests pass
2018-10-21 23:02:10 +02:00

45 lines
1.2 KiB
PHP

<?php
namespace Bsr\Utils\FileSystem;
class FileSystem
{
/**
* @param string $path full path
* @throws Exception if not writable
*/
public static function createFileOrDirIfNotExists($path, $file=false, $throw=true)
{
if (file_exists($path)) {
return true;
}
$parts = explode('/', $path);
if ($file) {
$fileName = array_pop($parts);
}
$partsCount = count($parts);
$buildPath = '';
for ($i=0; $i<$partsCount; $i++) {
$part = $parts[$i];
if (!file_exists($buildPath . "/$part")) {
if (!is_writable($buildPath)) {
if ($throw) {
throw new Exception("Attempting to create : $path, but $buildPath is not writeable.");
}
return false;
}
break;
}
$buildPath .= "/$part";
}
$dirPath = implode('/', $parts);
if (!file_exists($dirPath)) {
mkdir($dirPath, 0777, true);
}
if ($file) {
touch("$dirPath/$fileName");
}
return true;
}
}