Skip to content

Commit 29855c1

Browse files
committed
Refactor file operations to Laravel's illuminate/filesystem
1 parent 3adaffb commit 29855c1

14 files changed

+82
-59
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
"require": {
2323
"php": "^8.0",
2424
"illuminate/contracts": "^8.0|^9.0",
25+
"illuminate/filesystem": "^8.0|^9.0",
2526
"livewire/livewire": "^2.10"
2627
},
2728
"require-dev": {

config/log-viewer.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,17 @@
6060

6161
'middleware' => ['web'],
6262

63+
/*
64+
|--------------------------------------------------------------------------
65+
| Filesystem for logs
66+
|--------------------------------------------------------------------------
67+
|
68+
*/
69+
'filesystem' => [
70+
'root' => '',
71+
'disk' => 'log-viewer-local',
72+
],
73+
6374
/*
6475
|--------------------------------------------------------------------------
6576
| Include file patterns

src/Facades/LogViewer.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Opcodes\LogViewer\Facades;
44

5+
use Illuminate\Contracts\Filesystem\Filesystem;
56
use Illuminate\Support\Facades\Facade;
67
use Opcodes\LogViewer\LogFile;
78
use Opcodes\LogViewer\LogFileCollection;
@@ -19,6 +20,7 @@
1920
* @method static void clearFileCache()
2021
* @method static string|null getRouteDomain()
2122
* @method static array getRouteMiddleware()
23+
* @method static Filesystem getFilesystem()
2224
* @method static string getRoutePrefix()
2325
* @method static void auth($callback = null)
2426
* @method static void setMaxLogSize(int $bytes)

src/Http/Livewire/FileList.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ public function deleteFolder(string $folderIdentifier)
9090
{
9191
$folder = LogViewer::getFolder($folderIdentifier);
9292

93+
9394
if ($folder) {
9495
Gate::authorize('deleteLogFolder', $folder);
9596

src/LogFile.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66
use Illuminate\Support\Str;
77
use Opcodes\LogViewer\Events\LogFileDeleted;
88
use Opcodes\LogViewer\Exceptions\InvalidRegularExpression;
9+
use Opcodes\LogViewer\Facades\LogViewer;
910
use Opcodes\LogViewer\Utils\Utils;
1011
use Symfony\Component\HttpFoundation\BinaryFileResponse;
12+
use Symfony\Component\HttpFoundation\StreamedResponse;
1113

1214
class LogFile
1315
{
@@ -49,9 +51,7 @@ public function logs(): LogReader
4951

5052
public function size(): int
5153
{
52-
clearstatcache();
53-
54-
return filesize($this->path);
54+
return LogViewer::getFilesystem()->size($this->path);
5555
}
5656

5757
public function sizeInMB(): float
@@ -74,9 +74,9 @@ public function downloadUrl(): string
7474
return route('blv.download-file', $this->identifier);
7575
}
7676

77-
public function download(): BinaryFileResponse
77+
public function download(): StreamedResponse
7878
{
79-
return response()->download($this->path);
79+
return LogViewer::getFilesystem()->download($this->path);
8080
}
8181

8282
public function addRelatedIndex(LogIndex $logIndex): void
@@ -104,13 +104,13 @@ public function getLastScannedFilePositionForQuery(?string $query = ''): ?int
104104
public function earliestTimestamp(): int
105105
{
106106
return $this->getMetadata('earliest_timestamp')
107-
?? (is_file($this->path) ? filemtime($this->path) : 0);
107+
?? LogViewer::getFilesystem()->lastModified($this->path);
108108
}
109109

110110
public function latestTimestamp(): int
111111
{
112112
return $this->getMetadata('latest_timestamp')
113-
?? (is_file($this->path) ? filemtime($this->path) : 0);
113+
?? LogViewer::getFilesystem()->lastModified($this->path);
114114
}
115115

116116
public function scan(int $maxBytesToScan = null, bool $force = false): void
@@ -134,7 +134,7 @@ public function search(string $query = null): LogReader
134134
public function delete(): void
135135
{
136136
$this->clearCache();
137-
unlink($this->path);
137+
LogViewer::getFilesystem()->delete($this->path);
138138
LogFileDeleted::dispatch($this);
139139
}
140140
}

src/LogFolder.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ public function download(): BinaryFileResponse
123123
/** @var LogFile $file */
124124
foreach ($this->files() as $file) {
125125
if (Gate::check('downloadLogFile', $file)) {
126-
$zip->addFile($file->path, $file->name);
126+
$zip->addFromString(name: $file->name, content: LogViewer::getFilesystem()->get($file->path));
127127
}
128128
}
129129

src/LogReader.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ public function open(): self
163163
return $this;
164164
}
165165

166-
$this->fileHandle = fopen($this->file->path, 'r');
166+
$this->fileHandle = LogViewer::getFilesystem()->readStream($this->file->path);
167167

