Test Failed
Push — ft/fields-refactor ( 9f047d...e6f9ef )
by Ben
315:03 queued 288:46
created

Memoize   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 7
eloc 13
dl 0
loc 36
rs 10
c 2
b 1
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 11 2
A __construct() 0 3 1
A convertToCachableParameters() 0 7 3
A clear() 0 3 1
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
    public function __construct($baseKey)
14
    {
15
        $this->baseKey = $baseKey;
16
    }
17
18
    public function run(\Closure $closure, array $parameters = [])
19
    {
20
        $cachableParameters = $this->convertToCachableParameters($parameters);
21
22
        $cachekey = $this->baseKey.':'.md5(implode('', $cachableParameters));
23
24
        if (isset(static::$cache[$cachekey])) {
25
            return static::$cache[$cachekey];
26
        }
27
28
        return static::$cache[$cachekey] = call_user_func_array($closure, $parameters);
29
    }
30
31
    public static function clear()
32
    {
33
        static::$cache = [];
34
    }
35
36
    private function convertToCachableParameters(array $parameters)
37
    {
38
        foreach($parameters as $key => $value) {
39
            if($value instanceof Model) $parameters[$key] = get_class($value) . '@' . $value->id;
40
        }
41
42
        return $parameters;
43
    }
44
}
45