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 (#68)
by
unknown
02:41
created

Pinyin::getLoader()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 9
cts 10
cp 0.9
rs 9.4285
cc 3
eloc 9
nc 3
nop 0
crap 3.009
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 1
define('PINYIN_NONE', 'none');
14 1
define('PINYIN_ASCII', 'ascii');
15 1
define('PINYIN_UNICODE', 'unicode');
16
17
/**
18
 * Chinese to pinyin translator.
19
 *
20
 * @author    overtrue <[email protected]>
21
 * @copyright 2015 overtrue <[email protected]>
22
 *
23
 * @link      https://github.com/overtrue/pinyin
24
 * @link      http://overtrue.me
25
 */
26
class Pinyin
27
{
28
    const NONE = 'none';
29
    const ASCII = 'ascii';
30
    const UNICODE = 'unicode';
31
32
    /**
33
     * Dict loader.
34
     *
35
     * @var \Overtrue\Pinyin\DictLoaderInterface
36
     */
37
    protected $loader;
38
39
    /**
40
     * Punctuations map.
41
     *
42
     * @var array
43
     */
44
    protected $punctuations = array(
45
        ',' => ',',
46
        '。' => '.',
47
        '!' => '!',
48
        '?' => '?',
49
        ':' => ':',
50
        '“' => '"',
51
        '”' => '"',
52
        '‘' => "'",
53
        '’' => "'",
54
    );
55
56
    /**
57
     * Constructor.
58
     *
59
     * @param mixed $loader
60
     */
61 19
    public function __construct($loader = null)
62
    {
63 19
        $this->loader = $loader;
64 19
    }
65
66
    /**
67
     * Convert string to pinyin.
68
     *
69
     * @param string $string
70
     * @param string $option
71
     *
72
     * @return array
73
     */
74 8
    public function convert($string, $option = self::NONE)
75
    {
76 8
        $pinyin = $this->romanize($string);
77
78 8
        return $this->splitWords($pinyin, $option);
79
    }
80
81
    /**
82
     * Convert string (person name) to pinyin.
83
     *
84
     * @param string $stringName
85
     * @param string $option
86
     *
87
     * @return array
88
     */
89 2
    public function name($stringName, $option = self::NONE)
90
    {
91 2
        $pinyin = $this->romanize($stringName, true);
92
93 2
        return $this->splitWords($pinyin, $option);
94
    }
95
96
    /**
97
     * Return a pinyin permalink from string.
98
     *
99
     * @param string $string
100
     * @param string $delimiter
101
     *
102
     * @return string
103
     */
104 2
    public function permalink($string, $delimiter = '-')
105
    {
106 2
        if (!in_array($delimiter, array('_', '-', '.', ''), true)) {
107 2
            throw new InvalidArgumentException("Delimiter must be one of: '_', '-', '', '.'.");
108
        }
109
110 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...
111
    }
112
113
    /**
114
     * Return first letters.
115
     *
116
     * @param string $string
117
     * @param string $delimiter
118
     *
119
     * @return string
120
     */
121 2
    public function abbr($string, $delimiter = '')
122
    {
123
        return implode($delimiter, array_map(function ($pinyin) {
124 2
            return $pinyin[0];
125 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...
126
    }
127
128
    /**
129
     * Chinese to pinyin sentense.
130
     *
131
     * @param string $sentence
132
     * @param string $option
0 ignored issues
show
Bug introduced by
There is no parameter named $option. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

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