Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New @attributes blade directive. #52783

Closed
Closed
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
25 changes: 25 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

use ArgumentCountError;
use ArrayAccess;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Traits\Macroable;
use Illuminate\View\ComponentAttributeBag;
use InvalidArgumentException;
use Random\Randomizer;

Expand Down Expand Up @@ -891,6 +893,29 @@ public static function toCssClasses($array)
return implode(' ', $classes);
}

/**
* Conditionally compile attributes from an array into an HTML attribute string.
*
* @param array $array
* @return string
*/
public static function toHtmlAttributes($array)
{
return Collection::make($array)->map(function ($value, $key) {
if ($key) {
$value = value($value);
return is_null($value) || $value === false ? null : sprintf('%s="%s"', $key, $value);
} elseif ($value instanceof ComponentAttributeBag) {
return self::toHtmlAttributes($value->getAttributes());
} else {
return sprintf("%s", $value);
}
})
->filter()
->values()
->implode(" ");
}

/**
* Conditionally compile styles from an array into a style list.
*
Expand Down
1 change: 1 addition & 0 deletions src/Illuminate/View/Compilers/BladeCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
class BladeCompiler extends Compiler implements CompilerInterface
{
use Concerns\CompilesAuthorizations,
Concerns\CompilesAttributes,
Concerns\CompilesClasses,
Concerns\CompilesComments,
Concerns\CompilesComponents,
Expand Down
84 changes: 78 additions & 6 deletions src/Illuminate/View/Compilers/ComponentTagCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
*/
class ComponentTagCompiler
{

use Concerns\CompilesAttributes;

/**
* The Blade compiler instance.
*
Expand Down Expand Up @@ -111,6 +114,10 @@ protected function compileOpeningTags(string $value)
(?:
\s+
(?:
(?:
@(?:attributes)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
@(?:class)(\( (?: (?>[^()]+) | (?-1) )* \))
)
Expand Down Expand Up @@ -150,9 +157,7 @@ protected function compileOpeningTags(string $value)

return preg_replace_callback($pattern, function (array $matches) {
$this->boundAttributes = [];

$attributes = $this->getAttributesFromAttributeString($matches['attributes']);

return $this->componentString($matches[1], $attributes);
}, $value);
}
Expand All @@ -176,6 +181,10 @@ protected function compileSelfClosingTags(string $value)
(?:
\s+
(?:
(?:
@(?:attributes)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
@(?:class)(\( (?: (?>[^()]+) | (?-1) )* \))
)
Expand Down Expand Up @@ -511,6 +520,10 @@ public function compileSlots(string $value)
(?:
\s+
(?:
(?:
@(?:attributes)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
@(?:class)(\( (?: (?>[^()]+) | (?-1) )* \))
)
Expand Down Expand Up @@ -545,6 +558,8 @@ public function compileSlots(string $value)
/x";

$value = preg_replace_callback($pattern, function ($matches) {


$name = $this->stripQuotes($matches['inlineName'] ?: $matches['name'] ?: $matches['boundName']);

if (Str::contains($name, '-') && ! empty($matches['inlineName'])) {
Expand All @@ -558,6 +573,7 @@ public function compileSlots(string $value)

$this->boundAttributes = [];


$attributes = $this->getAttributesFromAttributeString($matches['attributes']);

// If an inline name was provided and a name or bound name was *also* provided, we will assume the name should be an attribute...
Expand All @@ -581,8 +597,9 @@ public function compileSlots(string $value)
*/
protected function getAttributesFromAttributeString(string $attributeString)
{
$attributeString = $this->parseShortAttributeSyntax($attributeString);
$attributeString = $this->parseComponentTagAttributesStatements($attributeString);
$attributeString = $this->parseAttributeBag($attributeString);
$attributeString = $this->parseShortAttributeSyntax($attributeString);
$attributeString = $this->parseComponentTagClassStatements($attributeString);
$attributeString = $this->parseComponentTagStyleStatements($attributeString);
$attributeString = $this->parseBindAttributes($attributeString);
Expand All @@ -607,7 +624,8 @@ protected function getAttributesFromAttributeString(string $attributeString)
return [];
}

return collect($matches)->mapWithKeys(function ($match) {
return collect($matches)
->mapWithKeys(function ($match) {
$attribute = $match['attribute'];
$value = $match['value'] ?? null;

Expand All @@ -632,7 +650,8 @@ protected function getAttributesFromAttributeString(string $attributeString)
}

return [$attribute => $value];
})->toArray();
})
->toArray();
}