168168
if ($this->fileHandle === false) {
169169
throw new \Exception('Could not open "'.$this->file->path.'" for reading.');

src/LogViewerService.php

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@
44

55
use Composer\InstalledVersions;
66
use Illuminate\Auth\Access\AuthorizationException;
7+
use Illuminate\Contracts\Filesystem\Filesystem;
78
use Illuminate\Support\Collection;
89
use Illuminate\Support\Facades\Gate;
10+
use Illuminate\Support\Facades\Storage;
911
use Illuminate\Support\Str;
12+
use Symfony\Component\Finder\Glob;
1013

1114
class LogViewerService
1215
{
@@ -20,30 +23,20 @@ class LogViewerService
2023

2124
protected function getFilePaths(): array
2225
{
23-
// Because we'll use the base path as a parameter for `glob`, we should escape any
24-
// glob's special characters and treat those as actual characters of the path.
25-
// We can assume this, because it's the actual path of the Laravel app, not a user-defined
26-
// search pattern.
27-
if (PHP_OS_FAMILY === 'Windows') {
28-
$baseDir = str_replace(
29-
['[', ']'],
30-
['{LEFTBRACKET}', '{RIGHTBRACKET}'],
31-
str_replace('\\', '/', $this->basePathForLogs())
32-
);
33-
$baseDir = str_replace(
34-
['{LEFTBRACKET}', '{RIGHTBRACKET}'],
35-
['[[]', '[]]'],
36-
$baseDir
37-
);
38-
} else {
39-
$baseDir = str_replace(
40-
['*', '?', '\\', '[', ']'],
41-
['\*', '\?', '\\\\', '\[', '\]'],
42-
$this->basePathForLogs()
43-
);
44-
}
4526
$files = [];
4627

28+
// Because we use the Glob::toRegex function we have to escape the brackets
29+
$baseDir = str_replace(
30+
['[', ']'],
31+
['{LEFTBRACKET}', '{RIGHTBRACKET}'],
32+
str_replace('\\', '/', $this->basePathForLogs())
33+
);
34+
$baseDir = str_replace(
35+
['{LEFTBRACKET}', '{RIGHTBRACKET}'],
36+
['[[]', '[]]'],
37+
$baseDir
38+
);
39+
4740
foreach (config('log-viewer.include_files', []) as $pattern) {
4841
if (! str_starts_with($pattern, DIRECTORY_SEPARATOR)) {
4942
$pattern = $baseDir.$pattern;
@@ -60,23 +53,26 @@ protected function getFilePaths(): array
6053
$files = array_diff($files, $this->getFilePathsMatchingPattern($pattern));
6154
}
6255

63-
$files = array_map('realpath', $files);
64-
65-
$files = array_filter($files, 'is_file');
66-
6756
return array_values(array_reverse($files));
6857
}
6958

7059
protected function getFilePathsMatchingPattern($pattern)
7160
{
72-
// The GLOB_BRACE flag is not available on some non GNU systems, like Solaris or Alpine Linux.
61+
$files = [];
7362

74-
return glob($pattern);
63+
foreach($this->getFilesystem()->allFiles($this->basePathForLogs()) as $file)
64+
{
65+
if (preg_match(pattern: Glob::toRegex(glob: $pattern), subject: $file)) {
66+
$files[] = $file;
67+
}
68+
}
69+
70+
return $files;
7571
}
7672

7773
public function basePathForLogs(): string
7874
{
79-
return Str::finish(realpath(storage_path('logs')), DIRECTORY_SEPARATOR);
75+
return config('log-viewer.filesystem.root');
8076
}
8177

8278
/**
@@ -154,6 +150,11 @@ public function getRouteMiddleware(): array
154150
return config('log-viewer.middleware', []) ?: ['web'];
155151
}
156152

153+
public function getFilesystem(): Filesystem
154+
{
155+
return Storage::disk(config('log-viewer.filesystem.disk'));
156+
}
157+
157158
public function auth($callback = null): void
158159
{
159160
if (is_null($callback) && isset($this->authCallback)) {

src/LogViewerServiceProvider.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ public function register()
2121
{
2222
$this->mergeConfigFrom($this->basePath("/config/{$this->name}.php"), $this->name);
2323

24+
$this->app['config']['filesystems.disks.log-viewer-local'] = [
25+
'driver' => 'local',
26+
'root' => storage_path('logs'),
27+
];
28+
2429
$this->app->bind('log-viewer', LogViewerService::class);
2530
$this->app->bind('log-viewer-cache', function () {
2631
return Cache::driver(config('log-viewer.cache_driver'));

tests/Pest.php

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
use Carbon\CarbonInterface;
44
use Illuminate\Support\Facades\File;
5+
use Opcodes\LogViewer\Facades\LogViewer;
56
use Opcodes\LogViewer\LogFile;
67
use Opcodes\LogViewer\LogIndex;
78
use Opcodes\LogViewer\Tests\TestCase;
@@ -34,18 +35,18 @@ function generateLogFile(string $fileName = null, string $content = null, bool $
3435
$fileName = \Illuminate\Support\Str::random().'.log';
3536
}
3637

37-
$path = storage_path('logs/'.$fileName);
38+
$storage = LogViewer::getFilesystem();
3839

39-
if (File::exists($path)) {
40-
File::delete($path);
40+
if ($storage->exists($fileName)) {
41+
$storage->delete($fileName);
4142
}
4243

43-
File::put($path, $content ?? ($randomContent ? dummyLogData() : ''));
44+
$storage->put($fileName, $content ?? ($randomContent ? dummyLogData() : ''));
4445

4546
// we perform a regular PHP assertion, so it doesn't count towards the unit test assertion count.
46-
assert(file_exists($path));
47+
assert($storage->exists($fileName));
4748

48-
return new LogFile($path);
49+
return new LogFile($fileName);
4950
}
5051

5152
function dummyLogData(int $lines = null): string

0 commit comments

Comments
 (0)