forked from z38/swiss-payment
-
Notifications
You must be signed in to change notification settings - Fork 6
/
PostalAccount.php
90 lines (76 loc) · 2.12 KB
/
PostalAccount.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
<?php
namespace Z38\SwissPayment;
use DOMDocument;
use InvalidArgumentException;
/**
* PostalAccount holds details about a PostFinance account
*/
class PostalAccount implements AccountInterface
{
private const PATTERN = '/^[0-9]{2}-[1-9][0-9]{0,5}-[0-9]$/';
/**
* @var int
*/
protected $prefix;
/**
* @var int
*/
protected $number;
/**
* @var int
*/
protected $checkDigit;
/**
* Constructor
*
* @param string $postalAccount
*
* @throws InvalidArgumentException When the account number is not valid.
*/
public function __construct($postalAccount)
{
if (!preg_match(self::PATTERN, $postalAccount)) {
throw new InvalidArgumentException('Postal account number is not properly formatted.');
}
$parts = explode('-', $postalAccount);
if (!self::validateCheckDigit(sprintf('%02s%06s%s', $parts[0], $parts[1], $parts[2]))) {
throw new InvalidArgumentException('Postal account number has an invalid check digit.');
}
$this->prefix = (int) $parts[0];
$this->number = (int) $parts[1];
$this->checkDigit = (int) $parts[2];
}
/**
* Format the postal account number
*
* @return string The formatted account number
*/
public function format()
{
return sprintf('%02d-%d-%d', $this->prefix, $this->number, $this->checkDigit);
}
/**
* {@inheritdoc}
*/
public function asDom(DOMDocument $doc)
{
$root = $doc->createElement('Id');
$other = $doc->createElement('Othr');
$other->appendChild($doc->createElement('Id', $this->format()));
$root->appendChild($other);
return $root;
}
/**
* @param $number
* @return bool
*/
public static function validateCheckDigit($number)
{
$lookup = [0, 9, 4, 6, 8, 2, 7, 1, 3, 5];
$carry = 0;
for ($i = 0; $i < strlen($number) - 1; $i++) {
$carry = $lookup[($carry + $number[$i]) % 10];
}
return (10 - $carry) % 10 === (int) $number[strlen($number) - 1];
}
}