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

Draft
wants to merge 7 commits into
base: 11.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 5 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
22 changes: 22 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,26 @@ 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) {
return $value ? sprintf('%s', $key) : null;
} elseif ($value instanceof ComponentAttributeBag) {
return collect($value->getAttributes())->map(fn ($value, $key) => sprintf('%s="%s"', $key, $value))->join(' ');
} else {
return sprintf("%s", $value);
}
})
->implode(" ");
}

Copy link
Member

Choose a reason for hiding this comment

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

I would want to make sure this matches the attribute parsing we do in Vite.

<div {{ Arr::toHtmlAttributes([
    'null-value'=> null,         // removed
    'false-value' => false,      // removed
    'empty-string-value' => '',  
    'zero-value' => 0,           
    'true-value' => true,        
    'other-key' => 'other-value',
]) }}>

//

<div
    empty-string-value="" 
    zero-value="0" 
    true-value="true-value" 
    other-key="other-value"
>

/**
* 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
73 changes: 67 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 @@ -581,8 +594,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 +621,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 +647,8 @@ protected function getAttributesFromAttributeString(string $attributeString)
}

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

/**
Expand Down Expand Up @@ -678,7 +694,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 +702,52 @@ 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') {
// $match[2] = str_replace('"', "'", $match[2]);

// Using regex to extract keys and values
$matches = [];
preg_match_all(
"/'([^']+)' =>\s*(true|false|'.*?')/",
$match[2],
$matches);

$parsedArray = [];
// Iterate through the matches to handle boolean and string values correctly
foreach ($matches[1] as $index => $key) {
$value = $matches[2][$index];

// Check if the value is actual boolean true or false
if ($value === 'true') {
$parsedArray[$key] = true;
} elseif ($value === 'false') {
$parsedArray[$key] = false;
} else {
// If it's a string (e.g., 'value'), remove the surrounding quotes
$parsedArray[$key] = trim($value, "'");
}
}

// Combine keys and values into an associative array
$parsedArray = array_combine($matches[1], $matches[2]);
return \Illuminate\Support\Arr::toHtmlAttributes($parsedArray);
}

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

/**
* 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}; ?>";
}
}
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\"' => true, 'disabled=\"disabled\"' => false, 'role=\"button\"'])></span>";
$expected = "<span <?php echo \Illuminate\Support\Arr::toHtmlAttributes(['class=\"mt-1\"' => true, 'disabled=\"disabled\"' => false, 'role=\"button\"']); ?>></span>";

$this->assertEquals($expected, $this->compiler->compileString($string));
}
}