GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#79)
by xiaobei
02:06
created

Pinyin::setLoader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the overtrue/pinyin.
5
 *
6
 * (c) 2016 overtrue <[email protected]>
7
 */
8
9
namespace Overtrue\Pinyin;
10
11
use InvalidArgumentException;
12
13
/**
14
 * Chinese to pinyin translator.
15
 *
16
 * @author    overtrue <[email protected]>
17
 * @copyright 2015 overtrue <[email protected]>
18
 *
19
 * @link      https://github.com/overtrue/pinyin
20
 * @link      http://overtrue.me
21
 */
22
23 1
define('PINYIN_NONE', 'none');
24 1
define('PINYIN_ASCII', 'ascii');
25 1
define('PINYIN_UNICODE', 'unicode');
26
27
class Pinyin
28
{
29
    const NONE = 'none';
30
    const ASCII = 'ascii';
31
    const UNICODE = 'unicode';
32
33
    /**
34
     * Dict loader.
35
     *
36
     * @var \Overtrue\Pinyin\DictLoaderInterface
37
     */
38
    protected $loader;
39
40
    /**
41
     * Punctuations map.
42
     *
43
     * @var array
44
     */
45
    protected $punctuations = array(
46
        ',' => ',',
47
        '。' => '.',
48
        '!' => '!',
49
        '?' => '?',
50
        ':' => ':',
51
        '“' => '"',
52
        '”' => '"',
53
        '‘' => "'",
54
        '’' => "'",
55
    );
56
57
    /**
58
     * Constructor.
59
     *
60
     * @param string $loaderName
61
     */
62 19
    public function __construct($loaderName = null)
63
    {
64 19
        $this->loader = $loaderName ?: 'Overtrue\\Pinyin\\FileDictLoader';
0 ignored issues
show
Documentation Bug introduced by
It seems like $loaderName ?: 'Overtrue\\Pinyin\\FileDictLoader' of type string is incompatible with the declared type object<Overtrue\Pinyin\DictLoaderInterface> of property $loader.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
65 19
    }
66
67
    /**
68
     * Convert string to pinyin.
69
     *
70
     * @param string $string
71
     * @param string $option
72
     *
73
     * @return array
74
     */
75 8
    public function convert($string, $option = self::NONE)
76
    {
77 8
        $pinyin = $this->romanize($string);
78
79 8
        return $this->splitWords($pinyin, $option);
80
    }
81
82
    /**
83
     * Convert string (person name) to pinyin.
84
     *
85
     * @param string $stringName
86
     * @param string $option
87
     *
88
     * @return array
89
     */
90 2
    public function name($stringName, $option = self::NONE)
91
    {
92 2
        $pinyin = $this->romanize($stringName, true);
93
94 2
        return $this->splitWords($pinyin, $option);
95
    }
96
97
    /**
98
     * Return a pinyin permalink from string.
99
     *
100
     * @param string $string
101
     * @param string $delimiter
102
     *
103
     * @return string
104
     */
105 2
    public function permalink($string, $delimiter = '-')
106
    {
107 2
        if (!in_array($delimiter, array('_', '-', '.', ''), true)) {
108 2
            throw new InvalidArgumentException("Delimiter must be one of: '_', '-', '', '.'.");
109
        }
110
111 2
        return implode($delimiter, $this->convert($string, false));
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
112
    }
113
114
    /**
115
     * Return first letters.
116
     *
117
     * @param string $string
118
     * @param string $delimiter
119
     *
120
     * @return string
121
     */
122 2
    public function abbr($string, $delimiter = '')
123
    {
124
        return implode($delimiter, array_map(function ($pinyin) {
125 2
            return $pinyin[0];
126 2
        }, $this->convert($string, false)));
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
127
    }
128
129
    /**
130
     * Chinese phrase to pinyin.
131
     *
132
     * @param string $string
133
     * @param string $delimiter
134
     * @param string $option
135
     *
136
     * @return string
137 9
     */
138
    public function phrase($string, $delimiter = ' ', $option = self::NONE) {
139 9
        return implode($delimiter, array_map(function ($pinyin) {
140 9
            return $pinyin;
141 9
        }, $this->convert($string, $option)));
142
    }
143 9
    
144
    /**
145 9
     * Chinese to pinyin sentense.
146 9
     *
147
     * @param string $sentence
148 9
     * @param bool $withTone
149
     *
150
     * @return string
151
     */
152
    public function sentence($sentence, $withTone = false)
153
    {
154
        $marks = array_keys($this->punctuations);
155
        $punctuationsRegex = preg_quote(implode(array_merge($marks, $this->punctuations)), '/');
156
        $regex = '/[^üāēīōūǖáéíóúǘǎěǐǒǔǚàèìòùǜa-z0-9'.$punctuationsRegex.'\s_]+/iu';
157
158 1
        $pinyin = preg_replace($regex, '', $this->romanize($sentence));
159
160 1
        $punctuations = array_merge($this->punctuations, array("\t" => ' ', '  ' => ' '));
161
        $pinyin = trim(str_replace(array_keys($punctuations), $punctuations, $pinyin));
162 1
163
        return $withTone ? $pinyin : $this->format($pinyin, false);
164
    }
165
166
    /**
167
     * Loader setter.
168
     *
169
     * @param \Overtrue\Pinyin\DictLoaderInterface $loader
170 19
     *
171
     * @return $this
172 19
     */
173 18
    public function setLoader(DictLoaderInterface $loader)
174
    {
175 18
        $this->loader = $loader;
176 18
177 18
        return $this;
178
    }
179 19
180
    /**
181
     * Return dict loader,.
182
     *
183
     * @return \Overtrue\Pinyin\DictLoaderInterface
184
     */
185
    public function getLoader()
186
    {
187
        if (!($this->loader instanceof DictLoaderInterface)) {
188
            $dataDir = dirname(__DIR__).'/data/';
189 19
190
            $loaderName = $this->loader;
191
            $this->loader = new $loaderName($dataDir);
192 8
        }
193 19
194
        return $this->loader;
195 19
    }
196
197
    /**
198
     * Preprocess.
199
     *
200
     * @param string $string
201
     *
202
     * @return string
203
     */
204
    protected function prepare($string)
205
    {
206 19
        $string = preg_replace_callback('~[a-z0-9_-]+~i', function ($matches) {
207
            return "\t".$matches[0];
208 19
        }, $string);
209
210 19
        return preg_replace("~[^\p{Han}\p{P}\p{Z}\p{M}\p{N}\p{L}\t]~u", '', $string);
211
    }
212 19
213 2
    /**
214 2
     * Convert Chinese to pinyin.
215
     *
216
     * @param string $string
217 19
     * @param bool   $isName
218 19
     *
219
     * @return string
220 19
     */
221
    protected function romanize($string, $isName = false)
222
    {
223
        $string = $this->prepare($string);
224
225
        $dictLoader = $this->getLoader();
226
227
        if ($isName) {
228
            $string = $this->convertSurname($string, $dictLoader);
229
        }
230
231
        $dictLoader->map(function ($dictionary) use (&$string) {
232
            $string = strtr($string, $dictionary);
233 2
        });
234 2
235 2
        return $string;
236 2
    }
237 2
238
    /**
239 2
     * Convert Chinese Surname to pinyin.
240 2
     *
241
     * @param string                               $string
242 2
     * @param \Overtrue\Pinyin\DictLoaderInterface $dictLoader
243
     *
244
     * @return string
245
     */
246
    protected function convertSurname($string, $dictLoader)
247
    {
248
        $dictLoader->mapSurname(function ($dictionary) use (&$string) {
249
            foreach ($dictionary as $surname => $pinyin) {
250
                if (strpos($string, $surname) === 0) {
251
                    $string = $pinyin.mb_substr($string, mb_strlen($surname, 'UTF-8'), mb_strlen($string, 'UTF-8') - 1, 'UTF-8');
252
                    break;
253 10
                }
254
            }
255 10
        });
256
257 10
        return $string;
258 8
    }
259 8
260 8
    /**
261 8
     * Split pinyin string to words.
262
     *
263 10
     * @param string $pinyin
264
     * @param string $option
265
     *
266
     * @return array
267
     */
268
    public function splitWords($pinyin, $option)
269
    {
270
        $split = array_filter(preg_split('/[^üāēīōūǖáéíóúǘǎěǐǒǔǚàèìòùǜa-z\d]+/iu', $pinyin));
271
272
        if ($option !== self::UNICODE) {
273
            foreach ($split as $index => $pinyin) {
274 15
                $split[$index] = $this->format($pinyin, $option === self::ASCII);
275
            }
276
        }
277 15
278 15
        return array_values($split);
279 15
    }
280 15
281 15
    /**
282 15
     * Format.
283
     *
284 15
     * @param string $pinyin
285 15
     * @param bool   $tone
286 14
     *
287 14
     * @return string
288 15
     */
289
    protected function format($pinyin, $tone = false)
290 15
    {
291
        $replacements = array(
292
            'üē' => array('ue', 1), 'üé' => array('ue', 2), 'üě' => array('ue', 3), 'üè' => array('ue', 4),
293
            'ā' => array('a', 1), 'ē' => array('e', 1), 'ī' => array('i', 1), 'ō' => array('o', 1), 'ū' => array('u', 1), 'ǖ' => array('v', 1),
294
            'á' => array('a', 2), 'é' => array('e', 2), 'í' => array('i', 2), 'ó' => array('o', 2), 'ú' => array('u', 2), 'ǘ' => array('v', 2),
295
            'ǎ' => array('a', 3), 'ě' => array('e', 3), 'ǐ' => array('i', 3), 'ǒ' => array('o', 3), 'ǔ' => array('u', 3), 'ǚ' => array('v', 3),
296
            'à' => array('a', 4), 'è' => array('e', 4), 'ì' => array('i', 4), 'ò' => array('o', 4), 'ù' => array('u', 4), 'ǜ' => array('v', 4),
297
        );
298
299
        foreach ($replacements as $unicde => $replacements) {
300
            if (false !== strpos($pinyin, $unicde)) {
301
                $pinyin = str_replace($unicde, $replacements[0], $pinyin).($tone ? $replacements[1] : '');
302
            }
303
        }
304
305
        return $pinyin;
306
    }
307
}
308