-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathCAFormatter.php
More file actions
41 lines (33 loc) · 1.05 KB
/
CAFormatter.php
File metadata and controls
41 lines (33 loc) · 1.05 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
<?php
declare(strict_types=1);
namespace Brick\Postcode\Formatter;
use Brick\Postcode\CountryPostcodeFormatter;
use function preg_match;
use function substr;
/**
* Validates and formats postcodes in Canada.
*
* The format is ANA NAN, where A is a letter and N is a digit.
* Postal codes do not include the letters D, F, I, O, Q or U.
* The first position also does not make use of the letters W or Z.
*
* @see https://en.wikipedia.org/wiki/List_of_postal_codes
* @see https://en.wikipedia.org/wiki/Postal_codes_in_Canada
*/
final class CAFormatter implements CountryPostcodeFormatter
{
public function hint(): string
{
return 'The format is ANA NAN, where A is a letter and N is a digit.';
}
public function format(string $postcode): ?string
{
if (preg_match('/^([ABCEGHJ-NPRSTV-Z][0-9]){3}$/', $postcode) !== 1) {
return null;
}
if ($postcode[0] === 'W' || $postcode[0] === 'Z') {
return null;
}
return substr($postcode, 0, 3) . ' ' . substr($postcode, 3);
}
}