Issues (40)

php-src/Converters/ObjectConverter.php (2 issues)

Severity
1
<?php
2
3
namespace kalanis\Restful\Converters;
4
5
6
use kalanis\Restful\IResource;
7
use stdClass;
8
use Traversable;
9
10
11
/**
12
 * ObjectConverter
13
 * @package kalanis\Restful\Converters
14
 * @template TK of string
15
 * @template TVal of mixed
16
 * @implements IConverter<TK, TVal>
17
 */
18 1
class ObjectConverter implements IConverter
19
{
20
21
    /**
22
     * Converts stdClass and traversable objects in resource to array
23
     * @param array<TK, TVal> $resource
24
     * @return array<TK, TVal>
25
     */
26
    public function convert(array $resource): array
27
    {
28 1
        return (array) $this->parseObjects($resource);
29
    }
30
31
    /**
32
     * Parse objects in resource
33
     * @param array<TK, TVal>|Traversable<TK, TVal>|stdClass $data
34
     * @return array<TK, TVal>
35
     */
36
    protected function parseObjects(array|object $data): array
37
    {
38 1
        if ($data instanceof Traversable) {
0 ignored issues
show
$data is never a sub-type of Traversable.
Loading history...
39 1
            $data = iterator_to_array($data);
40 1
        } elseif ($data instanceof stdClass) {
0 ignored issues
show
$data is never a sub-type of stdClass.
Loading history...
41 1
            $data = (array) $data;
42
        }
43
44 1
        foreach ($data as $key => $value) {
45 1
            if ($value instanceof IResource) {
46 1
                $value = $value->getData();
47
            }
48
49 1
            if ($value instanceof Traversable || $value instanceof stdClass || is_array($value)) {
50 1
                $data[$key] = $this->parseObjects($value);
51
            }
52
        }
53 1
        return $data;
54
    }
55
}
56