/**
Expand Down Expand Up @@ -678,7 +697,6 @@ protected function parseComponentTagClassStatements(string $attributeString)
'/@(class)(\( ( (?>[^()]+) | (?2) )* \))/x', function ($match) {
if ($match[1] === 'class') {
$match[2] = str_replace('"', "'", $match[2]);

return ":class=\"\Illuminate\Support\Arr::toCssClasses{$match[2]}\"";
}

Expand All @@ -687,6 +705,60 @@ protected function parseComponentTagClassStatements(string $attributeString)
);
}

/**
* Parse @attributes statements in a given attribute string into their fully-qualified syntax.
*
* @param string $attributeString
* @return string
*/
protected function parseComponentTagAttributesStatements(string $attributeString)
{
return preg_replace_callback(
'/@(attributes)(\( ( (?>[^()]+) | (?2) )* \))/x', function ($match) {


if ($match[1] === 'attributes') {
return \Illuminate\Support\Arr::toHtmlAttributes(
$this->reformatAttributeExpressionStringToArray($match[2])
);
}

return $match[0];
}, $attributeString
);
}

/**
* Take an attribute string in expression format (surrounded by ([]))
* and reformat it into a compiled HTML attribute string.
*
* @param string $expression
* @return array
*/
public function reformatAttributeExpressionStringToArray(string $expression)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timacdonald could use some pointers here if you don't mind?

For any @attributes call on a normal HTML element i'm just doing this - which is fairly simple.

For @attributes calls on slots and custom components, it's tough, because we can't compile into an existing attribute and prefix with : in the same way we can with @class, the attributes need to be parsed before compile time, so that they're fully parsed and passed down into the component.

BUT, this doesn't work when functions and

I'd ended up with this, which is taking the @attributes expression, parsing it using a regex, and turning it back into an array so it can be parsed properly by the new toHtmlAttributes method, but this isn't going to support things like calls to when or $variables properly.

Am i on the right track, or should i look at taking another approach? I'm trying to get my head around blade's compilation order, and the expectations of the output.

Cheers!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey, Dan, I don't know a heap about the Blade compiler unfortunately.

I don't imagine that the regex is gonna be the answer...but then again blade is entirely regex so maybe it is?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No worries man, i'll keep plucking at the problem, it feels like this is over-engineered to me, but will keep digging. 👍

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good. Don't take my feedback as anything you must do. Just sharing an opinion.

{
preg_match_all(
'/[\'"](?<key>[^\'"]+)[\'"]\s*=>\s*(?:(?<bool>true|false)|(?<int>\d+)|[\'"](?<string>[^\'"]*)[\'"])/x',
trim($expression, '()[]'),
$matches,
PREG_SET_ORDER
);
return \Illuminate\Support\Collection::make($matches)
->mapWithKeys(function ($match) {
$key = $match['key'];
if (isset($match['bool']) && $match['bool'] !== '') {
$value = $match['bool'] === 'true';
} elseif (isset($match['int']) && $match['int'] !== '') {
$value = intval($match['int']);
} elseif (isset($match['string'])) {
$value = $match['string'];
} else {
$value = null;
}
return [$key => $value];
})->toArray();
}

