Skip to content

Commit

Permalink
[10.x] allow resolving view from closure (laravel#48719)
Browse files Browse the repository at this point in the history
* allow resolving view from closure

* fix styling
  • Loading branch information
ph7jack authored and timacdonald committed Oct 24, 2023
1 parent 12e07c0 commit cfa1b8b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Illuminate/View/Component.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ public function resolveView()
}

$resolver = function ($view) {
if ($view instanceof ViewContract) {
return $view;
}

return $this->extractBladeViewFromString($view);
};

Expand Down
37 changes: 37 additions & 0 deletions tests/View/ComponentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Tests\View;

use Closure;
use Illuminate\Config\Repository as Config;
use Illuminate\Container\Container;
use Illuminate\Contracts\Container\BindingResolutionException;
Expand Down Expand Up @@ -72,6 +73,42 @@ public function testRegularViewsGetReturnedUsingViewHelper()
$this->assertSame($view, $component->resolveView());
}

public function testRenderingStringClosureFromComponent()
{
$this->config->shouldReceive('get')->once()->with('view.compiled')->andReturn('/tmp');
$this->viewFactory->shouldReceive('exists')->once()->andReturn(false);
$this->viewFactory->shouldReceive('addNamespace')->once()->with('__components', '/tmp');

$component = new class() extends Component
{
protected $title;

public function __construct($title = 'World')
{
$this->title = $title;
}

public function render()
{
return function (array $data) {
return "<p>Hello {$this->title}</p>";
};
}
};

$closure = $component->resolveView();

$viewPath = $closure([]);

$this->viewFactory->shouldReceive('make')->with($viewPath, [], [])->andReturn('<p>Hello World</p>');

$this->assertInstanceOf(Closure::class, $closure);
$this->assertSame('__components::9cc08f5001b343c093ee1a396da820dc', $viewPath);

$hash = str_replace('__components::', '', $viewPath);
$this->assertSame('<p>Hello World</p>', file_get_contents("/tmp/{$hash}.blade.php"));
}

public function testRegularViewsGetReturnedUsingViewMethod()
{
$view = m::mock(View::class);
Expand Down

0 comments on commit cfa1b8b

Please sign in to comment.