-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGermanAddressValidation.php
More file actions
118 lines (109 loc) · 2.99 KB
/
GermanAddressValidation.php
File metadata and controls
118 lines (109 loc) · 2.99 KB
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
112
113
114
115
116
117
118
<?php
/**
* Author: ojooss
* Copyright 2019
*/
class GermanAddressValidation
{
const URL = 'https://www.postdirekt.de/plzserver/PlzAjaxServlet';
/**
* @var string
*/
public $lastResult;
/**
* @param array $postFields
* @return stdClass
* @throws Exception
*/
protected function request(array $postFields): stdClass
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, self::URL);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postFields));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$this->lastResult = curl_exec($curl);
if ($this->lastResult === false) {
throw new Exception('Invalid server response');
}
$errno = curl_errno($curl);
$error = curl_error($curl);
curl_close($curl);
if ($errno > 0) {
throw new Exception($error);
}
$json = json_decode($this->lastResult);
if (is_null($json)) {
throw new Exception('Invalid server response');
}
if (!$json->success) {
throw new Exception('Request failed');
}
return $json;
}
/**
* @param string $postCode
* @return stdClass[]
* @throws Exception
*/
public function searchCityByPostCode(string $postCode): array
{
if (!preg_match('~[0-9]{5}~', $postCode)) {
throw new Exception('Invalid postcode');
}
$postFields = [
'finda' => 'city',
'city' => $postCode,
'lang' => 'de_DE'
];
$result = $this->request($postFields);
return $result->rows ?? [];
}
/**
* @param string $city
* @param string $street
* @return stdClass[]
* @throws Exception
*/
public function searchPostCodeByCityStreet(string $city, string $street): array
{
$postFields = [
'finda' => 'plz',
'plz_city' => $city,
'plz_plz' => '',
'plz_city_clear' => '',
'plz_district' => '',
'plz_street' => $street,
'lang' => 'de_DE'
];
$result = $this->request($postFields);
return $result->rows ?? [];
}
/**
* @param string $postCode
* @return bool
* @throws Exception
*/
public function validatePostCode(string $postCode): bool
{
$cities = $this->searchCityByPostCode($postCode);
return (count($cities) > 0);
}
/**
* @param string $city
* @param string $street
* @param string $postCode
* @return bool
* @throws Exception
*/
public function validateAddress(string $city, string $street, string $postCode): bool
{
$matches = $this->searchPostCodeByCityStreet($city, $street);
foreach($matches as $address) {
if ($address->plz == $postCode) {
return true;
}
}
return false;
}
}