Test Setup Failed
Pull Request — latest (#3)
by Mark
34:22
created

Dataset::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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