From 71dfe0f0824412f106b80df8dedd7708e66dfb00 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Fri, 23 Jun 2017 13:47:10 -0500 Subject: [PATCH] add if method --- .../View/Compilers/BladeCompiler.php | 35 +++++++++++++++++++ tests/View/Blade/BladeCustomTest.php | 13 +++++++ 2 files changed, 48 insertions(+) diff --git a/src/Illuminate/View/Compilers/BladeCompiler.php b/src/Illuminate/View/Compilers/BladeCompiler.php index e11731e8afe6..a401244386ba 100644 --- a/src/Illuminate/View/Compilers/BladeCompiler.php +++ b/src/Illuminate/View/Compilers/BladeCompiler.php @@ -2,6 +2,7 @@ namespace Illuminate\View\Compilers; +use Closure; use Illuminate\Support\Arr; use Illuminate\Support\Str; @@ -345,6 +346,40 @@ public function getExtensions() return $this->extensions; } + /** + * Register an "if" statement directive. + * + * @param string $name + * @param \Closrue $callback + * @return void + */ + public function if($name, Closure $callback) + { + $this->conditions[$name] = $callback; + + $this->directive($name, function ($expression) use ($name) { + return $expression + ? "" + : ""; + }); + + $this->directive('end'.$name, function () { + return ""; + }); + } + + /** + * Check the result of a condition. + * + * @param string $name + * @param array $parameters + * @return bool + */ + public function check($name, ...$parameters) + { + return call_user_func($this->conditions[$name], ...$parameters); + } + /** * Register a handler for custom directives. * diff --git a/tests/View/Blade/BladeCustomTest.php b/tests/View/Blade/BladeCustomTest.php index 27eba76227b9..510b1c1d551c 100644 --- a/tests/View/Blade/BladeCustomTest.php +++ b/tests/View/Blade/BladeCustomTest.php @@ -60,4 +60,17 @@ public function testCustomExtensionOverwritesCore() $expected = ''; $this->assertEquals($expected, $this->compiler->compileString($string)); } + + public function testCustomConditions() + { + $this->compiler->if('custom', function ($user) { + return true; + }); + + $string = '@custom($user) +@endcustom'; + $expected = ' +'; + $this->assertEquals($expected, $this->compiler->compileString($string)); + } }