Completed
Push — master ( 0a5beb...6bf385 )
by z38
11:34
created

IID::format()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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