Completed
Push — master ( dc2855...0a5beb )
by z38
03:37
created

PostalAccount::asDom()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 9.6666
cc 1
eloc 6
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Z38\SwissPayment;
4
5
use DOMDocument;
6
7
/**
8
 * PostalAccount holds details about a PostFinance account
9
 */
10
class PostalAccount implements AccountInterface
11
{
12
    const PATTERN = '/^[0-9]{2}-[1-9][0-9]{0,5}-[0-9]$/';
13
14
    /**
15
     * @var int
16
     */
17
    protected $prefix;
18
19
    /**
20
     * @var int
21
     */
22
    protected $number;
23
24
    /**
25
     * @var int
26
     */
27
    protected $checkDigit;
28
29
    /**
30
     * Constructor
31
     *
32
     * @param string $postalAccount
33
     *
34
     * @throws \InvalidArgumentException When the account number is not valid (check digit is not being tested).
35
     */
36 8
    public function __construct($postalAccount)
37
    {
38 8
        if (!preg_match(self::PATTERN, $postalAccount)) {
39 1
            throw new \InvalidArgumentException('Postal account number is not properly formatted.');
40
        }
41
42 7
        $parts = explode('-', $postalAccount);
43 7
        if (!self::checkPrefix($parts[0])) {
44 1
            throw new \InvalidArgumentException('Postal account number has an invalid prefix.');
45
        }
46
47 6
        $this->prefix = (int) $parts[0];
48 6
        $this->number = (int) $parts[1];
49 6
        $this->checkDigit = (int) $parts[2];
50 6
    }
51
52
    /**
53
     * Format the postal account number
54
     *
55
     * @return string The formatted account number
56
     */
57 6
    public function format()
58
    {
59 6
        return sprintf('%d-%d-%d', $this->prefix, $this->number, $this->checkDigit);
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 2
    public function asDom(DOMDocument $doc)
66
    {
67 2
        $root = $doc->createElement('Id');
68 2
        $other = $doc->createElement('Othr');
69 2
        $other->appendChild($doc->createElement('Id', $this->format()));
70 2
        $root->appendChild($other);
71
72 2
        return $root;
73
    }
74
75
    /**
76
     * Checks whether a given prefix is valid
77
     *
78
     * @param int $prefix The prefix to be checked
79
     *
80
     * @return bool True if the prefix is valid
81
     */
82 2
    private static function checkPrefix($prefix)
83
    {
84 2
        return in_array($prefix, array(
85 2
            10, 12, 17, 18, 19,
86 2
            20, 23, 25, 30, 34,
87 2
            40, 45, 46, 49, 50,
88 2
            60, 65, 69, 70, 80,
89 2
            82, 84, 85, 87, 90,
90 2
            91, 92,
91 2
        ));
92
    }
93
}
94