Skip to content

Commit c825068

Browse files
authored
Add Api Postcode Client
1 parent 227498d commit c825068

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

Client/PostcodeClient.php

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php
2+
/*
3+
* (c) Api Postcode <info@api-postcode.nl>
4+
*
5+
* For the full copyright and license information, please view the LICENSE
6+
* file that was distributed with this source code.
7+
*/
8+
9+
namespace ApiPostcode\Client;
10+
11+
use ApiPostcode\Exception\InvalidPostcodeException;
12+
use ApiPostcode\Exception\InvalidResponseException;
13+
use ApiPostcode\Model\Address;
14+
15+
/**
16+
* Class PostcodeClient
17+
*
18+
* @author Api Postcode <info@api-postcode.nl>
19+
*/
20+
class PostcodeClient
21+
{
22+
/** @var string */
23+
private $token;
24+
25+
/**
26+
* @param string $token
27+
*/
28+
public function __construct($token)
29+
{
30+
$this->token = $token;
31+
}
32+
33+
/**
34+
* @param string $zipCode
35+
* @param string $houseNumber
36+
*
37+
* @throws InvalidPostcodeException
38+
* @throws InvalidResponseException
39+
*
40+
* @return Address
41+
*/
42+
public function fetchAddress($zipCode, $houseNumber)
43+
{
44+
if (0 === preg_match('/^[1-9]{1}[0-9]{3}[\s]{0,1}[a-z]{2}$/i', $zipCode)) {
45+
throw new InvalidPostcodeException('Given postcode incorrect');
46+
}
47+
48+
$uri = sprintf("http://json.api-postcode.nl?postcode=%s&number=%s", $zipCode, $houseNumber);
49+
$curl = curl_init();
50+
51+
curl_setopt($curl, CURLOPT_URL,$uri);
52+
curl_setopt($curl, CURLOPT_POST, 1);
53+
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
54+
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers = [sprintf('Token: %s', $this->token)]);
55+
56+
$server_output = curl_exec ($curl);
57+
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
58+
59+
if ($httpCode !== 200) {
60+
throw new InvalidResponseException('Response does not return a valid response code');
61+
}
62+
63+
curl_close($curl);
64+
65+
$responseData = json_decode($server_output, true);
66+
67+
$address = new Address(
68+
$responseData['street'],
69+
$responseData['postcode'],
70+
$responseData['house_number'],
71+
$responseData['city']
72+
);
73+
74+
$address->setLatitude($responseData['latitude']);
75+
$address->setLongitude($responseData['longitude']);
76+
77+
return $address;
78+
}
79+
}

0 commit comments

Comments
 (0)