add file system class for missing file/dir creation with writability exception

This commit is contained in:
Guillermo Dev
2018-10-21 22:45:15 +02:00
parent 7deff8ec61
commit 5300fbc3b9
2 changed files with 47 additions and 6 deletions

View File

@@ -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;
}
}

View File

@@ -2,6 +2,7 @@
namespace Bsr\Utils\Logger;
use Bsr\Utils\Configuration\Configuration;
use Bsr\Utils\FileSystem\FileSystem;
class Logger {
@@ -158,12 +159,7 @@ class Logger {
{
$mostRecentLogFileName = Configuration::get('log.file');
if (!file_exists($mostRecentLogFileName)) {
if (!is_dir(dirname($mostRecentLogFileName))) {
mkdir(dirname($mostRecentLogFileName), 0777, true);
}
touch($mostRecentLogFileName);
}
FileSystem::createFileOrDirIfNotExists($mostRecentLogFileName, true);
if(self::isMostRecentLogFileFromYesterday()) {
self::makeRoomForNewLogFile($mostRecentLogFileName);