Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
17 / 17
Singleton
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
2 / 2
7
100.00% covered (success)
100.00%
17 / 17
 instance
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
8 / 8
 __callStatic
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
9 / 9
1<?php
2
3namespace Amf\Proxy;
4
5use ReflectionClass;
6
7/**
8 * Singleton proxy class.
9 *
10 * This class can be used to proxy function calls from static methods to
11 * a given object.
12 * When extending this class you must specify a fully qualified class name
13 * in the static $classname property
14 *
15 * @template T of object
16 */
17abstract class Singleton
18{
19    /** @var class-string<T> */
20    protected static string $classname;
21
22    /** @var T|null */
23    protected static ?object $instance = null;
24
25    /**
26     * @param T|false|null $instance
27     * @param mixed[] $args
28     * @return T
29     */
30    public static function instance($instance = false, array $args = []): object
31    {
32        if ($instance !== false) {
33            static::$instance = $instance;
34        }
35
36        if (static::$instance === null) {
37            if (!empty($args)) {
38                $reflection = new ReflectionClass(static::$classname);
39                static::$instance = $reflection->newInstanceArgs($args);
40            } else {
41                static::$instance = new static::$classname();
42            }
43        }
44
45        /** @var T */
46        return static::$instance;
47    }
48
49    /**
50     * Function calls proxy method.
51     *
52     * This function should never be called manually. Just call the original
53     * function names as static methods instead.
54     *
55     * @param string $name      The method name
56     * @param mixed[] $arguments The method arguments
57     *
58     * @return mixed The proxied method result
59     */
60    public static function __callStatic(string $name, array $arguments)
61    {
62        $instance = static::instance();
63        $callback = [$instance, $name];
64
65        if (!is_callable($callback) && !method_exists($instance, '__call')) {
66            $class = get_class($instance);
67            $trace = debug_backtrace();
68            $file = $trace[0]['file'];
69            $line = $trace[0]['line'];
70            throw new \BadMethodCallException("Call to undefined method $class::$name() in $file on line $line");
71        }
72        return call_user_func_array($callback, $arguments); // @phpstan-ignore-line
73    }
74}