That just looks like a mess. What is the problem you're trying to solve?
How to extend Illumimnate\View\ComponentAttributeBag
Illuminate\View\ComponentAttributeBag has a funtion merge()
The function merges attributes which is super helpful when building nested components. However, the merge handles class attributes different from all other attributes by appending, rather than overwriting. I would like to extend the function so that other types of attributes can be appended rather than overwritten. Specifically, I'm building components that utilize AlpineJS. AlpineJS uses custom attributes to declare functionality. Specifically the x-on: directive (@click, @input, @mousedown,...). But when components are nested, and you merge attributes with the current function... only the outermost components x-on directives get included.
I would like to extend that function so that I can conditionally merge x-on attributes by appending rather than overwriting.
It's also weird because you HAVE to use the ComponentAttributeBag to pass attributes along. I tried just building my own array, but blade ends up not rendering the component.
Is there a laravel(y) way for me to extend that class?
For now, I just have this little function to do the job:
static function mergeXonAttributes($attributes,$newXonAttributes){
$xonData = [];
foreach($attributes as $key=>$value) {
$xon = (strpos($key,'@')!==false || strpos($key,'x-on')!==false);
if(!$xon) continue;
$xonData[$key] = implode(';', array_unique(
array_filter([$newXonAttributes[$key] ?? '', $value])
));
}
$xonData = array_merge($newXonAttributes,$xonData);
$attributes->setAttributes(array_merge($attributes->getAttributes(),$xonData));
}
The class implements macroable so you can add your own method to it as a macro
Please or to participate in this conversation.