antonioprimera / filesystem
一组简单的文件和文件夹类,易于管理文件和文件夹操作
v2.1
2024-09-23 16:31 UTC
Requires
- php: >=8.2
- ext-zip: *
Requires (Dev)
- pestphp/pest: ^v3.1.0
- spatie/ray: ^1.41
README
FileSystem包是一个PHP库,提供了一组用于以对象形式操作文件和目录的实用工具。它旨在使文件和目录操作更加简单和直观。
特性
- 文件和文件夹操作:移动、删除和创建文件和文件夹。
- 文件内容管理:读取、写入和替换文件内容。
- 路径操作:获取相对和绝对路径。
- 名称检查:检查文件或文件夹是否与特定模式匹配。
安装
使用composer安装FileSystem包
composer require antonioprimera/filesystem
用法
该包提供了两个主要类File
和Directory
,以及另一个辅助类OS
。
File
类代表一个文件,提供了读取、写入和操作文件内容的方法,而Folder
类代表一个目录,提供了处理目录的方法。
OS
类提供了处理跨平台路径字符串操作的静态方法,如连接路径、分割路径和规范化路径(例如,将路径分隔符转换为当前操作系统正确的格式)。
文件
以下是一些使用File
类的示例
use AntonioPrimera\FileSystem\File; // --- Generic methods, available for both File and Folder classes --- // Create a new file instance $file = new File('/path/to/file.txt'); //or $file = File::instance('/path/to/file.txt'); // Get the file name echo $file->name; // Get the file name without the extension echo $file->nameWithoutExtension; // Get the file extension echo $file->extension; // Get the file's containing folder path echo $file->folderPath; // Get the file's creation time echo $file->createTime; // Get the file's last modification time echo $file->modifiedTime; // Get the file's relative path, relative to a specific directory echo $file->relativePath('/path/to/directory'); // Get the file's containing folder path, relative to a specific directory echo $file->relativeFolderPath('/path/to/directory'); // Check if the file instance points to a given file path $isFile = $file->is('/path/to/file.txt'); // Check if the file name matches a specific pattern $matches = $file->nameMatches('/IMG_[0-9]{4}\.jpg/'); // Get the matches from the file name, for a specific pattern $matches = $file->getMatches('/IMG_([0-9]{4})\.jpg/'); //see: preg_match for the return value // --- Methods specific to the File class --- // Check if the file exists $exists = $file->exists; // Get the containing folder as a Folder instance $folder = $file->folder; // Get the file contents $contents = $file->contents; // Get the file size in bytes $size = $file->size; // Get the human-readable file size (e.g. 1.2 MB) $size = $file->humanReadableFileSize; // Get the sha256 hash of the file contents $hash = $file->hash; // Clone the file instance (to allow for multiple operations on the same file) $clone = $file->clone(); // Rename the file $file->rename(newFileName: 'new-name-without-extension', preserveExtension: true); // Move the file to a new directory $file->moveTo(targetFolder: '/path/to/new/directory', overwrite: true); // Delete the file $file->delete(); // Write contents to the file $file->putContents('Hello, World!'); // Copy the file contents of a given file to the current file (overwriting the current file) $file->copyContentsFromFile(sourceFile: '/path/to/other/file.txt'); // Copy the file contents of the current file to a given file (overwriting the target file) $file->copyContentsToFile(destinationFile: '/path/to/other/file.txt'); // Replace any placeholders in the file contents with the given values $file->replaceInFile(['{name}' => 'John Doe', '__DATE__' => date('d.M.Y')]); // Create a new empty file $file->create(); // OR $file->touch(); // Check if the file contains a specific string $containsString = $file->contains('Hello'); // Copy a file to a new location $file->copy('/path/to/new/file.txt', overwrite: true); // Backup the file by creating a copy in the same folder, appending .backup to the file name // If a backup already exists, a counter will be appended (e.g. test-file.001.backup) $file->backup();
目录
以下是一些使用Directory
类的示例。通用方法与File
类相同,因为两个类都扩展了同一个FileSystemItem类。
use AntonioPrimera\FileSystem\Folder; // --- Methods specific to the Folder class --- // Get a Folder instance for a subfolder $subFolderInstance = $folder->subFolder('subfolder-name'); // Get a File instance for a file in the folder $fileInstance = $folder->file('file-name.txt'); // Get the files in the folder, as an array of File instances $files = $folder->files; // Get the subfolders in the folder, as an array of Folder instances $subFolders = $folder->folders; // Get a list of all file names in the folder (and optionally filter by a pattern or using a callable) $fileNames = $folder->getFileNames('/IMG_[0-9]{4}\.jpg/'); // OR $fileNames = $folder->getFileNames(fn($name) => str_starts_with($name, 'IMG_')); // OR without any filter $fileNames = $folder->fileNames; // Get a list of all subfolder names in the folder (and optionally filter by a pattern or using a callable) $subFolderNames = $folder->getFolderNames('/[0-9]{4}/'); // OR $subFolderNames = $folder->getFolderNames(fn($name) => is_numeric($name)); // OR without any filter $subFolderNames = $folder->folderNames; // Get a flat list of all files in the folder and its subfolders recursively, as an array of File instances $allFiles = $folder->getAllFiles(filter: '/IMG_[0-9]{4}\.jpg/'); //filter by a pattern or using a callable // OR without any filter $allFiles = $folder->allFiles; // Create the current folder (corresponding to the current instance) if it doesn't exist $folder->create(); // Rename the folder $folder->rename('new-folder-name'); // Move the folder to a new directory $folder->move('/path/to/new/parent/directory', overwrite: true); // Move a list of files (an array of string path names or File instances) to the folder $folder->moveFilesToSelf(['/path/to/file1.txt', '/path/to/file2.txt', $fileInstance]); // Delete the folder and all its contents (recursively) $folder->delete(deep: true); // Check if the folder contains a file with a specific name $containsFile = $folder->hasFile('file-name.txt'); // Check if the folder contains a subfolder with a specific name $containsFolder = $folder->hasSubFolder('subfolder-name'); // Check if the folder has all the files in a list of file names $hasAllFiles = $folder->hasFiles(['file1.txt', 'file2.txt']); // Check if the folder has all the subfolders in a list of folder names $hasAllSubFolders = $folder->hasSubFolders(['subfolder1', 'subfolder2']); // Check if the folder is empty (contains no files and no folders) $isEmpty = $folder->isEmpty(); // Check if the folder is not empty (contains at least one file or folder) $notEmpty = $folder->isNotEmpty(); // Go up the folder hierarchy and find the first folder that has a specific name //e.g. instead of '__DIR__ . '/../../../../parent-folder-name' $parentFolder = Folder::instance(__DIR__)->closest('parent-folder-name');
压缩和解压缩文件和文件夹
File
和Folder
类提供了压缩和解压缩文件和文件夹的方法
use AntonioPrimera\FileSystem\File; use AntonioPrimera\FileSystem\Folder; // Zip a file to a zip archive named the same as the file with the .zip extension $file = File::instance('/path/to/file.txt')->zip(); //creates /path/to/file.txt.zip // Zip a file to a specific zip archive and return the archive File instance $file = File::instance('/path/to/file.txt')->zipTo('/path/to/archive.zip'); // Unzip a zip archive to the same folder as the archive and return the parent Folder instance $folder = File::instance('/path/to/archive.zip')->unzip(); //creates /path/to/archive/ // Unzip a zip archive to a specific folder and return the target Folder instance $folder = File::instance('/path/to/archive.zip')->unzipTo('/path/to/destination/'); // Zip a folder to an archive named the same as the folder with the .zip extension $folder = Folder::instance('/path/to/folder')->zip(); //creates /path/to/folder.zip // Zip a folder to a specific archive and return the archive File instance $file = Folder::instance('/path/to/folder')->zipTo('/specific/path/to/archive.zip'); // Zip a folder, excluding the root folder (only the contents are zipped) $file = Folder::instance('/path/to/folder')->zipTo('/specific/path/to/archive.zip', includeRoot: false); $file = Folder::instance('/path/to/folder')->zip(includeRoot: false);
OS
OS
类提供了用于检测操作系统和处理跨平台路径字符串操作的静态方法
use AntonioPrimera\FileSystem\OS; // Determine the current OS OS::isWindows(); //returns true if the current OS is Windows OS::isLinux(); //returns true if the current OS is Linux OS::isMac(); //returns true if the current OS is macOS OS::isOsx(); //returns true if the current OS is macOS OS::isUnix(); //returns true if the current OS is Unix (Linux or macOS) // Determine if a string path is absolute OS::isAbsolutePath('/path/to/file.txt'); //returns true OS::isAbsolutePath('path/to/file.txt'); //returns false OS::isAbsolutePath('C:\path\to\file.txt'); //returns true // Cleans up paths, normalizes separators and returns correct OS specific paths // All the following calls return '/path/to/file.txt' on Unix and '\path\to\file.txt' on Windows $path = OS::path('/path/to/file.txt'); $path = OS::path('path', 'to', 'file.txt'); $path = OS::path('/path', '/to', '', null, '\\file.txt'); // Normalizes path separators in a string path if no cleanup is needed, returns '/path/to/file.txt' on Unix, '\path\to\file.txt' on Windows $path = OS::normalizePathSeparators('/path/to/file.txt'); // Splits a path string into an array of path parts (same result on Unix and Windows) // All the following calls return ['path', 'to', 'file.txt'] $parts = OS::splitPath('/path/to/file.txt'); $parts = OS::splitPath('\\path\\to\\file.txt'); $parts = OS::splitPath('path/', '\\to\\', 'file.txt'); //works with mixed separators $parts = OS::splitPath('path\\', '\\to\\', 'file.txt'); //works with redundant separators $parts = OS::splitPath('\\path/to', '/', '', null, '\\', 'file.txt'); //works with dirty paths
贡献
欢迎提交拉取请求。对于重大更改,请先提交问题以讨论您想要更改的内容。此外,如果您能改进此文档,请这么做。
许可证
MIT