| 1 |
<?php |
| 2 |
|
| 3 |
namespace Minify\StaticService; |
| 4 |
|
| 5 |
/** |
| 6 |
* Build a URI for the static cache |
| 7 |
* |
| 8 |
* @param string $static_uri E.g. "/min/static" |
| 9 |
* @param string $query E.g. "b=scripts&f=1.js,2.js" |
| 10 |
* @param string $type "css" or "js" |
| 11 |
* @return string |
| 12 |
*/ |
| 13 |
function build_uri($static_uri, $query, $type) |
| 14 |
{ |
| 15 |
$static_uri = rtrim($static_uri, '/'); |
| 16 |
$query = ltrim($query, '?'); |
| 17 |
|
| 18 |
$ext = ".$type"; |
| 19 |
if (substr($query, - strlen($ext)) !== $ext) { |
| 20 |
$query .= "&z=$ext"; |
| 21 |
} |
| 22 |
|
| 23 |
$cache_time = get_cache_time(); |
| 24 |
|
| 25 |
return "$static_uri/$cache_time/$query"; |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Get the name of the current cache directory within static/. E.g. "1467089473" |
| 30 |
* |
| 31 |
* @param bool $auto_create Automatically create the directory if missing? |
| 32 |
* @return null|string null if missing or can't create |
| 33 |
*/ |
| 34 |
function get_cache_time($auto_create = true) |
| 35 |
{ |
| 36 |
foreach (scandir(__DIR__) as $entry) { |
| 37 |
if (ctype_digit($entry)) { |
| 38 |
return $entry; |
| 39 |
break; |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
if (!$auto_create) { |
| 44 |
return null; |
| 45 |
} |
| 46 |
|
| 47 |
$time = (string)time(); |
| 48 |
if (!mkdir(__DIR__ . "/$time")) { |
| 49 |
return null; |
| 50 |
} |
| 51 |
|
| 52 |
return $time; |
| 53 |
} |
| 54 |
|
| 55 |
function flush_cache() |
| 56 |
{ |
| 57 |
$time = get_cache_time(false); |
| 58 |
if ($time) { |
| 59 |
remove_tree(__DIR__ . "/$time"); |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
function remove_tree($dir) |
| 64 |
{ |
| 65 |
$files = array_diff(scandir($dir), array('.', '..')); |
| 66 |
|
| 67 |
foreach ($files as $file) { |
| 68 |
is_dir("$dir/$file") ? remove_tree("$dir/$file") : unlink("$dir/$file"); |
| 69 |
} |
| 70 |
|
| 71 |
return rmdir($dir); |
| 72 |
} |
| 73 |
|