-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathwiseFacade.php
More file actions
395 lines (355 loc) · 12 KB
/
PathwiseFacade.php
File metadata and controls
395 lines (355 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<?php
declare(strict_types=1);
namespace Infocyph\Pathwise;
use Infocyph\Pathwise\DirectoryManager\DirectoryOperations;
use Infocyph\Pathwise\FileManager\FileCompression;
use Infocyph\Pathwise\FileManager\FileOperations;
use Infocyph\Pathwise\FileManager\SafeFileReader;
use Infocyph\Pathwise\FileManager\SafeFileWriter;
use Infocyph\Pathwise\Indexing\ChecksumIndexer;
use Infocyph\Pathwise\Observability\AuditTrail;
use Infocyph\Pathwise\Queue\FileJobQueue;
use Infocyph\Pathwise\Retention\RetentionManager;
use Infocyph\Pathwise\Security\PolicyEngine;
use Infocyph\Pathwise\Storage\StorageFactory;
use Infocyph\Pathwise\StreamHandler\DownloadProcessor;
use Infocyph\Pathwise\StreamHandler\UploadProcessor;
use Infocyph\Pathwise\Utils\FileWatcher;
use Infocyph\Pathwise\Utils\FlysystemHelper;
use Infocyph\Pathwise\Utils\MetadataHelper;
use Infocyph\Pathwise\Utils\PathHelper;
use League\Flysystem\FilesystemOperator;
/**
* @phpstan-type SnapshotEntry array{mtime: int, size: int}
* @phpstan-type SnapshotMap array<string, SnapshotEntry>
* @phpstan-type DiffReport array{created: list<string>, modified: list<string>, deleted: list<string>}
*/
final class PathwiseFacade
{
/**
* Constructor to initialize the file path.
*
* @param string $path The path to the file or directory.
*/
public function __construct(private string $path)
{
$this->path = PathHelper::normalize($path);
}
/**
* Create a new instance at the given path.
*
* @param string $path The path to the file or directory.
* @return self A new facade instance.
*/
public static function at(string $path): self
{
return new self($path);
}
/**
* Create an audit trail logger.
*
* @param string $logFilePath The path to the log file.
* @return AuditTrail The audit trail instance.
*/
public static function audit(string $logFilePath): AuditTrail
{
return new AuditTrail($logFilePath);
}
/**
* Create a Flysystem filesystem from configuration.
*
* @param array<string, mixed> $config The filesystem configuration.
* @return FilesystemOperator The created filesystem.
*/
public static function createFilesystem(array $config): FilesystemOperator
{
return StorageFactory::createFilesystem($config);
}
/**
* Deduplicate files in a directory using hard links.
*
* @param string $directory The directory to deduplicate.
* @param string $algorithm The hash algorithm to use. Defaults to 'sha256'.
* @return array{linked: list<string>, skipped: list<string>} Array with linked and skipped file paths.
*/
public static function deduplicate(string $directory, string $algorithm = 'sha256'): array
{
$result = ChecksumIndexer::deduplicateWithHardLinks($directory, $algorithm);
return [
'linked' => self::normalizeStringList($result['linked']),
'skipped' => self::normalizeStringList($result['skipped']),
];
}
/**
* Compare two snapshots and return the differences.
*
* @param SnapshotMap $previousSnapshot The previous snapshot data.
* @param SnapshotMap $currentSnapshot The current snapshot data.
* @return DiffReport The diff report.
*/
public static function diffSnapshots(array $previousSnapshot, array $currentSnapshot): array
{
return FileWatcher::diff($previousSnapshot, $currentSnapshot);
}
/**
* Create a download processor for secure file downloads.
*
* @return DownloadProcessor The download processor instance.
*/
public static function download(): DownloadProcessor
{
return new DownloadProcessor();
}
/**
* Find duplicate files in a directory.
*
* @param string $directory The directory to search for duplicates.
* @param string $algorithm The hash algorithm to use. Defaults to 'sha256'.
* @return array<string, array<int, string>> Array mapping checksum to duplicate file paths.
*/
public static function duplicates(string $directory, string $algorithm = 'sha256'): array
{
return ChecksumIndexer::findDuplicates($directory, $algorithm);
}
/**
* Alias for at() - create a new instance at the given path.
*
* @param string $path The path to the file or directory.
* @return self A new facade instance.
*/
public static function from(string $path): self
{
return self::at($path);
}
/**
* Build a checksum index for all files in a directory.
*
* @param string $directory The directory to index.
* @param string $algorithm The hash algorithm to use. Defaults to 'sha256'.
* @return array<string, array<int, string>> Array mapping checksum to file paths.
*/
public static function index(string $directory, string $algorithm = 'sha256'): array
{
return ChecksumIndexer::buildIndex($directory, $algorithm);
}
/**
* Create and mount a filesystem under a name.
*
* @param string $name The mount name.
* @param array<string, mixed> $config The filesystem configuration.
* @return FilesystemOperator The created filesystem.
*/
public static function mountStorage(string $name, array $config): FilesystemOperator
{
return StorageFactory::mount($name, $config);
}
/**
* Mount multiple filesystems at once.
*
* @param array<string, array<string, mixed>> $mounts Array of mount name => config pairs.
*/
public static function mountStorages(array $mounts): void
{
StorageFactory::mountMany($mounts);
}
/**
* Create a policy engine for access control.
*
* @return PolicyEngine The policy engine instance.
*/
public static function policy(): PolicyEngine
{
return new PolicyEngine();
}
/**
* Create a file-based job queue.
*
* @param string $queueFilePath The path to the queue file.
* @return FileJobQueue The job queue instance.
*/
public static function queue(string $queueFilePath): FileJobQueue
{
return new FileJobQueue($queueFilePath);
}
/**
* Apply retention rules to a directory.
*
* @param string $directory The directory to apply retention rules to.
* @param int|null $keepLast Number of most recent files to keep (null for unlimited).
* @param int|null $maxAgeDays Maximum age of files in days (null for unlimited).
* @param string $sortBy Field to sort by ('mtime' or 'ctime').
* @return array{deleted: list<string>, kept: list<string>} Array with deleted and kept file paths.
*/
public static function retain(
string $directory,
?int $keepLast = null,
?int $maxAgeDays = null,
string $sortBy = 'mtime',
): array {
$result = RetentionManager::apply($directory, $keepLast, $maxAgeDays, $sortBy);
return [
'deleted' => self::normalizeStringList($result['deleted']),
'kept' => self::normalizeStringList($result['kept']),
];
}
/**
* Build a snapshot map for a file or directory.
*
* @param string $path The path to snapshot.
* @param bool $recursive Whether to include subdirectories recursively.
* @return array<string, array{mtime: int, size: int}> The snapshot map.
*/
public static function snapshot(string $path, bool $recursive = true): array
{
return FileWatcher::snapshot($path, $recursive);
}
/**
* Create an upload processor for secure file uploads.
*
* @return UploadProcessor The upload processor instance.
*/
public static function upload(): UploadProcessor
{
return new UploadProcessor();
}
/**
* Poll for file-system changes and invoke callback on each non-empty diff.
*
* @param string $path The path to watch.
* @param callable $onChange Callback invoked when changes detected.
* @param int $durationSeconds How long to watch in seconds. Defaults to 5.
* @param int $intervalMilliseconds Polling interval in milliseconds. Defaults to 500.
* @param bool $recursive Whether to watch subdirectories. Defaults to true.
* @return array<string, array{mtime: int, size: int}> Final snapshot.
*/
public static function watch(
string $path,
callable $onChange,
int $durationSeconds = 5,
int $intervalMilliseconds = 500,
bool $recursive = true,
): array {
return FileWatcher::watch($path, $onChange, $durationSeconds, $intervalMilliseconds, $recursive);
}
/**
* Get a file compression handler for this path.
*
* @param bool $create If true, create a new ZIP archive if it doesn't exist.
* @return FileCompression The file compression instance.
*/
public function compression(bool $create = false): FileCompression
{
return new FileCompression($this->path, $create);
}
/**
* Get a directory operations handler for this path.
*
* @return DirectoryOperations The directory operations instance.
*/
public function directory(): DirectoryOperations
{
return new DirectoryOperations($this->path);
}
/**
* Check if the file or directory exists.
*
* @return bool True if the path exists, false otherwise.
*/
public function exists(): bool
{
return FlysystemHelper::has($this->path);
}
/**
* Get a file operations handler for this path.
*
* @return FileOperations The file operations instance.
*/
public function file(): FileOperations
{
return new FileOperations($this->path);
}
/**
* Get metadata for this file or directory.
*
* @param bool $humanReadableSize If true, return size in human-readable format.
* @return array<string, mixed>|null The metadata array, or null if the path doesn't exist.
*/
public function metadata(bool $humanReadableSize = false): ?array
{
return self::normalizeStringMap(MetadataHelper::getAllMetadata($this->path, $humanReadableSize));
}
/**
* Get the MIME type of this file.
*
* @return string|null The MIME type, or null if not a file.
*/
public function mimeType(): ?string
{
return MetadataHelper::getMimeType($this->path);
}
/**
* Get the normalized path.
*
* @return string The normalized path.
*/
public function path(): string
{
return $this->path;
}
/**
* Get a safe file reader for this path.
*
* @param string $mode The file mode to open with. Defaults to 'r'.
* @param bool $exclusiveLock If true, acquire an exclusive lock.
* @return SafeFileReader The file reader instance.
*/
public function reader(string $mode = 'r', bool $exclusiveLock = false): SafeFileReader
{
return new SafeFileReader($this->path, $mode, $exclusiveLock);
}
/**
* Get a safe file writer for this path.
*
* @param bool $append If true, append to existing file. Defaults to false.
* @return SafeFileWriter The file writer instance.
*/
public function writer(bool $append = false): SafeFileWriter
{
return new SafeFileWriter($this->path, $append);
}
/**
* @return list<string>
*/
private static function normalizeStringList(mixed $values): array
{
if (!is_array($values)) {
return [];
}
$result = [];
foreach ($values as $value) {
if (!is_string($value)) {
continue;
}
$result[] = $value;
}
return $result;
}
/**
* @param array<mixed, mixed>|null $values
* @return array<string, mixed>|null
*/
private static function normalizeStringMap(?array $values): ?array
{
if ($values === null) {
return null;
}
$result = [];
foreach ($values as $key => $value) {
if (!is_string($key)) {
continue;
}
$result[$key] = $value;
}
return $result;
}
}