Skip to content
Merged
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
1 change: 1 addition & 0 deletions src/Illuminate/Support/Facades/Blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
* @method static void withDoubleEncoding()
* @method static void withoutComponentTags()
* @method static void withoutDoubleEncoding()
* @method static void stringable(string|callable $class, callable|null $handler)
*
* @see \Illuminate\View\Compilers\BladeCompiler
*/
Expand Down
28 changes: 27 additions & 1 deletion src/Illuminate/View/Compilers/BladeCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

namespace Illuminate\View\Compilers;

use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ReflectsClosures;
use InvalidArgumentException;

class BladeCompiler extends Compiler implements CompilerInterface
Expand All @@ -22,7 +24,8 @@ class BladeCompiler extends Compiler implements CompilerInterface
Concerns\CompilesLoops,
Concerns\CompilesRawPhp,
Concerns\CompilesStacks,
Concerns\CompilesTranslations;
Concerns\CompilesTranslations,
ReflectsClosures;

/**
* All of the registered extensions.
Expand Down Expand Up @@ -99,6 +102,13 @@ class BladeCompiler extends Compiler implements CompilerInterface
*/
protected $echoFormat = 'e(%s)';

/**
* Custom rendering callbacks for stringable objects.
*
* @var array
*/
public $echoHandlers = [];

/**
* Array of footer lines to be added to the template.
*
Expand Down Expand Up @@ -701,6 +711,22 @@ public function getCustomDirectives()
return $this->customDirectives;
}

/**
* Add a handler to be executed before echoing a given class.
*
* @param string|callable $class
* @param callable|null $handler
* @return void
*/
public function stringable($class, $handler = null)
{
if ($class instanceof Closure) {
[$class, $handler] = [$this->firstClosureParameterType($class), $class];
}

$this->echoHandlers[$class] = $handler;
}

/**
* Register a new precompiler.
*
Expand Down
23 changes: 20 additions & 3 deletions src/Illuminate/View/Compilers/Concerns/CompilesEchos.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ protected function compileRawEchos($value)
$callback = function ($matches) {
$whitespace = empty($matches[3]) ? '' : $matches[3].$matches[3];

return $matches[1] ? substr($matches[0], 1) : "<?php echo {$matches[2]}; ?>{$whitespace}";
return $matches[1]
? substr($matches[0], 1)
: "<?php echo {$this->applyEchoHandlerFor($matches[2])}; ?>{$whitespace}";
};

return preg_replace_callback($pattern, $callback, $value);
Expand All @@ -65,7 +67,7 @@ protected function compileRegularEchos($value)
$callback = function ($matches) {
$whitespace = empty($matches[3]) ? '' : $matches[3].$matches[3];

$wrapped = sprintf($this->echoFormat, $matches[2]);
$wrapped = sprintf($this->echoFormat, $this->applyEchoHandlerFor($matches[2]));

return $matches[1] ? substr($matches[0], 1) : "<?php echo {$wrapped}; ?>{$whitespace}";
};
Expand All @@ -86,9 +88,24 @@ protected function compileEscapedEchos($value)
$callback = function ($matches) {
$whitespace = empty($matches[3]) ? '' : $matches[3].$matches[3];

return $matches[1] ? $matches[0] : "<?php echo e({$matches[2]}); ?>{$whitespace}";
return $matches[1]
? $matches[0]
: "<?php echo e({$this->applyEchoHandlerFor($matches[2])}); ?>{$whitespace}";
};

return preg_replace_callback($pattern, $callback, $value);
}

/**
* Wrap the echoable value in an echo handler if applicable.
*
* @param string $value
* @return string
*/
protected function applyEchoHandlerFor($value)
{
return empty($this->echoHandlers)
? $value
: "is_object($value) && isset(app('blade.compiler')->echoHandlers[get_class($value)]) ? call_user_func_array(app('blade.compiler')->echoHandlers[get_class($value)], [$value]) : $value";
}
}
77 changes: 77 additions & 0 deletions tests/View/Blade/BladeEchoHandlerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace Illuminate\Tests\View\Blade;

use Exception;
use Illuminate\Support\Fluent;
use Illuminate\Support\Str;

class BladeEchoHandlerTest extends AbstractBladeTestCase
{
protected function setUp(): void
{
parent::setUp();

$this->compiler->stringable(function (Fluent $object) {
return 'Hello World';
});
}

public function testBladeHandlersCanBeAddedForAGivenClass()
{
$this->assertSame('Hello World', $this->compiler->echoHandlers[Fluent::class](new Fluent()));
}

public function testBladeHandlerCanInterceptRegularEchos()
{
$this->assertSame(
"<?php echo e(is_object(\$exampleObject) && isset(app('blade.compiler')->echoHandlers[get_class(\$exampleObject)]) ? call_user_func_array(app('blade.compiler')->echoHandlers[get_class(\$exampleObject)], [\$exampleObject]) : \$exampleObject); ?>",
$this->compiler->compileString('{{$exampleObject}}')
);
}

public function testBladeHandlerCanInterceptRawEchos()
{
$this->assertSame(
"<?php echo is_object(\$exampleObject) && isset(app('blade.compiler')->echoHandlers[get_class(\$exampleObject)]) ? call_user_func_array(app('blade.compiler')->echoHandlers[get_class(\$exampleObject)], [\$exampleObject]) : \$exampleObject; ?>",
$this->compiler->compileString('{!!$exampleObject!!}')
);
}

public function testBladeHandlerCanInterceptEscapedEchos()
{
$this->assertSame(
"<?php echo e(is_object(\$exampleObject) && isset(app('blade.compiler')->echoHandlers[get_class(\$exampleObject)]) ? call_user_func_array(app('blade.compiler')->echoHandlers[get_class(\$exampleObject)], [\$exampleObject]) : \$exampleObject); ?>",
$this->compiler->compileString('{{{$exampleObject}}}')
);
}

public function testWhitespaceIsPreservedCorrectly()
{
$this->assertSame(
"<?php echo e(is_object(\$exampleObject) && isset(app('blade.compiler')->echoHandlers[get_class(\$exampleObject)]) ? call_user_func_array(app('blade.compiler')->echoHandlers[get_class(\$exampleObject)], [\$exampleObject]) : \$exampleObject); ?>\n\n",
$this->compiler->compileString("{{\$exampleObject}}\n")
);
}

public function testHandlerLogicWorksCorrectly()
{
$this->expectExceptionMessage('The fluent object has been successfully handled!');

$this->compiler->stringable(Fluent::class, function ($object) {
throw new Exception('The fluent object has been successfully handled!');
});

app()->singleton('blade.compiler', function () {
return $this->compiler;
});

$exampleObject = new Fluent();

eval(
Str::of($this->compiler->compileString('{{$exampleObject}}'))
->after('<?php')
->beforeLast('?>')
);
}
}