Skip to content

Commit a8dc475

Browse files
mikadamczykGrabowskiM
authored andcommitted
Code improvements
1 parent 78cba96 commit a8dc475

File tree

1 file changed

+33
-10
lines changed

1 file changed

+33
-10
lines changed

src/lib/Twig/Components/OverflowList.php

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
namespace Ibexa\DesignSystemTwig\Twig\Components;
1010

11+
use InvalidArgumentException;
1112
use Symfony\Component\OptionsResolver\OptionsResolver;
1213
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
1314
use Symfony\UX\TwigComponent\Attribute\ExposeInTemplate;
@@ -39,7 +40,28 @@ public function validate(array $props): array
3940
$resolver
4041
->define('items')
4142
->allowedTypes('array')
42-
->default([]);
43+
->default([])
44+
->normalize(static function ($options, $value): array {
45+
if (!is_array($value) || !array_is_list($value)) {
46+
throw new InvalidArgumentException('Property "items" must be a list (sequential array).');
47+
}
48+
49+
foreach ($value as $i => $item) {
50+
if (!is_array($item)) {
51+
throw new InvalidArgumentException(sprintf('items[%d] must be an array, %s given.', $i, get_debug_type($item)));
52+
}
53+
foreach (array_keys($item) as $key) {
54+
if (!is_string($key)) {
55+
throw new InvalidArgumentException(sprintf('items[%d] must use string keys.', $i));
56+
}
57+
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $key)) {
58+
throw new InvalidArgumentException(sprintf('Invalid key "%s" in items[%d].', $key, $i));
59+
}
60+
}
61+
}
62+
63+
return $value;
64+
});
4365
$resolver
4466
->define('itemTemplateProps')
4567
->allowedTypes('array')
@@ -54,17 +76,18 @@ public function validate(array $props): array
5476
#[ExposeInTemplate('item_template_props')]
5577
public function getItemTemplateProps(): array
5678
{
57-
$itemPropsNames = array_keys($this->items[0]);
58-
59-
$itemPropsPatterns = array_map(
60-
static fn (string $name): string => '{{ ' . $name . ' }}',
61-
$this->itemTemplateProps
62-
);
79+
if (empty($this->items)) {
80+
return [];
81+
}
6382

64-
$props = array_combine($itemPropsNames, $itemPropsPatterns);
83+
$allKeys = [];
84+
foreach ($this->items as $item) {
85+
$allKeys = array_unique([...$allKeys, ...array_keys($item)]);
86+
}
6587

66-
if (empty($props)) {
67-
return [];
88+
$props = [];
89+
foreach ($allKeys as $name) {
90+
$props[$name] = '{{ ' . $name . ' }}';
6891
}
6992

7093
return $props;

0 commit comments

Comments
 (0)