From cb8ad9567a940db0434b9ca8991422ac9d2ce795 Mon Sep 17 00:00:00 2001 From: Li Zhineng Date: Mon, 28 Apr 2025 17:53:19 +0800 Subject: region manager --- src/RegionException.php | 10 ++++++++ src/RegionManager.php | 58 +++++++++++++++++++++++++++++++++++++++++++++ tests/RegionManagerTest.php | 52 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 src/RegionException.php create mode 100644 src/RegionManager.php create mode 100644 tests/RegionManagerTest.php diff --git a/src/RegionException.php b/src/RegionException.php new file mode 100644 index 0000000..f33adec --- /dev/null +++ b/src/RegionException.php @@ -0,0 +1,10 @@ + $codeToName + * @param array $relationships + * @param array $topLevels + */ + public function __construct( + private array $codeToName, + private array $relationships, + private array $topLevels + ) { + // + } + + public static function createFromBuiltIn(): static + { + return new self( + require __DIR__.'/../resources/code-to-name.php', + require __DIR__.'/../resources/relationships.php', + require __DIR__.'/../resources/top-levels.php' + ); + } + + public function getName(int $code): string + { + return $this->codeToName[$this->groupKey($code)] + ?? throw new RegionException('The region code does not exist.'); + } + + /** + * @return int[] + */ + public function getTopLevelNodes(): array + { + return $this->topLevels; + } + + /** + * @return int[] + */ + public function getNodes(int $code): array + { + return $this->relationships[$this->groupKey($code)] + ?? throw new RegionException('Could not find any nodes under the region code.'); + } + + private function groupKey(int $code): string + { + return '_'.$code; + } +} diff --git a/tests/RegionManagerTest.php b/tests/RegionManagerTest.php new file mode 100644 index 0000000..2536a7c --- /dev/null +++ b/tests/RegionManagerTest.php @@ -0,0 +1,52 @@ + '北京市'], + [], + [] + ); + $this->assertSame('北京市', $manager->getName(110000)); + } + + public function test_name_resolution_with_non_existent_code(): void + { + $this->expectException(RegionException::class); + $this->expectExceptionMessage('The region code does not exist.'); + $manager = new RegionManager([], [], []); + $manager->getName(110000); + } + + public function test_top_level_nodes_resolution(): void + { + $manager = new RegionManager([], [], [1, 2, 3]); + $this->assertSame([1, 2, 3], $manager->getTopLevelNodes()); + } + + public function test_nodes_resolution(): void + { + $manager = new RegionManager([], ['_1' => [2]], []); + $this->assertSame([2], $manager->getNodes(1)); + } + + public function test_nodes_resolution_with_non_existent_code(): void + { + $this->expectException(RegionException::class); + $this->expectExceptionMessage('Could not find any nodes under the region code.'); + $manager = new RegionManager([], [], []); + $manager->getNodes(1); + } +} -- cgit v1.2.3