summaryrefslogtreecommitdiff
path: root/src/RegionManager.php
blob: daf49eb5370ade2dac134bb138438bbce75147b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php

declare(strict_types=1);

namespace Zhineng\RegionChina;

final class RegionManager
{
    /**
     * @param  array<string, string>  $codeToName
     * @param  array<string, int[]>  $relationships
     * @param  array<int, int[]>  $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;
    }
}