Skip to content

Commit

Permalink
[10.x]: Add Blade @use directive (#49179)
Browse files Browse the repository at this point in the history
* Add Blade @use directive

* Allow for `use` without `as`

* Update CompilesUseStatements.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
simonhamp and taylorotwell committed Nov 30, 2023
1 parent 5172665 commit e4ffa95
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Illuminate/View/Compilers/BladeCompiler.php
Expand Up @@ -33,6 +33,7 @@ class BladeCompiler extends Compiler implements CompilerInterface
Concerns\CompilesStacks,
Concerns\CompilesStyles,
Concerns\CompilesTranslations,
Concerns\CompilesUseStatements,
ReflectsClosures;

/**
Expand Down
22 changes: 22 additions & 0 deletions src/Illuminate/View/Compilers/Concerns/CompilesUseStatements.php
@@ -0,0 +1,22 @@
<?php

namespace Illuminate\View\Compilers\Concerns;

trait CompilesUseStatements
{
/**
* Compile the use statements into valid PHP.
*
* @param string $expression
* @return string
*/
protected function compileUse($expression)
{
$segments = explode(',', preg_replace("/[\(\)]/", '', $expression));

$use = trim($segments[0], " '\"");
$as = isset($segments[1]) ? ' as '.trim($segments[1], " '\"") : '';

return "<?php use \\{$use}{$as}; ?>";
}
}
20 changes: 20 additions & 0 deletions tests/View/Blade/BladeUseTest.php
@@ -0,0 +1,20 @@
<?php

namespace Illuminate\Tests\View\Blade;

class BladeUseTest extends AbstractBladeTestCase
{
public function testUseStatementsAreCompiled()
{
$string = "Foo @use('SomeNamespace\SomeClass', 'Foo') bar";
$expected = "Foo <?php use \SomeNamespace\SomeClass as Foo; ?> bar";
$this->assertEquals($expected, $this->compiler->compileString($string));
}

public function testUseStatementsWithoutAsAreCompiled()
{
$string = "Foo @use('SomeNamespace\SomeClass') bar";
$expected = "Foo <?php use \SomeNamespace\SomeClass; ?> bar";
$this->assertEquals($expected, $this->compiler->compileString($string));
}
}

0 comments on commit e4ffa95

Please sign in to comment.