1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* FastCGI Cache Bust plugin for Craft CMS 3.x |
4
|
|
|
* |
5
|
|
|
* Bust the Nginx FastCGI Cache when entries are saved or created. |
6
|
|
|
* |
7
|
|
|
* @link https://nystudio107.com |
|
|
|
|
8
|
|
|
* @copyright Copyright (c) 2017 nystudio107 |
|
|
|
|
9
|
|
|
*/ |
|
|
|
|
10
|
|
|
|
11
|
|
|
namespace nystudio107\fastcgicachebust\services; |
12
|
|
|
|
13
|
|
|
use Craft; |
14
|
|
|
use craft\base\Component; |
15
|
|
|
use craft\base\Element; |
16
|
|
|
use craft\elements\Entry; |
17
|
|
|
use craft\helpers\FileHelper; |
18
|
|
|
use nystudio107\fastcgicachebust\FastcgiCacheBust; |
19
|
|
|
use nystudio107\fastcgicachebust\models\Settings; |
20
|
|
|
use yii\base\ErrorException; |
21
|
|
|
|
22
|
|
|
/** |
|
|
|
|
23
|
|
|
* @author nystudio107 |
|
|
|
|
24
|
|
|
* @package FastcgiCacheBust |
|
|
|
|
25
|
|
|
* @since 1.0.0 |
|
|
|
|
26
|
|
|
*/ |
|
|
|
|
27
|
|
|
class Cache extends Component |
28
|
|
|
{ |
29
|
|
|
// Public Methods |
30
|
|
|
// ========================================================================= |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Clears the entirety of the FastCGI Cache |
34
|
|
|
*/ |
|
|
|
|
35
|
|
|
public function clearAll() |
36
|
|
|
{ |
37
|
|
|
/** |
|
|
|
|
38
|
|
|
* @var Settings $settings |
39
|
|
|
*/ |
40
|
|
|
$settings = FastcgiCacheBust::$plugin->getSettings(); |
41
|
|
|
if ($settings !== null && !empty($settings->cachePath)) { |
42
|
|
|
$cacheDirs = explode(',', $settings->cachePath); |
43
|
|
|
foreach ($cacheDirs as $cacheDir) { |
44
|
|
|
$cacheDir = Craft::parseEnv($cacheDir); |
|
|
|
|
45
|
|
|
$cacheDir = trim($cacheDir); |
|
|
|
|
46
|
|
|
try { |
47
|
|
|
FileHelper::clearDirectory($cacheDir); |
48
|
|
|
} catch (ErrorException $e) { |
49
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
50
|
|
|
} |
51
|
|
|
Craft::info( |
52
|
|
|
Craft::t( |
53
|
|
|
'fastcgi-cache-bust', |
54
|
|
|
'FastCGI Cache busted: `' . $cacheDir |
55
|
|
|
), |
56
|
|
|
__METHOD__ |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Determine whether the cache should be busted or not based on the $element |
64
|
|
|
* |
65
|
|
|
* @param Element $element |
|
|
|
|
66
|
|
|
* |
67
|
|
|
* @return bool |
68
|
|
|
*/ |
69
|
|
|
public function shouldBustCache(Element $element): bool |
70
|
|
|
{ |
71
|
|
|
$bustCache = true; |
72
|
|
|
// Only bust the cache if the element is ENABLED or LIVE |
73
|
|
|
if (($element->getStatus() !== Element::STATUS_ENABLED) |
74
|
|
|
&& ($element->getStatus() !== Entry::STATUS_LIVE) |
75
|
|
|
) { |
76
|
|
|
$bustCache = false; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return $bustCache; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|