Completed
Push — 0713 ( 6118f2 )
by Mikael
02:49
created

CFastTrackCache::setCacheDir()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
rs 9.4285
c 1
b 0
f 0
1
<?php
2
/**
3
 * Enable a fast track cache with a json representation of the image delivery.
4
 *
5
 */
6
class CFastTrackCache
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
7
{
8
    /**
9
     * Cache is disabled to start with.
10
     */
11
    private $enabled = false;
12
13
14
15
    /**
16
     * Path to the cache directory.
17
     */
18
    private $path;
19
20
21
22
    /**
23
     * Filename of current cache item.
24
     */
25
    private $filename;
26
27
28
29
    /**
30
     * Container with items to store as cached item.
31
     */
32
    private $container;
33
34
35
36
    /**
37
     * Enable or disable cache.
38
     *
39
     * @param boolean $enable set to true to enable, false to disable
0 ignored issues
show
Documentation introduced by
There is no parameter named $enable. Did you maybe mean $enabled?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
40
     *
41
     * @return $this
42
     */
43
    public function enable($enabled)
44
    {
45
        $this->enabled = $enabled;
46
        return $this;
47
    }
48
49
50
51
    /**
52
     * Set the path to the cache dir which must exist.
53
     *
54
     * @param string $path to the cache dir.
55
     *
56
     * @throws Exception when $path is not a directory.
57
     *
58
     * @return $this
59
     */
60
    public function setCacheDir($path)
61
    {
62
        if (!is_dir($path)) {
63
            throw new Exception("Cachedir is not a directory.");
64
        }
65
66
        $this->path = rtrim($path, "/");
67
68
        return $this;
69
    }
70
71
72
73
    /**
74
     * Set the filename to store in cache, use the querystring to create that
75
     * filename.
76
     *
77
     * @param array $clear items to clear in $_GET when creating the filename.
78
     *
79
     * @return string as filename created.
80
     */
81
    public function setFilename($clear)
0 ignored issues
show
Coding Style introduced by
setFilename uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
82
    {
83
        $query = $_GET;
84
85
        // Remove parts from querystring that should not be part of filename
86
        foreach ($clear as $value) {
87
            unset($query[$value]);
88
        }
89
90
        arsort($query);
91
        $queryAsString = http_build_query($query);
92
93
        $this->filename = md5($queryAsString);
94
        $this->container["query-string"] = $queryAsString;
95
96
        return $this->filename;
97
    }
98
99
100
101
    /**
102
     * Add header items.
103
     *
104
     * @param string $header add this as header.
105
     *
106
     * @return $this
107
     */
108
    public function addHeader($header)
109
    {
110
        $this->container["header"][] = $header;
111
        return $this;
112
    }
113
114
115
116
    /**
117
     * Add header items on output, these are not output when 304.
118
     *
119
     * @param string $header add this as header.
120
     *
121
     * @return $this
122
     */
123
    public function addHeaderOnOutput($header)
124
    {
125
        $this->container["header-output"][] = $header;
126
        return $this;
127
    }
128
129
130
131
    /**
132
     * Set path to source image to.
133
     *
134
     * @param string $source path to source image file.
135
     *
136
     * @return $this
137
     */
138
    public function setSource($source)
139
    {
140
        $this->container["source"] = $source;
141
        return $this;
142
    }
143
144
145
146
    /**
147
     * Set last modified of source image, use to check for 304.
148
     *
149
     * @param string $lastModified
150
     *
151
     * @return $this
152
     */
153
    public function setLastModified($lastModified)
154
    {
155
        $this->container["last-modified"] = $lastModified;
156
        return $this;
157
    }
158
159
160
161
    /**
162
     * Get filename of cached item.
163
     *
164
     * @return string as filename.
165
     */
166
    public function getFilename()
167
    {
168
        return $this->path . "/" . $this->filename;
169
    }
170
171
172
173
    /**
174
     * Write current item to cache.
175
     *
176
     * @return boolean if cache file was written.
177
     */
178
    public function writeToCache()
179
    {
180
        if (!$this->enabled) {
181
            return false;
182
        }
183
184
        if (is_dir($this->path) && is_writable($this->path)) {
185
            $filename = $this->getFilename();
186
            return file_put_contents($filename, json_encode($this->container)) !== false;
187
        }
188
189
        return false;
190
    }
191
192
193
194
    /**
195
     * Output current item from cache, if available.
196
     *
197
     * @return void
198
     */
199
    public function output()
0 ignored issues
show
Coding Style introduced by
output uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
200
    {
201
        $filename = $this->getFilename();
202
        if (!is_readable($filename)) {
203
            return;
204
        }
205
206
        $item = json_decode(file_get_contents($filename), true);
207
208
        if (!is_readable($item["source"])) {
209
            return;
210
        }
211
212
        foreach ($item["header"] as $value) {
213
            header($value);
214
        }
215
216
        if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])
217
            && strtotime($_SERVER["HTTP_IF_MODIFIED_SINCE"]) == $item["last-modified"]) {
218
            header("HTTP/1.0 304 Not Modified");
219
            debug("fast track 304");
220
            exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method output() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
221
        }
222
223
        foreach ($item["header-output"] as $value) {
224
            header($value);
225
        }
226
227
        readfile($item["source"]);
228
        debug("fast track 200");
229
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method output() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
230
    }
231
}
232