Passed
Push — master ( f96468...e8dc9f )
by M. Mikkel
03:43
created

CachesController::actionInvalidate()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
c 2
b 0
f 0
nc 6
nop 0
dl 0
loc 27
rs 9.4222
1
<?php
2
3
4
namespace mmikkel\cacheflag\controllers;
5
6
use Craft;
7
use craft\web\Controller;
8
9
use mmikkel\cacheflag\CacheFlag;
10
11
/**
12
 * Class CachesController
13
 * @package mmikkel\cacheflag\controllers
14
 * @since 1.2.0
15
 */
16
class CachesController extends Controller
17
{
18
19
    /** @var bool */
20
    public $allowAnonymous = true;
21
22
    /**
23
     * Invalidate all flagged caches, or caches flagged with one or several particular flags
24
     *
25
     * @return bool
26
     */
27
    public function actionInvalidate(): bool
28
    {
29
        $flags = Craft::$app->getRequest()->getParam('flags', []);
30
31
        if (\is_string($flags)) {
32
            $flags = \preg_replace('/\s+/', '', $flags);
33
            $flags = \array_filter(\explode(',', $flags));
34
        } else if (\is_array($flags)) {
35
            $flags = \array_reduce($flags, function (array $carry, string $flag) {
36
                $flag = \preg_replace('/\s+/', '', $flag);
37
                if (\strlen($flag)) {
38
                    $carry[] = $flag;
39
                }
40
                return $carry;
41
            }, []);
42
        }
43
44
        /** @var array $flags */
45
        if (empty($flags)) {
46
            CacheFlag::getInstance()->cacheFlag->invalidateAllFlaggedCaches();
47
            return true;
48
        }
49
50
        $flags = \array_unique($flags);
51
52
        CacheFlag::getInstance()->cacheFlag->invalidateFlaggedCachesByFlags($flags);
53
        return true;
54
    }
55
}
56