Skip to content

[11.x] Add in-memory cache support to Blade #51141

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/Illuminate/Filesystem/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Filesystem;

use Closure;
use ErrorException;
use FilesystemIterator;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
Expand All @@ -18,6 +19,13 @@ class Filesystem
{
use Conditionable, Macroable;

/**
* Array of cached require values.
*
* @var array
*/
protected array $cachedRequirements = [];

/**
* Determine if a file or directory exists.
*
Expand Down Expand Up @@ -107,21 +115,32 @@ public function sharedGet($path)
*
* @param string $path
* @param array $data
* @param bool|Closure $cache
* @return mixed
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function getRequire($path, array $data = [])
public function getRequire($path, array $data = [], bool|Closure $cache = false)
{
if ($cache && isset($this->cachedRequirements[$path])) {
return $this->cachedRequirements[$path];
}

if ($this->isFile($path)) {
$__path = $path;
$__data = $data;

return (static function () use ($__path, $__data) {
$require = (static function () use ($__path, $__data) {
extract($__data, EXTR_SKIP);

return require $__path;
})();

if (is_callable($cache) ? call_user_func($cache, $require) : $cache) {
$this->cachedRequirements[$path] = $require;
}

return $require;
}

throw new FileNotFoundException("File does not exist at path {$path}.");
Expand Down
21 changes: 20 additions & 1 deletion src/Illuminate/View/Compilers/BladeCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,9 @@ public function compile($path = null)
}

if (! is_null($this->cachePath)) {
$contents = $this->compileString($this->files->get($this->getPath()));
$contents = $this->wrapInCallback(
$this->compileString($this->files->get($this->getPath()))
);

if (! empty($this->getPath())) {
$contents = $this->appendFilePath($contents);
Expand All @@ -195,6 +197,23 @@ public function compile($path = null)
}
}

/**
* Wrap the compiled string by a function.
*
* @param string $contents
* @return string
*/
protected function wrapInCallback($contents)
{
$tokens = $this->getOpenAndClosingPhpTokens($contents);

if ($tokens->isNotEmpty() && $tokens->last() !== T_CLOSE_TAG) {
$contents .= ' ?>';
}

return "<?php return function (\$__laravel_data) { extract(\$__laravel_data, EXTR_SKIP); ?>$contents<?php } ?>";
}

/**
* Append the file path to the compiled string.
*
Expand Down
6 changes: 5 additions & 1 deletion src/Illuminate/View/Engines/PhpEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ protected function evaluatePath($path, $data)
// flush out any stray output that might get out before an error occurs or
// an exception is thrown. This prevents any partial views from leaking.
try {
$this->files->getRequire($path, $data);
$requiredView = $this->files->getRequire($path, $data, fn ($require) => is_callable($require));

if (is_callable($requiredView)) {
$requiredView($data);
}
} catch (Throwable $e) {
$this->handleViewException($e, $obLevel);
}
Expand Down
11 changes: 11 additions & 0 deletions tests/Filesystem/FilesystemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,17 @@ public function testGetRequireThrowsExceptionNonExistingFile()
$files->getRequire(self::$tempDir.'/file.php');
}

public function testGetRequireCachedReturnsProperly()
{
file_put_contents(self::$tempDir.'/file.php', '<?php return "Howdy?"; ?>');
$files = new Filesystem;
$files->getRequire(self::$tempDir.'/file.php', cache: true);
file_put_contents(self::$tempDir.'/file.php', '<?php return "Hey!"; ?>');

$this->assertSame('Hey!', $files->getRequire(self::$tempDir.'/file.php'));
$this->assertSame('Howdy?', $files->getRequire(self::$tempDir.'/file.php', cache: true));
}

public function testJsonReturnsDecodedJsonData()
{
file_put_contents(self::$tempDir.'/file.json', '{"foo": "bar"}');
Expand Down
30 changes: 15 additions & 15 deletions tests/View/ViewBladeCompilerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function testCompileCompilesFileAndReturnsContents()
$compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
$files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');
$files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true);
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>');
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', '<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello World<?php } ?><?php /**PATH foo ENDPATH**/ ?>');
$compiler->compile('foo');
}

Expand All @@ -76,7 +76,7 @@ public function testCompileCompilesFileAndReturnsContentsCreatingDirectory()
$files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');
$files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(false);
$files->shouldReceive('makeDirectory')->once()->with(__DIR__, 0777, true, true);
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>');
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', '<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello World<?php } ?><?php /**PATH foo ENDPATH**/ ?>');
$compiler->compile('foo');
}

