File size: 2,026 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php

namespace Mautic\ApiBundle\Helper;

use Doctrine\ORM\Tools\Pagination\Paginator;

class EntityResultHelper
{
    /**
     * @param array<mixed>|Paginator<mixed> $results
     * @param callable|null                 $callback
     *
     * @return array<mixed>|\ArrayObject<int,mixed>
     */
    public function getArray($results, $callback = null)
    {
        $entities = [];

        // we have to convert them from paginated proxy functions to entities in order for them to be
        // returned by the serializer/rest bundle
        foreach ($results as $key => $entityRow) {
            $entities[$key] = $this->getEntityData($entityRow);

            if (is_callable($callback)) {
                $callback($entities[$key]);
            }
        }

        // solving array/object discrepancy for empty values
        if ($this->isKeyedById($results) && empty($entities)) {
            $entities = new \ArrayObject();
        }

        return $entities;
    }

    /**
     * @param mixed $entityRow
     *
     * @return mixed
     */
    private function getEntityData($entityRow)
    {
        if (is_array($entityRow) && isset($entityRow[0])) {
            return $this->getDataForArray($entityRow);
        }

        return $entityRow;
    }

    /**
     * @param array $array
     *
     * @return mixed
     */
    private function getDataForArray($array)
    {
        if (is_object($array[0])) {
            return $this->getDataForObject($array);
        }

        return $array[0];
    }

    /**
     * @param object $object
     *
     * @return mixed
     */
    private function getDataForObject($object)
    {
        foreach ($object as $key => $value) {
            if (0 === $key) {
                continue;
            }

            $object[0]->$key = $value;
        }

        return $object[0];
    }

    /**
     * @param array<mixed>|Paginator<mixed> $results
     */
    private function isKeyedById($results): bool
    {
        return !$results instanceof Paginator;
    }
}