You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.2 KiB
PHP
47 lines
1.2 KiB
PHP
<?php
|
|
namespace Bsr\Utils\FileSystem;
|
|
|
|
use Bsr\Utils\FileSystem\Exception\BadEnvException;
|
|
|
|
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 BadEnvException("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;
|
|
}
|
|
}
|