Skip to content

Commit

Permalink
Merge pull request #758 from hydephp/Create-class-AnonymousViewCompiler
Browse files Browse the repository at this point in the history
Add simple class to compile any Blade file without having to register it as a view path
  • Loading branch information
caendesilva authored Dec 15, 2022
2 parents e1151c3 + 4a546de commit ed57dac
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
38 changes: 38 additions & 0 deletions packages/framework/src/Framework/Actions/AnonymousViewCompiler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Hyde\Framework\Actions;

use Hyde\Facades\Filesystem;
use Hyde\Framework\Concerns\InvokableAction;
use Hyde\Framework\Exceptions\FileNotFoundException;
use Illuminate\Support\Facades\Blade;

/**
* Compile any Blade file using the Blade facade as it allows us to render
* it without having to register the directory with the view finder.
*/
class AnonymousViewCompiler extends InvokableAction
{
protected string $viewPath;
protected array $data;

public function __construct(string $viewPath, array $data = [])
{
$this->viewPath = $viewPath;
$this->data = $data;
}

public function __invoke(): string
{
if (Filesystem::missing($this->viewPath)) {
throw new FileNotFoundException($this->viewPath);
}

return Blade::render(
Filesystem::getContents($this->viewPath),
$this->data
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types=1);

namespace Hyde\Framework\Testing\Feature\Actions;

use Hyde\Framework\Actions\AnonymousViewCompiler;
use Hyde\Framework\Exceptions\FileNotFoundException;
use Hyde\Testing\TestCase;

/**
* @covers \Hyde\Framework\Actions\AnonymousViewCompiler
*/
class AnonymousViewCompilerTest extends TestCase
{
public function testCanCompileBladeFile()
{
$this->file('foo.blade.php', "{{ 'Hello World' }}");

$this->assertSame('Hello World', AnonymousViewCompiler::call('foo.blade.php'));
}

public function testCanCompileBladeFileWithData()
{
$this->file('foo.blade.php', '{{ $foo }}');

$this->assertSame('bar', AnonymousViewCompiler::call('foo.blade.php', ['foo' => 'bar']));
}

public function testWithMissingView()
{
$this->expectException(FileNotFoundException::class);
$this->expectExceptionMessage('File foo.blade.php not found.');

AnonymousViewCompiler::call('foo.blade.php');
}
}

0 comments on commit ed57dac

Please sign in to comment.