Files
swiftadmin/vendor/overtrue/pinyin/bin/pinyin
2023-04-25 20:11:49 +08:00

85 lines
2.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env php
<?php
require __DIR__ . '/../vendor/autoload.php';
use Overtrue\Pinyin\Pinyin;
$input = $argv[1] ?? null;
$methods = explode(',', 'name,phrase,permalink,polyphones,chars,nameAbbr,abbr,sentence');
$method = 'sentence';
$inputOptions = [];
$help = <<<"HELP"
Usage:
./pinyin [chinese] [method] [options]
Options:
-j, --json 输出 JSON 格式.
-c, --compact 不格式化输出 JSON.
-m, --method=[method] 转换方式可选name/phrase/permalink/polyphones/chars/nameAbbr/abbr/sentence.
--no-tone 不使用音调.
--tone-style=[style] 音调风格可选值default/none/number.
-h, --help 显示帮助.
HELP;
foreach ($argv as $i => $arg) {
if ($i === 0) {
continue;
}
if (in_array($arg, $methods)) {
$method = $arg;
} elseif (str_starts_with($arg, '-')) {
[$key, $value] = array_pad(array_map('trim', explode('=', $arg, 2)), 2, null);
$inputOptions[$key] = $value;
}
}
function has_option($option, $alias = null): bool
{
global $inputOptions;
if ($alias) {
return array_key_exists($option, $inputOptions) || array_key_exists($alias, $inputOptions);
}
return array_key_exists($option, $inputOptions);
}
function get_option($option, $default = null, $alias = null): ?string
{
global $inputOptions;
if ($alias) {
return $inputOptions[$option] ?? $inputOptions[$alias] ?? $default;
}
return $inputOptions[$option] ?? $default;
}
if (empty($input) || has_option('--help', '-h')) {
echo $help;
exit(0);
}
if (has_option('--method', '-m')) {
$method = get_option('--method');
}
$toneStyle = has_option('--no-tone') ? 'none' : get_option('--tone-style', 'default');
$result = Pinyin::$method($input, $method === 'permalink' ? '-' : $toneStyle);
$toJson = has_option('--json', '-j') || in_array($method, ['polyphones']);
if ($toJson) {
$options = JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT;
if (has_option('--compact', '-c')) {
$options = 0;
}
$result = json_encode($result, $options);
}
echo $result, "\n";