Skip to content

Commit 5721e8a

Browse files
committed
Add caching support to Filesystem getRequire
1 parent 79c9874 commit 5721e8a

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/Illuminate/Filesystem/Filesystem.php

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

33
namespace Illuminate\Filesystem;
44

5+
use Closure;
56
use ErrorException;
67
use FilesystemIterator;
78
use Illuminate\Contracts\Filesystem\FileNotFoundException;
@@ -18,6 +19,13 @@ class Filesystem
1819
{
1920
use Conditionable, Macroable;
2021

22+
/**
23+
* Array of cached require values.
24+
*
25+
* @var array
26+
*/
27+
protected array $cachedRequirements = [];
28+
2129
/**
2230
* Determine if a file or directory exists.
2331
*
@@ -107,21 +115,32 @@ public function sharedGet($path)
107115
*
108116
* @param string $path
109117
* @param array $data
118+
* @param bool|Closure $cache
110119
* @return mixed
111120
*
112121
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
113122
*/
114-
public function getRequire($path, array $data = [])
123+
public function getRequire($path, array $data = [], bool|Closure $cache = false)
115124
{
125+
if ($cache && isset($this->cachedRequirements[$path])) {
126+
return $this->cachedRequirements[$path];
127+
}
128+
116129
if ($this->isFile($path)) {
117130
$__path = $path;
118131
$__data = $data;
119132

120-
return (static function () use ($__path, $__data) {
133+
$require = (static function () use ($__path, $__data) {
121134
extract($__data, EXTR_SKIP);
122135

123136
return require $__path;
124137
})();
138+
139+
if (is_callable($cache) ? call_user_func($cache, $require) : $cache) {
140+
$this->cachedRequirements[$path] = $require;
141+
}
142+
143+
return $require;
125144
}
126145

127146
throw new FileNotFoundException("File does not exist at path {$path}.");

tests/Filesystem/FilesystemTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,17 @@ public function testGetRequireThrowsExceptionNonExistingFile()
344344
$files->getRequire(self::$tempDir.'/file.php');
345345
}
346346

347+
public function testGetRequireCachedReturnsProperly()
348+
{
349+
file_put_contents(self::$tempDir.'/file.php', '<?php return "Howdy?"; ?>');
350+
$files = new Filesystem;
351+
$files->getRequire(self::$tempDir.'/file.php', cache: true);
352+
file_put_contents(self::$tempDir.'/file.php', '<?php return "Hey!"; ?>');
353+
354+
$this->assertSame('Hey!', $files->getRequire(self::$tempDir.'/file.php'));
355+
$this->assertSame('Howdy?', $files->getRequire(self::$tempDir.'/file.php', cache: true));
356+
}
357+
347358
public function testJsonReturnsDecodedJsonData()
348359
{
349360
file_put_contents(self::$tempDir.'/file.json', '{"foo": "bar"}');

0 commit comments

Comments
 (0)