MemoryFile::map()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 * This file is part of the mucts/pinyin.
4
 *
5
 * This source file is subject to the MIT license that is bundled
6
 * with this source code in the file LICENSE.
7
 *
8
 * @version 1.0
9
 * @author herry<[email protected]>
10
 * @copyright © 2020 MuCTS.com All Rights Reserved.
11
 */
12
13
namespace MuCTS\Pinyin\Loaders;
14
15
use Closure;
16
use MuCTS\Pinyin\Exceptions\PinyinException;
17
use MuCTS\Pinyin\Interfaces\DictLoader;
18
use MuCTS\Support\Arr;
19
20
class MemoryFile implements DictLoader
21
{
22
23
    /**
24
     * Words segment name.
25
     *
26
     * @var string
27
     */
28
    protected string $segmentName = 'words_*';
29
30
    /**
31
     * Segment files.
32
     *
33
     * @var array
34
     */
35
    protected array $segments = [];
36
37
    /**
38
     * Surname cache.
39
     *
40
     * @var array
41
     */
42
    protected array $surnames = [];
43
44
    /**
45
     * Constructor.
46
     *
47
     * @param string $path
48
     * @throws PinyinException
49
     */
50
    public function __construct($path)
51
    {
52
        $segments = glob($path . '/' . $this->segmentName);
53
        if ($segments == false) {
54
            throw new PinyinException('CC-CEDICT dictionary data does not exist');
55
        }
56
        while (($segment = array_shift($segments))) {
57
            $this->segments[] = Arr::wrap(include $segment);
58
        }
59
        $surnames = $path . '/surnames';
60
        if (file_exists($surnames)) {
61
            $this->surnames = Arr::wrap(include $surnames);
62
        }
63
    }
64
65
    /**
66
     * Load dict.
67
     *
68
     * @param Closure $callback
69
     */
70
    public function map(Closure $callback)
71
    {
72
        foreach ($this->segments as $dictionary) {
73
            $callback($dictionary);
74
        }
75
    }
76
77
    /**
78
     * Load surname dict.
79
     *
80
     * @param Closure $callback
81
     */
82
    public function mapSurname(Closure $callback)
83
    {
84
        $callback($this->surnames);
85
    }
86
}
87