Completed
Push — dependabot/npm_and_yarn/vue-se... ( e78fac...845b60 )
by
unknown
358:07 queued 338:52
created

Memoize   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 7
eloc 14
c 2
b 1
f 0
dl 0
loc 38
ccs 17
cts 17
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 11 2
A __construct() 0 3 1
A clear() 0 3 1
A convertToCachableParameters() 0 9 3
1
<?php
2
3
namespace Thinktomorrow\Chief\Common\Helpers;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
class Memoize
8
{
9
    public static $cache = [];
10
11
    private $baseKey;
12
13 100
    public function __construct($baseKey)
14
    {
15 100
        $this->baseKey = $baseKey;
16 100
    }
17
18 100
    public function run(\Closure $closure, array $parameters = [])
19
    {
20 100
        $cachableParameters = $this->convertToCachableParameters($parameters);
21
22 100
        $cachekey = $this->baseKey.':'.md5(implode('', $cachableParameters));
23
24 100
        if (isset(static::$cache[$cachekey])) {
25 70
            return static::$cache[$cachekey];
26
        }
27
28 100
        return static::$cache[$cachekey] = call_user_func_array($closure, $parameters);
29
    }
30
31 450
    public static function clear()
32
    {
33 450
        static::$cache = [];
34 450
    }
35
36 100
    private function convertToCachableParameters(array $parameters)
37
    {
38 100
        foreach ($parameters as $key => $value) {
39 97
            if ($value instanceof Model) {
40 97
                $parameters[$key] = get_class($value) . '@' . $value->id;
41
            }
42
        }
43
44 100
        return $parameters;
45
    }
46
}
47