Expand All @@ -85,7 +85,7 @@ public function testCompileCompilesAndGetThePath()
$compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
$files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');
$files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true);
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>');
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', '<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello World<?php } ?><?php /**PATH foo ENDPATH**/ ?>');
$compiler->compile('foo');
$this->assertSame('foo', $compiler->getPath());
}
Expand All @@ -102,7 +102,7 @@ public function testCompileWithPathSetBefore()
$compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
$files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');
$files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true);
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>');
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', '<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello World<?php } ?><?php /**PATH foo ENDPATH**/ ?>');
// set path before compilation
$compiler->setPath('foo');
// trigger compilation with $path
Expand Down Expand Up @@ -145,39 +145,39 @@ public static function appendViewPathDataProvider()
return [
'No PHP blocks' => [
'Hello World',
'Hello World<?php /**PATH foo ENDPATH**/ ?>',
'<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello World<?php } ?><?php /**PATH foo ENDPATH**/ ?>',
],
'Single PHP block without closing ?>' => [
'<?php echo $path',
'<?php echo $path ?><?php /**PATH foo ENDPATH**/ ?>',
'<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?><?php echo $path ?><?php } ?><?php /**PATH foo ENDPATH**/ ?>',
],
'Ending PHP block.' => [
'Hello world<?php echo $path ?>',
'Hello world<?php echo $path ?><?php /**PATH foo ENDPATH**/ ?>',
'<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello world<?php echo $path ?><?php } ?><?php /**PATH foo ENDPATH**/ ?>',
],
'Ending PHP block without closing ?>' => [
'Hello world<?php echo $path',
'Hello world<?php echo $path ?><?php /**PATH foo ENDPATH**/ ?>',
'<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello world<?php echo $path ?><?php } ?><?php /**PATH foo ENDPATH**/ ?>',
],
'PHP block between content.' => [
'Hello world<?php echo $path ?>Hi There',
'Hello world<?php echo $path ?>Hi There<?php /**PATH foo ENDPATH**/ ?>',
'<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello world<?php echo $path ?>Hi There<?php } ?><?php /**PATH foo ENDPATH**/ ?>',
],
'Multiple PHP blocks.' => [
'Hello world<?php echo $path ?>Hi There<?php echo $path ?>Hello Again',
'Hello world<?php echo $path ?>Hi There<?php echo $path ?>Hello Again<?php /**PATH foo ENDPATH**/ ?>',
'<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello world<?php echo $path ?>Hi There<?php echo $path ?>Hello Again<?php } ?><?php /**PATH foo ENDPATH**/ ?>',
],
'Multiple PHP blocks without closing ?>' => [
'Hello world<?php echo $path ?>Hi There<?php echo $path',
'Hello world<?php echo $path ?>Hi There<?php echo $path ?><?php /**PATH foo ENDPATH**/ ?>',
'<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello world<?php echo $path ?>Hi There<?php echo $path ?><?php } ?><?php /**PATH foo ENDPATH**/ ?>',
],
'Short open echo tag' => [
'Hello world<?= echo $path',
'Hello world<?= echo $path ?><?php /**PATH foo ENDPATH**/ ?>',
'<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello world<?= echo $path ?><?php } ?><?php /**PATH foo ENDPATH**/ ?>',
],
'Echo XML declaration' => [
'<?php echo \'<?xml version="1.0" encoding="UTF-8"?>\';',
'<?php echo \'<?xml version="1.0" encoding="UTF-8"?>\'; ?><?php /**PATH foo ENDPATH**/ ?>',
'<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?><?php echo \'<?xml version="1.0" encoding="UTF-8"?>\'; ?><?php } ?><?php /**PATH foo ENDPATH**/ ?>',
],
];
}
Expand All @@ -187,7 +187,7 @@ public function testDontIncludeEmptyPath()
$compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
$files->shouldReceive('get')->once()->with('')->andReturn('Hello World');
$files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true);
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php', 'Hello World');
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php', '<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello World<?php } ?>');
$compiler->setPath('');
$compiler->compile();
}
Expand All @@ -197,7 +197,7 @@ public function testDontIncludeNullPath()
$compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
$files->shouldReceive('get')->once()->with(null)->andReturn('Hello World');
$files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true);
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php', 'Hello World');
$files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php', '<?php return function ($__laravel_data) { extract($__laravel_data, EXTR_SKIP); ?>Hello World<?php } ?>');
$compiler->setPath(null);
$compiler->compile();
}
Expand Down
22 changes: 11 additions & 11 deletions tests/View/ViewCompilerEngineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,19 @@ public function testViewsAreRecompiledWhenCompiledViewIsMissingViaFileNotFoundEx

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andReturn('compiled-content');

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andThrow(new FileNotFoundException(
"File does not exist at path {$path}."
));

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andReturn('compiled-content');

$engine->getCompiler()
Expand Down Expand Up @@ -139,19 +139,19 @@ public function testViewsAreRecompiledWhenCompiledViewIsMissingViaRequireExcepti

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andReturn('compiled-content');

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andThrow(new ErrorException(
"require({$path}): Failed to open stream: No such file or directory",
));

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andReturn('compiled-content');

$engine->getCompiler()
Expand Down Expand Up @@ -184,19 +184,19 @@ public function testViewsAreRecompiledJustOnceWhenCompiledViewIsMissing()

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andReturn('compiled-content');

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andThrow(new FileNotFoundException(
"File does not exist at path {$path}."
));

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andThrow(new FileNotFoundException(
"File does not exist at path {$path}."
));
Expand Down Expand Up @@ -234,7 +234,7 @@ public function testViewsAreNotRecompiledOnRegularViewException()

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andThrow(new Exception(
'Just an regular error...'
));
Expand Down Expand Up @@ -269,7 +269,7 @@ public function testViewsAreNotRecompiledIfTheyWereJustCompiled()

$files->shouldReceive('getRequire')
->once()
->with($compiled, [])
->with($compiled, [], m::on(fn ($c) => $c(1) == false && $c(fn() => 'test') == true))
->andThrow(new FileNotFoundException(
"File does not exist at path {$path}."
));
Expand Down