Skip to content

Commit 03c81f6

Browse files
committed
Add test if filename is writable
1 parent 23c8537 commit 03c81f6

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/Filename.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,27 @@ public function exists() {
5353
return file_exists($this->name);
5454
}
5555

56+
/**
57+
* @return bool
58+
*/
59+
public function isWritable() {
60+
if (is_writeable($this->asString())) {
61+
return true;
62+
}
63+
64+
if (is_link($this->asString())) {
65+
// file_exists follows symlinks and returns false if the linked file does not exist
66+
// so we need to check first if the file is a link
67+
return false;
68+
}
69+
70+
if (file_exists($this->asString())) {
71+
return false;
72+
}
73+
74+
return $this->getDirectory()->isWritable();
75+
}
76+
5677
/**
5778
* @return bool
5879
*/

tests/FilenameTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,33 @@ public function testReturnsExpectedFilenameWithoutExtension() {
4949
$this->assertEquals($expected, $filename->withoutExtension());
5050
}
5151

52+
public function testIsWritable() {
53+
$filename = new Filename(__DIR__ . '/foo/bar.txt');
54+
$linkFilename = new Filename(__DIR__ . '/foo/link');
55+
56+
$this->assertFalse($filename->exists());
57+
$this->assertTrue($filename->isWritable());
58+
59+
try {
60+
touch($filename->asString());
61+
$this->assertTrue($filename->exists());
62+
$this->assertTrue($filename->isWritable());
63+
64+
// Make file non writable
65+
chmod($filename->asString(), 0000);
66+
$this->assertFalse($filename->isWritable());
67+
68+
// Create link to non writable file
69+
link($filename->asString(), $linkFilename->asString());
70+
$this->assertFalse($linkFilename->isWritable());
71+
72+
// Make file writable
73+
chmod($filename->asString(), 0644);
74+
$this->assertTrue($linkFilename->isWritable());
75+
} finally {
76+
unlink($filename->asString());
77+
unlink($linkFilename->asString());
78+
}
79+
}
80+
5281
}

0 commit comments

Comments
 (0)