Completed
Push — master ( f13667...6d3ced )
by Sergey
04:50
created

Cache::init()   C

Complexity

Conditions 7
Paths 2

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 32
cts 32
cp 1
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 26
nc 2
nop 0
crap 7
1
<?php
2
/**
3
 * Yii 2 PHP file cache
4
 *
5
 * @see       https://github.com/sergeymakinen/yii2-php-file-cache
6
 * @copyright Copyright (c) 2016-2017 Sergey Makinen (https://makinen.ru)
7
 * @license   https://github.com/sergeymakinen/yii2-php-file-cache/blob/master/LICENSE MIT License
8
 */
9
10
namespace sergeymakinen\yii\phpfilecache;
11
12
use yii\caching\FileCache;
13
use yii\helpers\VarDumper;
14
15
/**
16
 * Cache implements a cache component using PHP files.
17
 */
18
class Cache extends FileCache
19
{
20
    /**
21
     * @inheritDoc
22
     */
23
    public $cacheFileSuffix = '.php';
24
25
    /**
26
     * @inheritDoc
27
     */
28 29
    public function init()
29
    {
30 29
        parent::init();
31 29
        if ($this->serializer === null) {
32 29
            $this->serializer = [
33
                function ($value) {
34 26
                    if ($value[0] instanceof ValueWithBootstrap) {
35 15
                        if ($value[0]->bootstrap instanceof \Closure) {
36 10
                            $bootstrap = '';
37 10
                            $namespaces = $this->extractClosureNamespaces($value[0]->bootstrap);
38 10
                            if ($namespaces['namespace'] !== null) {
39 10
                                $bootstrap .= 'namespace ' . $namespaces['namespace'] . ";\n\n";
40 10
                            }
41 10
                            foreach ($namespaces['uses'] as $alias => $namespace) {
42 10
                                $bootstrap .= 'use ' . $namespace;
43 10
                                if (is_string($alias)) {
44 5
                                    $bootstrap .= ' as ' . $alias;
45 5
                                }
46 10
                                $bootstrap .= ";\n";
47 10
                            }
48 10
                            $bootstrap .= 'call_user_func(' . VarDumper::export($value[0]->bootstrap) . ');';
49 10
                        } else {
50 5
                            $bootstrap = $value[0]->bootstrap;
51
                        }
52 15
                        $bootstrap = trim($bootstrap) . "\n\n";
53 15
                        $value[0] = $value[0]->value;
54 15
                    } else {
55 11
                        $bootstrap = '';
56
                    }
57 26
                    return "<?php\n\n{$bootstrap}return " . VarDumper::export($value) . ";\n";
58 29
                },
59 29
                function ($value) {
60 26
                    return $value;
61 29
                },
62
            ];
63 29
        }
64 29
    }
65
66
    /**
67
     * @inheritDoc
68
     */
69 28
    protected function getValue($key)
70
    {
71 28
        $cacheFile = $this->getCacheFile($key);
72 28
        if (@filemtime($cacheFile) > time()) {
73
            /** @noinspection PhpIncludeInspection */
74 27
            $cacheValue = @include $cacheFile;
75 27
            if (is_array($cacheValue) && array_key_exists(0, $cacheValue)) {
76 26
                return $cacheValue;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $cacheValue; (array) is incompatible with the return type of the parent method yii\caching\FileCache::getValue of type string|false.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
77
            }
78 1
        }
79
80 3
        return false;
81
    }
82
83
    /**
84
     * Returns Closure's namespace and uses.
85
     * @param \Closure $closure
86
     * @return array
87
     */
88 11
    private function extractClosureNamespaces(\Closure $closure)
89
    {
90 11
        $function = new \ReflectionFunction($closure);
91 11
        if ($function->getFileName() === false || strpos($function->getFileName(), 'eval()\'d code') !== false) {
92
            return [
93 1
                'namespace' => null,
94 1
                'uses' => [],
95 1
            ];
96
        }
97
98 11
        $tokens = token_get_all(implode(array_slice(file($function->getFileName()), 0, $function->getEndLine())));
99 11
        return $this->extractNamespaces($tokens);
100
    }
101
102
    /**
103
     * Extracts namespace and uses from PHP tokens.
104
     * @param array $tokens
105
     * @return array
106
     */
107 11
    private function extractNamespaces(array $tokens)
108
    {
109 11
        $closureNamespace = null;
110 11
        $closureUses = [];
111 11
        $state = null;
112 11
        $namespace = null;
113 11
        $alias = null;
114 11
        foreach ($tokens as $token) {
115 11
            if (is_array($token)) {
116 11
                if ($state === null && ($token[0] === T_NAMESPACE || $token[0] === T_USE)) {
117 11
                    $state = $token[0];
118 11
                    $namespace = '';
119 11
                } elseif ($state === T_USE && $alias === null && $token[0] === T_AS) {
120 6
                    $alias = '';
121 11
                } elseif ($state !== null && ($token[0] === T_STRING || $token[0] === T_NS_SEPARATOR)) {
122 11
                    if ($alias !== null) {
123 6
                        $alias .= $token[1];
124 6
                    } else {
125 11
                        $namespace .= $token[1];
126
                    }
127 11
                }
128 11
            } else {
129 11
                if ($state !== null && ($token === ';' || $token === '{')) {
130 11
                    if ($alias === null) {
131 11
                        if ($state === T_NAMESPACE) {
132 11
                            $closureNamespace = $namespace;
133 11
                            $closureUses = [];
134 11
                        } else {
135 11
                            $closureUses[] = $namespace;
136
                        }
137 11
                    } else {
138 6
                        $closureUses[$alias] = $namespace;
139 6
                        $alias = null;
140
                    }
141 11
                    $state = null;
142 11
                    $namespace = null;
143 11
                } elseif ($state === T_USE && $token === ',') {
144 6
                    if ($alias === null) {
145 6
                        $closureUses[] = $namespace;
146 6
                    } else {
147 6
                        $closureUses[$alias] = $namespace;
148 6
                        $alias = null;
149
                    }
150 6
                    $namespace = null;
151 6
                }
152
            }
153 11
        }
154
        return [
155 11
            'namespace' => $closureNamespace,
156 11
            'uses' => $closureUses,
157 11
        ];
158
    }
159
}
160