Files
breadcrumb-the-shire/core/Support/helpers/array.php

29 lines
820 B
PHP
Raw Normal View History

<?php
/**
* Normalize loose input into a list of unique positive integer IDs.
*
* Accepts any value: an array of scalars, a single scalar, or null/''.
* Scalars are treated as a single-element list. Non-numeric, empty,
* zero, or negative values are dropped. Input order of the first
* occurrence of each ID is preserved.
*
* Typical use: cleaning POST body arrays like `$request->body('role_ids', [])`
* before handing them to a service or repository.
*
* @return list<int>
*/
function toIntIds(mixed $value): array
{
if ($value === null || $value === '') {
return [];
}
if (!is_array($value)) {
$value = [$value];
}
$ids = array_map('intval', $value);
$ids = array_filter($ids, static fn (int $id): bool => $id > 0);
return array_values(array_unique($ids));
}