Skip to content

Commit

Permalink
BaseController buildAttributes throws error when attribute value is n…
Browse files Browse the repository at this point in the history
…ot a string (#310)

* fix: BaseController buildAttributes throws if attribute value not string

* refactor: BaseController buildAttributes

* refactor: BaseController buildAttributes
  • Loading branch information
thorbrink authored Jul 7, 2023
1 parent 0d23d88 commit 838fc5a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 11 deletions.
18 changes: 18 additions & 0 deletions source/php/Component/BaseController.Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

use ComponentLibrary\Component\BaseController;

class BaseControllerTest extends PHPUnit\Framework\TestCase
{
public function testBuildAttributesReturnsAllAttributesAsString()
{
$attributes = ['One' => 'one', 'Two' => 'two'];
$this->assertEquals('One="one" Two="two"', BaseController::buildAttributes($attributes));
}

public function testBuildAttributesOnlyHandlesAttributeStringValues()
{
$attributes = ['One' => ['foo']];
$this->assertEquals('', BaseController::buildAttributes($attributes));
}
}
27 changes: 16 additions & 11 deletions source/php/Component/BaseController.php
Original file line number Diff line number Diff line change
Expand Up @@ -386,18 +386,23 @@ public function sanitizeInlineCss($inlineCss)
return preg_replace('/.*:\s*;/i', '', $inlineCss);
}

public static function buildAttributes($attributes)
/**
* Builds a string of attributes.
*
* @param array $attributes An array of attributes to be added to the string.
* @return string A string of attributes.
*/
public static function buildAttributes(array $attributes): string
{
return (string) implode(
' ',
array_map(
function ($v, $k) {
return sprintf('%s="%s"', $k, htmlspecialchars($v, ENT_QUOTES, 'UTF-8'));
},
array_values($attributes),
array_keys($attributes)
)
);
$attributeStrings = [];
$filteredAttributes = array_filter($attributes, 'is_string');

foreach ($filteredAttributes as $key => $value) {
$escapedValue = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
$attributeStrings[] = "$key=\"$escapedValue\"";
}

return implode(' ', $attributeStrings);
}

public static function buildInlineStyle($styles)
Expand Down

0 comments on commit 838fc5a

Please sign in to comment.