Passed
Push — latest ( 03f783...d7ba96 )
by Mark
02:37
created

Dataset::archive()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace UnicornFail\Emoji;
6
7
use UnicornFail\Emoji\Exception\FileNotFoundException;
8
use UnicornFail\Emoji\Exception\MalformedArchiveException;
9
use UnicornFail\Emoji\Exception\UnarchiveException;
10
use UnicornFail\Emoji\Util\ImmutableArrayIterator;
11
use UnicornFail\Emoji\Util\Normalize;
12
13
final class Dataset extends ImmutableArrayIterator
14
{
15
    public const DIRECTORY = __DIR__ . '/../datasets';
16
17
    /** @var array<string, Dataset> */
18
    protected $indices = [];
19
20
    /**
21
     * @param mixed $emojis
22
     */
23 33
    public function __construct($emojis = [], string $index = 'hexcode')
24
    {
25 33
        parent::__construct(Normalize::dataset($emojis, $index), \ArrayIterator::ARRAY_AS_PROPS | \ArrayIterator::STD_PROP_LIST);
26 33
    }
27
28 621
    public static function unarchive(string $filename): self
29
    {
30 621
        if (! \file_exists($filename)) {
31 417
            throw new FileNotFoundException($filename);
32
        }
33
34
        if (
35 204
            ! ($contents = \file_get_contents($filename)) ||
36 204
            ! ($decoded = \gzdecode($contents))
37
        ) {
38 3
            throw new UnarchiveException($filename);
39
        }
40
41
        try {
42 201
            $dataset = \unserialize($decoded);
43 3
        } catch (\Throwable $throwable) {
44 3
            throw new MalformedArchiveException($filename, $throwable);
45
        }
46
47 198
        if (! $dataset instanceof Dataset) {
48 3
            throw new MalformedArchiveException($filename);
49
        }
50
51 195
        return $dataset;
52
    }
53
54
    /**
55
     * @param string[] $indices
56
     *
57
     * @return false|string
58
     */
59 3
    public function archive(array $indices = Parser::INDICES)
60
    {
61 3
        foreach ($indices as $index) {
62 3
            $this->indexBy($index);
63
        }
64
65 3
        $serialize = \serialize($this);
66
67 3
        return \gzencode($serialize, 9);
68
    }
69
70 9
    public function filter(callable $callback): Dataset
71
    {
72 9
        return new self(new \CallbackFilterIterator($this, $callback));
73
    }
74
75 87
    public function indexBy(string $index = 'hexcode'): Dataset
76
    {
77 87
        if (! isset($this->indices[$index])) {
78 6
            $this->indices[$index] = new self($this, $index);
79
        }
80
81 87
        return $this->indices[$index];
82
    }
83
}
84