IID::fromIBAN()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Z38\SwissPayment;
4
5
use DOMDocument;
6
use InvalidArgumentException;
7
8
/**
9
 * IID holds a Swiss institutional identification number (formerly known as BC number)
10
 */
11
class IID implements FinancialInstitutionInterface
12
{
13
    /**
14
     * @var string
15
     */
16
    protected $iid;
17
18
    /**
19
     * Constructor
20
     *
21
     * @param string $iid
22
     *
23
     * @throws \InvalidArgumentException When the IID does contain invalid characters or the length does not match.
24
     */
25 11
    public function __construct($iid)
26
    {
27 11
        $iid = (string) $iid;
28 11
        if (!preg_match('/^[0-9]{3,5}$/', $iid)) {
29 5
            throw new InvalidArgumentException('IID is not properly formatted.');
30
        }
31
32 6
        $this->iid = str_pad($iid, 5, '0', STR_PAD_LEFT);
33 6
    }
34
35
    /**
36
     * Extracts the IID from an IBAN
37
     *
38
     * @param IBAN $iban
39
     *
40
     * @throws \InvalidArgumentException When the supplied IBAN is not from a supported country.
41
     */
42 6
    public static function fromIBAN(IBAN $iban)
43
    {
44 6
        if (!in_array($iban->getCountry(), ['CH', 'LI'])) {
45 1
            throw new InvalidArgumentException('IID can only be extracted from Swiss and Lichtenstein IBANs.');
46
        }
47
48 5
        return new self(substr($iban->normalize(), 4, 5));
49
    }
50
51
    /**
52
     * Returns a formatted representation of the IID
53
     *
54
     * @return string The formatted IID
55
     */
56 1
    public function format()
57
    {
58 1
        return $this->iid;
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64 3
    public function asDom(DOMDocument $doc)
65
    {
66 3
        $xml = $doc->createElement('FinInstnId');
67 3
        $clearingSystem = $doc->createElement('ClrSysMmbId');
68 3
        $clearingSystemId = $doc->createElement('ClrSysId');
69 3
        $clearingSystemId->appendChild($doc->createElement('Cd', 'CHBCC'));
70 3
        $clearingSystem->appendChild($clearingSystemId);
71 3
        $clearingSystem->appendChild($doc->createElement('MmbId', ltrim($this->iid, '0'))); // strip zeroes for legacy systems
72 3
        $xml->appendChild($clearingSystem);
73
74 3
        return $xml;
75
    }
76
}
77