pinyin 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env php
  2. <?php
  3. require __DIR__ . '/../vendor/autoload.php';
  4. require __DIR__ . '/utils.php';
  5. use Overtrue\Pinyin\Pinyin;
  6. $methods = ['sentence','fullSentence','name','passportName','phrase','permalink','heteronym','heteronymAsList','chars','abbr','nameAbbr'];
  7. $method = 'sentence';
  8. $inputOptions = [];
  9. $methodAsString = implode('/', $methods);
  10. $help = <<<"HELP"
  11. Usage:
  12. ./pinyin [chinese] [method] [options]
  13. Options:
  14. -j, --json 输出 JSON 格式.
  15. -c, --compact 不格式化输出 JSON.
  16. -m, --method=[method] 转换方式,可选:{$methodAsString}.
  17. --no-tone 不使用音调.
  18. --tone-style=[style] 音调风格,可选值:symbol/none/number, default: none.
  19. -h, --help 显示帮助.
  20. HELP;
  21. function has_option($option, $alias = null): bool
  22. {
  23. global $inputOptions;
  24. if ($alias) {
  25. return array_key_exists($option, $inputOptions) || array_key_exists($alias, $inputOptions);
  26. }
  27. return array_key_exists($option, $inputOptions);
  28. }
  29. function get_option($option, $default = null, $alias = null): ?string
  30. {
  31. global $inputOptions;
  32. if ($alias) {
  33. return $inputOptions[$option] ?? $inputOptions[$alias] ?? $default;
  34. }
  35. return $inputOptions[$option] ?? $default;
  36. }
  37. $inputOptions = parse_options($argv);
  38. $input = $inputOptions[0] ?? null;
  39. $positionalMethod = $inputOptions[1] ?? null;
  40. if (empty($input) || has_option('help', 'h')) {
  41. echo $help;
  42. exit(0);
  43. }
  44. $method = get_option('method', $positionalMethod ?? $method, 'm');
  45. $toneStyle = has_option('no-tone') ? 'none' : get_option('tone-style', 'none');
  46. if (! in_array($method, $methods, true)) {
  47. echo "Method '{$method}' is not supported.\n";
  48. exit(1);
  49. }
  50. try {
  51. $result = Pinyin::$method($input, $method === 'permalink' ? '-' : $toneStyle);
  52. } catch (\InvalidArgumentException|\ValueError $e) {
  53. echo $e->getMessage(), "\n";
  54. exit(1);
  55. }
  56. $toJson = has_option('json', 'j') || in_array($method, ['heteronym', 'heteronymAsList'], true);
  57. if ($toJson) {
  58. $options = JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT;
  59. if (has_option('compact', 'c')) {
  60. $options = 0;
  61. }
  62. $result = json_encode($result, $options);
  63. }
  64. echo $result, "\n";