Skip to content

Commit a944904

Browse files
authored
Add @​context Blade directive (#56146)
Co-authored-by: Martin Bean <[email protected]>
1 parent 5474ddb commit a944904

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

src/Illuminate/View/Compilers/BladeCompiler.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ class BladeCompiler extends Compiler implements CompilerInterface
2121
Concerns\CompilesComments,
2222
Concerns\CompilesComponents,
2323
Concerns\CompilesConditionals,
24+
Concerns\CompilesContexts,
2425
Concerns\CompilesEchos,
2526
Concerns\CompilesErrors,
2627
Concerns\CompilesFragments,
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
namespace Illuminate\View\Compilers\Concerns;
4+
5+
trait CompilesContexts
6+
{
7+
/**
8+
* Compile the context statements into valid PHP.
9+
*
10+
* @param string $expression
11+
* @return string
12+
*/
13+
protected function compileContext($expression)
14+
{
15+
$expression = $this->stripParentheses($expression);
16+
17+
return '<?php $__contextArgs = ['.$expression.'];
18+
if (context()->has($__contextArgs[0])) :
19+
if (isset($value)) { $__contextPrevious[] = $value; }
20+
$value = context()->get($__contextArgs[0]); ?>';
21+
}
22+
23+
/**
24+
* Compile the endcontext statements into valid PHP.
25+
*
26+
* @param string $expression
27+
* @return string
28+
*/
29+
protected function compileEndcontext($expression)
30+
{
31+
return '<?php unset($value);
32+
if (isset($__contextPrevious) && !empty($__contextPrevious)) { $value = array_pop($__contextPrevious); }
33+
if (isset($__contextPrevious) && empty($__contextPrevious)) { unset($__contextPrevious); }
34+
endif;
35+
unset($__contextArgs); ?>';
36+
}
37+
}

tests/View/Blade/BladeContextTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
namespace Illuminate\Tests\View\Blade;
4+
5+
class BladeContextTest extends AbstractBladeTestCase
6+
{
7+
public function testContextsAreCompiled()
8+
{
9+
$string = '
10+
@context(\'foo\')
11+
<span>{{ $value }}</span>
12+
@endcontext';
13+
$expected = '
14+
<?php $__contextArgs = [\'foo\'];
15+
if (context()->has($__contextArgs[0])) :
16+
if (isset($value)) { $__contextPrevious[] = $value; }
17+
$value = context()->get($__contextArgs[0]); ?>
18+
<span><?php echo e($value); ?></span>
19+
<?php unset($value);
20+
if (isset($__contextPrevious) && !empty($__contextPrevious)) { $value = array_pop($__contextPrevious); }
21+
if (isset($__contextPrevious) && empty($__contextPrevious)) { unset($__contextPrevious); }
22+
endif;
23+
unset($__contextArgs); ?>';
24+
25+
$this->assertEquals($expected, $this->compiler->compileString($string));
26+
}
27+
}

0 commit comments

Comments
 (0)