Passed
Push — master ( e32a81...12baf4 )
by Antonio Carlos
02:26
created

src/Support/Traits/ToArray.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace PragmaRX\Health\Support\Traits;
4
5
use Illuminate\Contracts\Support\Arrayable;
6
7
trait ToArray
8
{
9
    private static $__depth;
10
11
    private static $__maxDepth;
12
13
    /**
14
     * Reset depth and convert object to array.
15
     *
16
     * @param $subject
17
     * @param int $maxDepth
18
     * @return array|null
19
     */
20 1
    public function __toArray($subject, $maxDepth = 3)
21
    {
22 1
        static::$__depth = 0;
23
24 1
        static::$__maxDepth = $maxDepth;
25
26 1
        return $this->___toArray($subject, $maxDepth);
0 ignored issues
show
The call to ToArray::___toArray() has too many arguments starting with $maxDepth.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
27
    }
28
29
    /**
30
     * Convert object to array.
31
     *
32
     * @param $subject
33
     * @return array|null
34
     */
35 1
    public function ___toArray($subject)
36
    {
37 1
        $callback = $this->__getToArrayCallBack();
38
39 1
        return $callback($subject);
40
    }
41
42
    /**
43
     * Generate a callback to transform object to array.
44
     *
45
     * @return \Closure
46
     */
47 1
    public function __getToArrayCallBack()
48
    {
49
        return function ($subject) {
50 1
            static::$__depth++;
51
52 1
            if ($subject instanceof Arrayable) {
53 1
                $subject = $subject->toArray();
54
            }
55
56 1
            if (is_object($subject)) {
57 1
                $subject = get_object_vars($subject);
58
            }
59
60 1
            if (is_array($subject)) {
61 1
                if (static::$__depth <= static::$__maxDepth) {
62 1
                    $subject = array_map(
63 1
                        $this->__getToArrayCallBack(),
64 1
                        $subject
65
                    );
66
                } else {
67 1
                    $subject = null;
68
                }
69
            }
70
71 1
            static::$__depth--;
72
73 1
            return $subject;
74 1
        };
75
    }
76
}
77