/**
* Parse @style statements in a given attribute string into their fully-qualified syntax.
*
Expand Down
18 changes: 18 additions & 0 deletions src/Illuminate/View/Compilers/Concerns/CompilesAttributes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Illuminate\View\Compilers\Concerns;

trait CompilesAttributes
{
/**
* Compile the conditional class statement into valid PHP.
*
* @param string $expression
* @return string
*/
protected function compileAttributes($expression)
{
$expression = is_null($expression) ? '([])' : $expression;
return "<?php echo \Illuminate\Support\Arr::toHtmlAttributes{$expression}; ?>";
}
}
34 changes: 34 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\View\ComponentAttributeBag;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use stdClass;
Expand Down Expand Up @@ -1235,6 +1236,39 @@ public function testToCssClasses()
$this->assertSame('font-bold mt-4 ml-2', $classes);
}

public function testToHtmlAttributes()
{
$resultString = Arr::toHtmlAttributes([
new ComponentAttributeBag([
'taylor' => false,
'joe' => '',
'aaron' => 0,
'james' => null,
'tim' => 'macdonald',
'christoph' => fn () => "rumpel",
]),
'audrey' => '',
'alex' => 0,
'leyton' => false,
'till' => null,
'josie' => 'cold',
'hedwood' => fn () => 'melanie'
]);

$this->assertStringContainsString( 'audrey=""', $resultString);
$this->assertStringContainsString( 'hedwood="melanie"', $resultString);
$this->assertStringContainsString( 'alex="0"', $resultString);
$this->assertStringNotContainsString( 'leyton', $resultString);
$this->assertStringNotContainsString( 'till', $resultString);

$this->assertStringContainsString( 'joe=""', $resultString);
$this->assertStringContainsString( 'christoph="rumpel"', $resultString);
$this->assertStringContainsString( 'aaron="0"', $resultString);
$this->assertStringContainsString( 'tim="macdonald"', $resultString);
$this->assertStringNotContainsString( 'taylor', $resultString);
$this->assertStringNotContainsString( 'james', $resultString);
}

public function testToCssStyles()
{
$styles = Arr::toCssStyles([
Expand Down
14 changes: 14 additions & 0 deletions tests/View/Blade/BladeAttributesTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Illuminate\Tests\View\Blade;

class BladeAttributesTest extends AbstractBladeTestCase
{
public function testAttributesAreConditionallyCompiledFromArray()
{
$string = "<span @attributes(['class' => \"mt-1\", 'disabled' => false, 'role' => null, 'wire:poll' => fn () => true])></span>";
$expected = "<span <?php echo \Illuminate\Support\Arr::toHtmlAttributes(['class' => \"mt-1\", 'disabled' => false, 'role' => null, 'wire:poll' => fn () => true]); ?>></span>";

$this->assertEquals($expected, $this->compiler->compileString($string));
}
}
20 changes: 20 additions & 0 deletions tests/View/Blade/BladeComponentTagCompilerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,26 @@ public function testSlotsWithClassDirectiveCanBeCompiled()
$this->assertSame("@slot('foo', null, ['class' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute(\Illuminate\Support\Arr::toCssClasses(\$classes))]) \n".' @endslot', trim($result));
}

public function testSlotsWithAttributesDirectiveCanBeCompiled()
{
$this->mockViewFactory();
$result = $this->compiler()->compileSlots('<x-slot name="foo" @attributes(["class" => "ml-4", "disabled" => false, "readonly" => 0])>"])>
</x-slot>');
dd(trim($result));
$this->assertSame("@slot('foo', null, ['class' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute(\Illuminate\Support\Arr::toCssClasses(\$classes))]) \n".' @endslot', trim($result));
}

public function testReformatAttributeExpressionStringToArrayMethod()
{
$compiler = app(ComponentTagCompiler::class);
$result = $compiler->reformatAttributeExpressionStringToArray('(["contains(" => ")bracket", "[other" => "]bracket,", "string" => "string", "bool" => true, "falseBool" => false, "int" => 32, \'singlestring\' => \'single\'])');
$this->assertEquals('string', $result['string']);
$this->assertEquals('single', $result['singlestring']);
$this->assertTrue($result['bool']);
$this->assertFalse($result['falseBool']);
$this->assertEquals(32, $result['int']);
}

public function testSlotsWithStyleDirectiveCanBeCompiled()
{
$this->mockViewFactory();
Expand Down
Loading