Skip to content

infocyph/Pathwise

Repository files navigation

Pathwise: File Management Made Simple

Security & Standards Documentation Packagist Downloads License: MIT Packagist Version Packagist PHP Version GitHub Code Size

Pathwise is a robust PHP library designed as streamlined file and directory management. It combines storage operations with higher-level workflows like safe reading/writing, metadata extraction, compression, upload pipelines, policy enforcement and observability.

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Installation
  4. Features Overview
  5. Quality Gates
  6. FileManager
  7. DirectoryManager
  8. Utils
  9. Storage Adapter Setup
  10. Handy Functions
  1. Support
  2. License

Prerequisites

  • Language: PHP 8.4/+

Installation

Pathwise is available via Composer:

composer require infocyph/pathwise

Requirements:

  • PHP 8.4 or higher
  • ext-fileinfo
  • Optional Extensions:
    • ext-zip: Required for compression features.
    • ext-pcntl: Required for long-running watch loops.
    • ext-posix: Required for permission handling.
    • ext-xmlreader and ext-simplexml: Required for XML parsing.

Features Overview

  • Filesystem operations across core modules.
  • Mount support with scheme paths (name://path) and default filesystem support for relative paths.
  • Config-driven storage bootstrap via StorageFactory for local/custom/adapter-based filesystems.
  • Unified entry facade via Infocyph\Pathwise\PathwiseFacade for file/dir/processors/storage/tooling.
  • Advanced file APIs: checksum verification, visibility controls, URL passthrough (publicUrl, temporaryUrl).
  • Directory automation: sync with diff report, recursive copy/move/delete, mounted-path ZIP/unzip bridging.
  • Upload/download pipelines: chunked/resumable uploads, validation profiles (image/video/document), extension allow/deny controls, strict MIME/signature checks, upload-id safety validation, malware-scan hook, secure download metadata + range handling.
  • Compression workflows: include/exclude glob patterns, ignore files, progress callbacks, hooks, optional native acceleration.
  • Operational tooling: AuditTrail, FileJobQueue, FileWatcher, RetentionManager and policy engine support.

Storage Adapter Setup

Pathwise supports any Flysystem adapter. You can mount storages through StorageFactory and use them with all modules (UploadProcessor, DownloadProcessor, FileOperations, etc.).

StorageFactory supports:

  • ['driver' => 'local', 'root' => '/path']
  • ['driver' => 'aws-s3', 'adapter' => $adapter]
  • ['driver' => 'aws-s3', 'constructor' => [...]]
  • ['filesystem' => $filesystemOperator]
  • custom drivers via StorageFactory::registerDriver()

Official adapter driver keys covered:

  • local, ftp, inmemory (in-memory)
  • read-only, path-prefixing
  • aws-s3 (s3), async-aws-s3
  • azure-blob-storage, google-cloud-storage, mongodb-gridfs
  • sftp-v2, sftp-v3, webdav, ziparchive

Local Driver

use Infocyph\Pathwise\Storage\StorageFactory;
use Infocyph\Pathwise\Utils\FlysystemHelper;

StorageFactory::mount('assets', [
    'driver' => 'local',
    'root' => '/srv/storage/assets',
]);

FlysystemHelper::write('assets://reports/a.txt', 'hello');

Any Adapter (Example: S3)

use Aws\S3\S3Client;
use Infocyph\Pathwise\Storage\StorageFactory;
use League\Flysystem\AwsS3V3\AwsS3V3Adapter;

$client = new S3Client([
    'version' => 'latest',
    'region' => 'us-east-1',
    'credentials' => [
        'key' => getenv('AWS_ACCESS_KEY_ID'),
        'secret' => getenv('AWS_SECRET_ACCESS_KEY'),
    ],
]);

$adapter = new AwsS3V3Adapter($client, 'my-bucket', 'app-prefix');

StorageFactory::mount('s3', ['adapter' => $adapter]);
// Use s3://... paths in processors and managers.

Custom Driver Registration

use Infocyph\Pathwise\Storage\StorageFactory;
use League\Flysystem\Filesystem;
use League\Flysystem\Local\LocalFilesystemAdapter;

StorageFactory::registerDriver('tenant-local', function (array $config): Filesystem {
    $tenant = (string) ($config['tenant'] ?? 'default');
    return new Filesystem(new LocalFilesystemAdapter('/srv/tenants/' . $tenant));
});

StorageFactory::mount('tenant', [
    'driver' => 'tenant-local',
    'tenant' => 'acme',
]);

Unified Pathwise Facade

Use a single entry point when you want fewer direct class imports.

use Infocyph\Pathwise\PathwiseFacade;

$entry = PathwiseFacade::at('/tmp/example.txt');
$entry->file()->create('hello')->append("\nworld");

$upload = PathwiseFacade::upload();
$download = PathwiseFacade::download();

PathwiseFacade::mountStorage('assets', ['driver' => 'local', 'root' => '/srv/assets']);

FileManager

The FileManager module provides classes for handling files, including reading, writing, compressing and general file operations.

SafeFileReader

A memory-safe file reader supporting various reading modes (line-by-line, binary chunks, JSON, CSV, XML, etc.) and iterator interfaces.

Key Features

  • Supports multiple reading modes.
  • Provides locking to prevent concurrent access issues.
  • Implements Countable, Iterator and SeekableIterator.

Usage Example

use Infocyph\Pathwise\FileManager\SafeFileReader;

$reader = new SafeFileReader('/path/to/file.txt');

// Line-by-line iteration
foreach ($reader->line() as $line) {
    echo $line;
}

// JSON decoding with error handling
foreach ($reader->json() as $data) {
    print_r($data);
}

SafeFileWriter

A memory-safe file writer with support for various writing modes, including CSV, JSON, binary and more.

Key Features

  • Supports multiple writing modes.
  • Ensures file locking and robust error handling.
  • Tracks write operations and supports flush and truncate methods.

Usage Example

use Infocyph\Pathwise\FileManager\SafeFileWriter;

$writer = new SafeFileWriter('/path/to/file.txt');

// Writing lines
$writer->line('Hello, World!');

// Writing JSON data
$writer->json(['key' => 'value']);

FileOperations

General-purpose file handling class for creating, deleting, copying, renaming and manipulating files.

Key Features

  • File creation and deletion.
  • Append and update content.
  • Rename, copy and metadata retrieval.

Usage Example

use Infocyph\Pathwise\FileManager\FileOperations;

$fileOps = new FileOperations('/path/to/file.txt');

// Check existence
if ($fileOps->exists()) {
    echo 'File exists';
}

// Read content
echo $fileOps->read();

FileCompression

Provides utilities for compressing and decompressing files using the ZIP format with optional password protection and encryption.

Key Features

  • Compress files/directories.
  • Decompress ZIP archives.
  • Support for AES encryption and password-protected ZIPs.

Usage Example

use Infocyph\Pathwise\FileManager\FileCompression;

$compression = new FileCompression('/path/to/archive.zip');

// Compress a directory
$compression->compress('/path/to/directory');

// Decompress
$compression->decompress('/path/to/extract/');

DirectoryManager

The DirectoryManager module offers tools for handling directory creation, deletion and traversal.

DirectoryOperations

Provides comprehensive tools for managing directories, including creation, deletion, copying and listing contents.

Key Features

  • Create, delete and copy directories.
  • Retrieve directory size, depth and contents.
  • Supports recursive operations and filtering.

Usage Example

use Infocyph\Pathwise\DirectoryManager\DirectoryOperations;

$dirOps = new DirectoryOperations('/path/to/directory');

// Create a directory
$dirOps->create();

// List contents
$contents = $dirOps->listContents(detailed: true);
print_r($contents);

Utils

Utility classes for managing paths, permissions and metadata.

PathHelper

Provides utilities for working with file paths, including joining, normalizing and converting between relative and absolute paths.

Key Features

  • Path joining and normalization.
  • Convert between relative and absolute paths.
  • Retrieve and manipulate file extensions.

Usage Example

use Infocyph\Pathwise\Utils\PathHelper;

$absolutePath = PathHelper::toAbsolutePath('relative/path');
echo $absolutePath;

$joinedPath = PathHelper::join('/var', 'www', 'html');
echo $joinedPath;

PermissionsHelper

Handles file and directory permissions, ownership and access control.

Key Features

  • Retrieve and set permissions.
  • Check read, write and execute access.
  • Retrieve and set ownership details.

Usage Example

use Infocyph\Pathwise\Utils\PermissionsHelper;

// Get human-readable permissions
echo PermissionsHelper::getHumanReadablePermissions('/path/to/file');

// Check if writable
if (PermissionsHelper::canWrite('/path/to/file')) {
    echo 'File is writable';
}

MetadataHelper

Extracts metadata for files and directories, such as size, timestamps, MIME type and more.

Key Features

  • Retrieve file size and type.
  • Compute checksums and timestamps.
  • Get ownership and visibility details.

Usage Example

use Infocyph\Pathwise\Utils\MetadataHelper;

// Get file size
$size = MetadataHelper::getFileSize('/path/to/file');
echo "File size: $size bytes";

// Retrieve metadata
$metadata = MetadataHelper::getAllMetadata('/path/to/file');
print_r($metadata);

Handy Functions

File and Directory Utilities

Pathwise provides standalone utility functions to simplify common file and directory operations.

1. Get Human-Readable File Size

Formats a file size in bytes into a human-readable format (e.g., 1.23 KB, 4.56 GB).

Usage Example:

$size = getHumanReadableFileSize(123456789);
echo $size; // Output: "117.74 MB"

2. Check if a Directory is Empty

Checks whether the given directory contains any files or subdirectories.

Usage Example:

$isEmpty = isDirectoryEmpty('/path/to/directory');
echo $isEmpty ? 'Empty' : 'Not Empty';

3. Delete a Directory Recursively

Deletes a directory and all its contents (files and subdirectories).

Usage Example:

$success = deleteDirectory('/path/to/directory');
echo $success ? 'Deleted successfully' : 'Failed to delete';

4. Get Directory Size

Calculates the total size of a directory, including all its files and subdirectories.

Usage Example:

$size = getDirectorySize('/path/to/directory');
echo "Directory size: " . getHumanReadableFileSize($size);

5. Create a Directory

Creates a directory (including parent directories) with specified permissions.

Usage Example:

$success = createDirectory('/path/to/new/directory');
echo $success ? 'Directory created' : 'Failed to create directory';

6. List Files in a Directory

Lists all files in a directory, excluding subdirectories.

Usage Example:

$files = listFiles('/path/to/directory');
print_r($files);

7. Copy a Directory Recursively

Copies a directory and all its contents to a new location.

Usage Example:

$success = copyDirectory('/source/directory', '/destination/directory');
echo $success ? 'Copied successfully' : 'Failed to copy';

Support

Having trouble? Create an issue!

License

Pathwise is licensed under the MIT License.

About

File Management Made Simple

Resources

License

Stars

Watchers

Forks

Contributors

Languages