Skip to content

Commit 5c36cc1

Browse files
janbarasekdg
authored andcommitted
FileSystem: Add method makeWritable() (#244)
1 parent e0a89b6 commit 5c36cc1

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Utils/FileSystem.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,29 @@ public static function write(string $file, string $content, ?int $mode = 0666):
148148
}
149149

150150

151+
/**
152+
* Fixes permissions to a specific file or directory. Directories can be fixed recursively.
153+
* @throws Nette\IOException on error occurred
154+
*/
155+
public static function makeWritable(string $path, int $dirMode = 0777, int $fileMode = 0666): void
156+
{
157+
if (is_file($path)) {
158+
if (!@chmod($path, $fileMode)) { // @ is escalated to exception
159+
throw new Nette\IOException("Unable to chmod file '$path' to mode " . decoct($fileMode) . '. ' . Helpers::getLastError());
160+
}
161+
} elseif (is_dir($path)) {
162+
foreach (new \FilesystemIterator($path) as $item) {
163+
static::makeWritable($item->getPathname(), $dirMode, $fileMode);
164+
}
165+
if (!@chmod($path, $dirMode)) { // @ is escalated to exception
166+
throw new Nette\IOException("Unable to chmod directory '$path' to mode " . decoct($dirMode) . '. ' . Helpers::getLastError());
167+
}
168+
} else {
169+
throw new Nette\IOException("File or directory '$path' not found.");
170+
}
171+
}
172+
173+
151174
/**
152175
* Determines if the path is absolute.
153176
*/

tests/Utils/FileSystem.phpt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,3 +165,24 @@ test('isAbsolute', function () {
165165
Assert::true(FileSystem::isAbsolute('http://file'));
166166
Assert::true(FileSystem::isAbsolute('remote://file'));
167167
});
168+
169+
170+
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
171+
test('makeWritable', function () {
172+
FileSystem::createDir(getTempDir() . '/12/x');
173+
FileSystem::write(getTempDir() . '/12/x/file', 'Hello');
174+
chmod(getTempDir() . '/12/x/file', 0444);
175+
chmod(getTempDir() . '/12/x', 0555);
176+
chmod(getTempDir() . '/12', 0555);
177+
178+
FileSystem::makeWritable(getTempDir() . '/12');
179+
180+
Assert::same(0777, fileperms(getTempDir() . '/12') & 0777);
181+
Assert::same(0777, fileperms(getTempDir() . '/12/x') & 0777);
182+
Assert::same(0666, fileperms(getTempDir() . '/12/x/file') & 0777);
183+
});
184+
}
185+
186+
Assert::exception(function () {
187+
FileSystem::makeWritable(getTempDir() . '/13');
188+
}, Nette\IOException::class, "File or directory '%S%' not found.");

0 commit comments

Comments
 (0)