Skip to content

Commit

Permalink
FileSystem: Add method makeWritable() (#244)
Browse files Browse the repository at this point in the history
  • Loading branch information
janbarasek authored and dg committed Aug 16, 2021
1 parent e0a89b6 commit 5c36cc1
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Utils/FileSystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,29 @@ public static function write(string $file, string $content, ?int $mode = 0666):
}


/**
* Fixes permissions to a specific file or directory. Directories can be fixed recursively.
* @throws Nette\IOException on error occurred
*/
public static function makeWritable(string $path, int $dirMode = 0777, int $fileMode = 0666): void
{
if (is_file($path)) {
if (!@chmod($path, $fileMode)) { // @ is escalated to exception
throw new Nette\IOException("Unable to chmod file '$path' to mode " . decoct($fileMode) . '. ' . Helpers::getLastError());
}
} elseif (is_dir($path)) {
foreach (new \FilesystemIterator($path) as $item) {
static::makeWritable($item->getPathname(), $dirMode, $fileMode);
}
if (!@chmod($path, $dirMode)) { // @ is escalated to exception
throw new Nette\IOException("Unable to chmod directory '$path' to mode " . decoct($dirMode) . '. ' . Helpers::getLastError());
}
} else {
throw new Nette\IOException("File or directory '$path' not found.");
}
}


/**
* Determines if the path is absolute.
*/
Expand Down
21 changes: 21 additions & 0 deletions tests/Utils/FileSystem.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,24 @@ test('isAbsolute', function () {
Assert::true(FileSystem::isAbsolute('http://file'));
Assert::true(FileSystem::isAbsolute('remote://file'));
});


if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
test('makeWritable', function () {
FileSystem::createDir(getTempDir() . '/12/x');
FileSystem::write(getTempDir() . '/12/x/file', 'Hello');
chmod(getTempDir() . '/12/x/file', 0444);
chmod(getTempDir() . '/12/x', 0555);
chmod(getTempDir() . '/12', 0555);

FileSystem::makeWritable(getTempDir() . '/12');

Assert::same(0777, fileperms(getTempDir() . '/12') & 0777);
Assert::same(0777, fileperms(getTempDir() . '/12/x') & 0777);
Assert::same(0666, fileperms(getTempDir() . '/12/x/file') & 0777);
});
}

Assert::exception(function () {
FileSystem::makeWritable(getTempDir() . '/13');
}, Nette\IOException::class, "File or directory '%S%' not found.");

0 comments on commit 5c36cc1

Please sign in to comment.