add file system class for missing file/dir creation with writability exception
parent
bdf897fed5
commit
10715899a0
@ -0,0 +1,45 @@
|
||||
<?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;
|
||||
}
|
||||
|
||||
$notExistsPart = false;
|
||||
$parts = explode('/', $path);
|
||||
$partsCount = count($parts);
|
||||
$buildPath = '';
|
||||
for ($i=0; $i<$partsCount; $i++) {
|
||||
$part = $parts[$i];
|
||||
if (!file_exists($buildPath . "/$part")) {
|
||||
if (!is_writable($builPath)) {
|
||||
if ($throw) {
|
||||
throw new Exception("Attempting to create : $path, but $buildPath is not writeable.");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
$notExistsPart = true;
|
||||
break;
|
||||
}
|
||||
$buildPath .= "/$part";
|
||||
}
|
||||
|
||||
if ($file) {
|
||||
$fileName = array_pop($parts);
|
||||
}
|
||||
$dirPath = implode('/', $parts);
|
||||
mkdir($dirPath, 0777, true);
|
||||
if ($file) {
|
||||
touch("$dirPath/$fileName");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue