From ce1cabc3c7fb89442caf2b98c4298b48a0deebc9 Mon Sep 17 00:00:00 2001 From: yggverse Date: Sun, 30 Jun 2024 02:04:10 +0300 Subject: [PATCH] init filesystem model --- src/Model/Filesystem.php | 98 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/Model/Filesystem.php diff --git a/src/Model/Filesystem.php b/src/Model/Filesystem.php new file mode 100644 index 0000000..bbeab1c --- /dev/null +++ b/src/Model/Filesystem.php @@ -0,0 +1,98 @@ +_base = realpath( + $dirname + ) . DIRECTORY_SEPARATOR; + } + + public function getBase(): string + { + return $this->_base; + } + + public function getAbsolute( + string $filename + ): ?string + { + // Require filename + if (empty($filename)) + { + throw new \Exception; + } + + // Unify separators + $filename = self::_fixDirectorySeparators( + $filename + ); + + // Check filename is absolute + if (str_starts_with($filename, DIRECTORY_SEPARATOR)) + { + // Check absolute filename path started with filesystem base + if (!str_starts_with($filepath, $this->_base)) + { + throw new \Exception; + } + + // Return as is + return $filename; + } + + // Append base + return $this->_base . $filename; + } + + private static function _fixDirectorySeparators( + string $path, + string $separator = DIRECTORY_SEPARATOR + ): string + { + return str_replace( + [ + '/', + '\\' // win + ], + $separator, + $path + ); + } +} \ No newline at end of file