Nenhuma descrição
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

MemoryFileDictLoader.php 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /*
  3. * This file is part of the overtrue/pinyin.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Overtrue\Pinyin;
  11. use Closure;
  12. class MemoryFileDictLoader implements DictLoaderInterface
  13. {
  14. /**
  15. * Data directory.
  16. *
  17. * @var string
  18. */
  19. protected $path;
  20. /**
  21. * Words segment name.
  22. *
  23. * @var string
  24. */
  25. protected $segmentName = 'words_%s';
  26. /**
  27. * Segment files.
  28. *
  29. * @var array
  30. */
  31. protected $segments = [];
  32. /**
  33. * Surname cache.
  34. *
  35. * @var array
  36. */
  37. protected $surnames = [];
  38. /**
  39. * Constructor.
  40. *
  41. * @param string $path
  42. */
  43. public function __construct($path)
  44. {
  45. $this->path = $path;
  46. for ($i = 0; $i < 100; ++$i) {
  47. $segment = $path . '/' . sprintf($this->segmentName, $i);
  48. if (file_exists($segment)) {
  49. $this->segments[] = (array) include $segment;
  50. }
  51. }
  52. }
  53. /**
  54. * Load dict.
  55. *
  56. * @param Closure $callback
  57. */
  58. public function map(Closure $callback)
  59. {
  60. foreach ($this->segments as $dictionary) {
  61. $callback($dictionary);
  62. }
  63. }
  64. /**
  65. * Load surname dict.
  66. *
  67. * @param Closure $callback
  68. */
  69. public function mapSurname(Closure $callback)
  70. {
  71. if (empty($this->surnames)) {
  72. $surnames = $this->path . '/surnames';
  73. if (file_exists($surnames)) {
  74. $this->surnames = (array) include $surnames;
  75. }
  76. }
  77. $callback($this->surnames);
  78. }
  79. }