Test Setup Failed
Pull Request — latest (#3)
by Mark
33:50
created

Dataset::unarchive()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 25
rs 9.2222
cc 6
nc 5
nop 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A Dataset::filter() 0 7 1
A Dataset::indexBy() 0 7 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace UnicornFail\Emoji\Dataset;
6
7
use UnicornFail\Emoji\Util\ImmutableArrayIterator;
8
use UnicornFail\Emoji\Util\Normalize;
9
10
/**
11
 * @method Emoji|null current()
12
 * @method Emoji[] getArrayCopy()
13
 */
14
final class Dataset extends ImmutableArrayIterator implements \ArrayAccess, \Countable, \SeekableIterator, \Serializable
15
{
16
    public const DIRECTORY = __DIR__ . '/../../datasets';
17
18
    /** @var string */
19
    private $index;
20
21
    /** @var Dataset[] */
22
    private $indices = [];
23
24
    /**
25
     * @param mixed $emojis
26
     */
27
    public function __construct($emojis = [], string $index = 'hexcode')
28
    {
29
        $this->index = $index;
30
        $normalized  = Normalize::emojis($emojis, $index);
31
        parent::__construct($normalized, \ArrayIterator::ARRAY_AS_PROPS | \ArrayIterator::STD_PROP_LIST);
32
    }
33
34
    /**
35
     * @param callable(Emoji):bool $callback
36
     */
37
    public function filter(callable $callback): Dataset
38
    {
39
        /** @var \Iterator $iterator */
40
        $iterator = $this;
41
        $filter   = new \CallbackFilterIterator($iterator, $callback);
42
43
        return new self($filter);
44
    }
45
46
    public function indexBy(string $index = 'hexcode'): Dataset
47
    {
48
        if (! isset($this->indices[$index])) {
49
            $this->indices[$index] = new self($this, $index);
50
        }
51
52
        return $this->indices[$index];
53
    }
54
55
    /**
56
     * @param string $key
57
     */
58
    public function offsetGet($key): ?Emoji // phpcs:ignore
59
    {
60
        // Normalize shortcodes to match index.
61
        if (\strpos($this->index, 'shortcode') !== false) {
62
            $key = (string) \current(Normalize::shortcodes($key));
63
        }
64
65
        /** @var ?Emoji $emoji */
66
        $emoji = parent::offsetGet($key);
67
68
        return $emoji;
69
    }
70
}
71