RegionService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Services;
  3. use App\Region;
  4. use App\Traits\ServiceAppAop;
  5. class RegionService
  6. {
  7. use ServiceAppAop;
  8. /**
  9. * 根据省份获取ID
  10. *
  11. * @param string $province
  12. *
  13. * @return int
  14. */
  15. public function getProvince(string $province):int
  16. {
  17. $pool = ["省","自治区","市","特别行政"];
  18. $province = $this->extractKeyword($province,$pool);
  19. $region = Region::withTrashed()->where("name","like",$province."%")
  20. ->where("type",1)->first();
  21. if (!$region)$region = Region::query()->create([
  22. "name" => $province,
  23. "type" => 2,
  24. ]);
  25. return $region->id;
  26. }
  27. /**
  28. * 根据城市获取ID
  29. *
  30. * @param string $city
  31. * @param string|int|null $parent
  32. *
  33. * @return int
  34. */
  35. public function getCity(string $city, $parent = null):int
  36. {
  37. $pool = ["市","区","自治州","州","盟"];
  38. $city = $this->extractKeyword($city,$pool);
  39. $region = Region::withTrashed()->where("name","like",$city."%")
  40. ->where("type",2)->first();
  41. if (!$region){
  42. $region = [
  43. "name" => $city,
  44. "type" => 2,
  45. ];
  46. if ($parent){
  47. if (is_int($parent))$region["parent_id"] = $parent;
  48. else $region["parent_id"] = $this->getProvince($parent);
  49. }
  50. $region = Region::query()->create($region);
  51. }
  52. return $region->id;
  53. }
  54. /**
  55. * 根据区县获取ID
  56. *
  57. * @param string $district
  58. * @param string|int|null $parent
  59. *
  60. * @return int
  61. */
  62. public function getDistrict(string $district, $parent = null):int
  63. {
  64. $pool = ["市","区","自治县","县","自治旗","旗","特区","林区"];
  65. $district = $this->extractKeyword($district,$pool);
  66. $region = Region::withTrashed()->where("name","like",$district."%")
  67. ->where("type",3)->first();
  68. if (!$region){
  69. $region = [
  70. "name" => $district,
  71. "type" => 3,
  72. ];
  73. if ($parent){
  74. if (is_int($parent))$region["parent_id"] = $parent;
  75. else $region["parent_id"] = $this->getCity($parent);
  76. }
  77. $region = Region::query()->create($region);
  78. }
  79. return $region->id;
  80. }
  81. /**
  82. * 根据字典池提取关键字
  83. *
  84. * @param string $name
  85. * @param array $pool
  86. *
  87. * @return string
  88. */
  89. private function extractKeyword(string $name,array $pool)
  90. {
  91. foreach ($pool as $keyword){
  92. $result = mb_strpos($name,$keyword);
  93. if ($result!==false){
  94. return mb_substr($name,0,$result);
  95. }
  96. }
  97. return $name;
  98. }
  99. }