Skip to content

Commit a0c0f08

Browse files
committed
Define SelectboxItem entity for safe type check.
1 parent ad7214b commit a0c0f08

File tree

2 files changed

+48
-6
lines changed

2 files changed

+48
-6
lines changed

src/SelectboxItem.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Baraja\SelectboxTree;
6+
7+
8+
final class SelectboxItem
9+
{
10+
/** @var int|string */
11+
private $id;
12+
13+
private string $name;
14+
15+
/** @var int|string|null */
16+
private $parentId;
17+
18+
19+
public function __construct($id, string $name, $parentId = null)
20+
{
21+
$this->id = $id;
22+
$this->name = $name;
23+
$this->parentId = $parentId;
24+
}
25+
26+
27+
/**
28+
* @return string[]|int[]|null[]
29+
*/
30+
public function toArray(): array
31+
{
32+
return [
33+
'id' => $this->id,
34+
'name' => $this->name,
35+
'parent_id' => $this->parentId,
36+
];
37+
}
38+
}

src/SelectboxTree.php

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,22 @@ final class SelectboxTree
2626
* | | iMac
2727
* | Windows
2828
*
29-
* @param mixed[][] $data raw database result in format [{"id", "name", "parent_id"}]
29+
* @param mixed[][]|SelectboxItem[] $data raw database result in format [{"id", "name", "parent_id"}]
3030
* @return string[] (id => user haystack)
3131
*/
3232
public function process(array $data): array
3333
{
3434
$categories = [];
3535
foreach ($data as $item) {
36-
$categories[] = [
37-
'id' => $item['id'],
38-
'name' => $this->nameFormatter === null ? (string) $item['name'] : $this->nameFormatter->format($item['name']),
39-
'parent' => $item['parent_id'],
40-
];
36+
if ($item instanceof SelectboxItem) {
37+
$categories[] = $item;
38+
} else {
39+
$categories[] = [
40+
'id' => $item['id'],
41+
'name' => $this->nameFormatter === null ? (string) $item['name'] : $this->nameFormatter->format($item['name']),
42+
'parent' => $item['parent_id'],
43+
];
44+
}
4145
}
4246

4347
$return = [];

0 commit comments

Comments
 (0)