Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.86% covered (success)
92.86%
13 / 14
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
JsonArrayHelper
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
2 / 2
10
100.00% covered (success)
100.00%
1 / 1
 toIntList
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 filterInts
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5/** @license For full copyright and license information, please see the LICENSE.md file. */
6
7namespace App\Shared\Utils;
8
9defined('AMMONLY_APP') || exit('Direct script access is forbidden.');
10
11/**
12 * Shared JSON and Array Utility Helper.
13 *
14 * Provides optimized helper methods for decoding and sanitizing array data,
15 * such as integer ID lists from JSON columns or HTTP input payloads.
16 *
17 * @package App\Shared\Utils
18 */
19final class JsonArrayHelper
20{
21    /**
22     * Extracts and sanitizes an array of integer IDs from mixed input (array, JSON string, or CSV).
23     *
24     * @param mixed $value Raw input value.
25     * @return array<int, int> Filtered list of integers.
26     */
27    public static function toIntList(mixed $value): array
28    {
29        if (is_array($value)) {
30            return self::filterInts($value);
31        }
32
33        if (is_string($value) && $value !== '' && $value !== '[]') {
34            $decoded = json_decode($value, true);
35            $items = is_array($decoded) ? $decoded : explode(',', $value);
36            return self::filterInts($items);
37        }
38
39        return [];
40    }
41
42    /**
43     * Filters and converts array items to integers.
44     *
45     * @param array<mixed> $items Raw items array.
46     * @return array<int, int> List of integers.
47     */
48    private static function filterInts(array $items): array
49    {
50        $result = [];
51        foreach ($items as $item) {
52            $trimmed = is_string($item) ? trim($item) : $item;
53            if (is_numeric($trimmed)) {
54                $result[] = (int) $trimmed;
55            }
56        }
57
58        return array_values(array_unique($result));
59    }
60}