Passed
Push — master ( 4cb087...e82047 )
by compolom
01:32
created

Cache   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 57
ccs 0
cts 26
cp 0
rs 10
wmc 11

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getCacheIds() 0 6 2
A addChannel() 0 7 2
A __construct() 0 11 2
A getCacheChannels() 0 6 2
A updateCacheIds() 0 4 2
A generateId() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Compolomus\RssReader;
6
7
use SplFileObject;
8
9
class Cache implements CacheInterface
10
{
11
    private SplFileObject $cache;
12
13
    private SplFileObject $cacheIds;
14
15
    private string $cacheFile;
16
17
    private string $cacheIdsFile;
18
19
    public function __construct(string $dir)
20
    {
21
        $this->cacheFile = $dir . '/cacheChannels.txt';
22
        $this->cacheIdsFile = $dir . '/cacheIds.txt';
23
24
        if (!is_dir($dir)) {
25
            mkdir($dir);
26
        }
27
28
        $this->cache = new SplFileObject($this->cacheFile, 'a+b');
29
        $this->cacheIds = new SplFileObject($this->cacheIdsFile, 'a+b');
30
    }
31
32
    public function addChannel(string $url): bool
33
    {
34
        if (!in_array($url, $this->getCacheChannels(), true)) {
35
            return (bool) $this->cache->fwrite($url . PHP_EOL);
36
        }
37
38
        return false;
39
    }
40
41
    public function generateId(string $id): int
42
    {
43
        return crc32($id);
44
    }
45
46
    public function getCacheChannels(): array
47
    {
48
        return file_exists($this->cacheFile) ? file(
49
            $this->cacheFile,
50
            FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
51
        ) : [];
52
    }
53
54
    public function getCacheIds(): array
55
    {
56
        return file_exists($this->cacheIdsFile) ? file(
57
            $this->cacheIdsFile,
58
            FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
59
        ) : [];
60
    }
61
62
    public function updateCacheIds(array $ids): void
63
    {
64
        if (count($ids)) {
65
            $this->cacheIds->fwrite(implode(PHP_EOL, $ids) . PHP_EOL);
66
        }
67
    }
68
}
69