Skip to content

Commit 784dce3

Browse files
committed
add ensureExists method for Directory
1 parent b35b000 commit 784dce3

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/Directory.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ public function clean(): bool
8181
/**
8282
* Create a directory.
8383
*
84-
* @param int $mode The mode is 0777 by default, which means the widest possible access.
84+
* @param int $mode The mode is 0755 by default, which means the widest possible access.
8585
* @param bool $recursive Allows the creation of nested directories specified in the path.
8686
*
8787
* @return bool Returns TRUE on success or FALSE on failure.
@@ -146,6 +146,23 @@ public function copy(string $destination, ?int $flags = null): bool
146146
return true;
147147
}
148148

149+
/**
150+
* Ensure a directory exists.
151+
*
152+
* @param int $mode The mode is 0755 by default, which means the widest possible access.
153+
* @param bool $recursive Allows the creation of nested directories specified in the path.
154+
*
155+
* @return bool Returns TRUE on success or FALSE on failure.
156+
*/
157+
public function ensureExists($mode = 0755, $recursive = false)
158+
{
159+
if ($this->exists() === false) {
160+
return $this->create($mode, $recursive);
161+
}
162+
163+
return true;
164+
}
165+
149166
/**
150167
* Checks the existence of directory and returns false if any of them is missing.
151168
*

tests/FilesystemTest.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,6 @@
9696
$this->assertTrue($filesystem->isStream('file://1.txt'));
9797
});
9898

99-
10099
test('test isAbsolute method', function (): void {
101100
$filesystem = new Filesystem();
102101

@@ -228,6 +227,12 @@
228227
$this->assertTrue($filesystem->directory($this->tempDir . '/2/3/4/')->create(0755, true));
229228
});
230229

230+
test('test directory ensureExists() method', function (): void {
231+
$filesystem = new Filesystem();
232+
$this->assertTrue($filesystem->directory($this->tempDir . '/1')->ensureExists());
233+
$this->assertTrue($filesystem->directory($this->tempDir . '/1/2/3/4/')->ensureExists(0755, true));
234+
$this->assertTrue($filesystem->directory($this->tempDir . '/2/3/4/')->ensureExists(0755, true));
235+
});
231236

232237
test('test directory move() method', function (): void {
233238
@mkdir($this->tempDir . '/1');

0 commit comments

Comments
 (0)