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

Cache::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 11
ccs 0
cts 7
cp 0
crap 6
rs 10
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