Completed
Push — master ( 1c972b...51a525 )
by JM
05:55
created

IbanSanitizer   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 13
c 2
b 0
f 0
lcom 1
cbo 3
dl 0
loc 74
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getRequestEndpoint() 0 4 1
A describeObject() 0 4 1
A isLive() 0 4 1
A isRealtime() 0 4 1
B sanitize() 0 11 5
A convertUsingOpenIban() 0 13 3
1
<?php
2
3
namespace fieldwork\sanitizers;
4
5
use fieldwork\sanitizers;
6
use GuzzleHttp\Client;
7
8
class IbanSanitizer extends sanitizers\FieldSanitizer
9
{
10
11
    const ENDPOINT = 'http://opendata.siteworkers.nl/openiban?bban=';
12
13
    private $openIbanUsername,
14
        $openIbanPassword;
15
16
    function __construct ($openIbanUsername = null, $openIbanPassword = null)
17
    {
18
        $this->openIbanUsername = $openIbanUsername;
19
        $this->openIbanPassword = $openIbanPassword;
20
    }
21
22
    /**
23
     * @param $bban
24
     * @return string
25
     */
26
    private static function getRequestEndpoint ($bban)
27
    {
28
        return self::ENDPOINT . $bban;
29
    }
30
31
    public function describeObject ()
32
    {
33
        return 'iban';
34
    }
35
36
    public function isLive ()
37
    {
38
        return true;
39
    }
40
41
    public function isRealtime ()
42
    {
43
        return false;
44
    }
45
46
    public function sanitize ($value)
47
    {
48
        $value = preg_replace('/\s/', '', $value);
49
        if (preg_match('/^[0-9]{1,10}$/', $value) && $this->openIbanUsername !== null && $this->openIbanPassword !== null) {
50
            $convertedValue = self::convertUsingOpenIban($value, $this->openIbanUsername, $this->openIbanPassword);
51
            if ($convertedValue !== null)
52
                $value = $convertedValue;
53
        }
54
        $parts = str_split($value, 4);
55
        return implode(' ', $parts);
56
    }
57
58
    /**
59
     * Converst BBAN number into IBAN number using the openiban API
60
     *
61
     * @param string $bban
62
     * @param string $username
63
     * @param string $password
64
     *
65
     * @return string|null
66
     */
67
    private static function convertUsingOpenIban ($bban, $username, $password)
68
    {
69
        try {
70
            $client      = new Client();
71
            $res         = $client->request('GET', self::getRequestEndpoint($bban), [
72
                'auth' => [$username, $password]
73
            ]);
74
            $apiResponse = json_decode($res->getBody());
75
            return $apiResponse === null ? null : $apiResponse['iban'];
76
        } catch (\Exception $e) {
77
            return null;
78
        }
79
    }
80
81
}