PurgeAsyncCache::createTagChunks()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 13
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 17
rs 9.8333
1
<?php
2
declare(strict_types=1);
3
4
namespace IntegerNet\AsyncVarnish\Model;
5
6
use Magento\CacheInvalidate\Model\PurgeCache as PurgeCache;
7
use IntegerNet\AsyncVarnish\Model\TagRepository as TagRepository;
8
use Magento\Framework\App\Config\ScopeConfigInterface;
9
10
class PurgeAsyncCache
11
{
12
    const VARNISH_PURGE_TAG_GLUE = "|";
13
    const MAX_HEADER_LENGTH_CONFIG_PATH = 'system/full_page_cache/async_varnish/varnish_max_header_length';
14
15
    /**
16
     * @var PurgeCache
17
     */
18
    private $purgeCache;
19
20
    /**
21
     * @var TagRepository
22
     */
23
    private $tagRepository;
24
25
    /**
26
     * @var ScopeConfigInterface
27
     */
28
    private $scopeConfig;
29
30
    public function __construct(
31
        PurgeCache $purgeCache,
32
        ScopeConfigInterface $scopeConfig,
33
        TagRepository $tagRepository
34
    ) {
35
        $this->purgeCache = $purgeCache;
36
        $this->scopeConfig = $scopeConfig;
37
        $this->tagRepository = $tagRepository;
38
    }
39
40
    private function getMaxHeaderLengthFromConfig()
41
    {
42
        return $this->scopeConfig->getValue(self::MAX_HEADER_LENGTH_CONFIG_PATH);
43
    }
44
45
    private function createTagChunks(array $tags): array
46
    {
47
        $maxHeaderLength = $this->getMaxHeaderLengthFromConfig();
48
        $tagChunks = [];
49
        $index = 0;
50
        foreach ($tags as $tag) {
51
            $nextChunkString = (isset($tagChunks[$index])
52
                    ? $tagChunks[$index] . self::VARNISH_PURGE_TAG_GLUE
53
                    : '') . $tag;
54
            if (strlen($nextChunkString) <= $maxHeaderLength) {
55
                $tagChunks[$index] = $nextChunkString;
56
            } else {
57
                $index ++;
58
                $tagChunks[$index] = $tag;
59
            }
60
        }
61
        return $tagChunks;
62
    }
63
64
    /**
65
     * @throws \Zend_Db_Statement_Exception
66
     * @throws \Exception
67
     */
68
    public function run():int
69
    {
70
        $tags = $this->tagRepository->getAll();
71
72
        if (!empty($tags)) {
73
            $tagChunks = $this->createTagChunks($tags);
74
            foreach ($tagChunks as $tagChunk) {
75
                $this->purgeCache->sendPurgeRequest($tagChunk);
76
            }
77
        }
78
79
        if ($lastUsedId = $this->tagRepository->getLastUsedId()) {
80
            $this->tagRepository->deleteUpToId($lastUsedId);
81
        }
82
        return count($tags);
83
    }
84
}
85