Passed
Push — master ( a6819e...14f211 )
by
unknown
09:28 queued 02:18
created

BaseInterface::fromCachedFile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 12
rs 10
1
<?php
2
3
namespace MySociety\TheyWorkForYou\DataClass;
4
5
use function Rutek\Dataclass\transform;
6
7
trait BaseInterface {
8
    /**
9
     * @return static
10
     */
11
    public static function fromJson(string $json) {
12
        $data = json_decode($json, true);
13
        try {
14
            return transform(static::class, $data);
15
        } catch (\Exception $transformException) {
16
            echo json_encode($transformException, JSON_PRETTY_PRINT);
17
            throw $transformException;
18
        }
19
    }
20
21
    /**
22
     * @return static
23
     */
24
    public static function fromFile(string $file) {
25
        $content = file_get_contents($file);
26
        return static::fromJson($content);
27
    }
28
29
    /**
30
     * @return static|null
31
     */
32
    public static function fromCachedFile(string $file) {
33
        if (!file_exists($file)) {
34
            return null;
35
        }
36
37
        $memcache = new \MySociety\TheyWorkForYou\Memcache();
38
        $content = $memcache->get($file);
39
        if (!$content) {
0 ignored issues
show
introduced by
The condition $content is always false.
Loading history...
40
            $content = file_get_contents($file);
41
            $memcache->set($file, $content, 60 * 60 * 1); // Cache for 1 hour
42
        }
43
        return static::fromJson($content);
44
    }
45
46
    /**
47
     * @return static
48
     */
49
    public static function fromArray(array $data) {
50
        try {
51
            return transform(static::class, $data);
52
        } catch (\Exception $transformException) {
53
            echo json_encode($transformException, JSON_PRETTY_PRINT);
54
            throw $transformException;
55
        }
56
    }
57
}
58