Skip to content

Commit 6c977c8

Browse files
committed
Add validator type of file
1 parent e8294e6 commit 6c977c8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/Validator.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
* @method static bool isStream(mixed $value, array $rule = []) Checks if value is resource
3939
* @method static bool isDir(mixed $value, array $rule = []) Checks if value is directory
4040
* @method static bool isDirectory(mixed $value, array $rule = []) Checks if value is directory
41+
* @method static bool isFile(mixed $value, array $rule = []) Checks if value is file
4142
*/
4243
class Validator
4344
{
@@ -253,6 +254,10 @@ protected function registerBuiltInTypes()
253254
'alias' => 'directory',
254255
'validator' => [$this, 'validateDir']
255256
]);
257+
258+
$this->addType('file', [
259+
'validator' => [$this, 'validateFile']
260+
]);
256261
}
257262

258263
/**
@@ -942,4 +947,30 @@ protected function validateDir($value, array $rule = []): bool
942947

943948
return $valid;
944949
}
950+
951+
/**
952+
* Validate the $value is a valid file.
953+
*
954+
* @param $value
955+
* @param array $rule
956+
* @return bool
957+
*/
958+
protected function validateFile($value, array $rule = []): bool
959+
{
960+
$valid = is_file($value);
961+
962+
if ($valid && isset($rule['is_writable']) && $rule['is_writable'] == true) {
963+
if (!is_writeable($value)) {
964+
$this->setError($rule['name'], "File ($value) must be writable.");
965+
return true;
966+
}
967+
} elseif ($valid && isset($rule['is_writable']) && $rule['is_writable'] == false) {
968+
if (is_writeable($value)) {
969+
$this->setError($rule['name'], "File ($value) must not be writable.");
970+
return true;
971+
}
972+
}
973+
974+
return $valid;
975+
}
945976
}

0 commit comments

Comments
 (0)