Passed
Pull Request — main (#152)
by Andrey
12:27
created

Resolvable::resolveCallback()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
rs 10
1
<?php
2
/******************************************************************************
3
 * This file is part of the "andrey-helldar/support" project.                 *
4
 *                                                                            *
5
 * @author Andrey Helldar <[email protected]>                                *
6
 *                                                                            *
7
 * @copyright 2021 Andrey Helldar                                             *
8
 *                                                                            *
9
 * @license MIT                                                               *
10
 *                                                                            *
11
 * @see https://github.com/andrey-helldar/support                             *
12
 *                                                                            *
13
 * For the full copyright and license information, please view the LICENSE    *
14
 * file that was distributed with this source code.                           *
15
 ******************************************************************************/
16
17
namespace Helldar\Support\Concerns;
18
19
trait Resolvable
20
{
21
    protected static $resolved = [];
22
23
    protected static function resolveInstance($instance, ...$parameters)
24
    {
25
        $class = is_object($instance) ? get_class($instance) : $instance;
26
27
        if (isset(self::$resolved[$class])) {
28
            return self::$resolved[$class];
29
        }
30
31
        return self::$resolved[$class] = is_object($instance) ? $instance : new $instance(...$parameters);
32
    }
33
34
    protected static function resolveCallback(string $value, callable $callback)
35
    {
36
        $class = static::getSameClass();
37
38
        if (isset(static::$resolved[$class][$value])) {
39
            return static::$resolved[$class][$value];
40
        }
41
42
        return static::$resolved[$class][$value] = $callback($value);
43
    }
44
45
    protected static function getSameClass(): string
46
    {
47
        return static::class;
48
    }
49
}
50