-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCantonManager.php
111 lines (87 loc) · 2.97 KB
/
CantonManager.php
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php declare(strict_types=1);
namespace Wnx\SwissCantons;
use Wnx\SwissCantons\Exceptions\CantonNotFoundException;
use Wnx\SwissCantons\Exceptions\NotUniqueCantonException;
class CantonManager
{
protected CantonSearch $search;
protected CitySearch $citySearch;
public function __construct()
{
$this->search = new CantonSearch();
$this->citySearch = new CitySearch();
}
/**
* Get Canton by abbreviation.
*
* @throws CantonNotFoundException
*/
public function getByAbbreviation(string $abbreviation): Canton
{
$result = $this->search->findByAbbreviation($abbreviation);
if (is_null($result)) {
throw CantonNotFoundException::notFoundForAbbreviation($abbreviation);
}
return $result;
}
/**
* Get Canton by Name.
*
* @throws CantonNotFoundException
*/
public function getByName(string $name): Canton
{
$result = $this->search->findByName($name);
if (is_null($result)) {
throw CantonNotFoundException::notFoundForName($name);
}
return $result;
}
/**
* Get possible Cantons with a Zipcode.
*
* @param int $zipcode
* @return Canton[]
* @throws CantonNotFoundException
*/
public function getByZipcode(int $zipcode): array
{
$cities = $this->citySearch->findByZipcode($zipcode);
// Get cantons abbreviations
$cantonAbbreviations = array_column($cities, 'canton');
// Remove duplicates
$cantonAbbreviations = array_unique($cantonAbbreviations);
// Search cantons by abbreviation
$cantons = array_map(fn (string $abbreviation) => $this->search->findByAbbreviation($abbreviation), $cantonAbbreviations);
// Call 'array_filter' without callback to remove null values
$cantons = array_filter($cantons);
if (empty($cantons)) {
throw CantonNotFoundException::notFoundForZipcode($zipcode);
}
return $cantons;
}
/**
* @param int $zipcode
* @param ?string $cityName
* @return Canton
* @throws CantonNotFoundException|NotUniqueCantonException
*/
public function getByZipcodeAndCity(int $zipcode, ?string $cityName = null): Canton
{
$cantons = $this->getByZipcode($zipcode);
if (1 === count($cantons)) {
return $cantons[0];
}
if (null !== $cityName) {
$cities = $this->citySearch->findByZipcode($zipcode);
foreach ($cities as $city) {
if ($city['city'] === $cityName) {
return $this->search->findByAbbreviation($city['canton'])
?? throw CantonNotFoundException::notFoundForAbbreviation($city['canton']);
}
}
throw NotUniqueCantonException::notUniqueForZipcodeAndCity($zipcode, $cityName);
}
throw NotUniqueCantonException::notUniqueForZipcode($zipcode);
}
}