Completed
Push — master ( 2e7298...3749b5 )
by
unknown
11s
created

Utils   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 7
Bugs 1 Features 1
Metric Value
wmc 3
c 7
b 1
f 1
lcom 0
cbo 0
dl 0
loc 54
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B toCents() 0 42 3
1
<?php
2
3
namespace Moip;
4
5
class Utils
6
{
7
    /**
8
     * convert a money amount (represented by a float or string (based on locale) ie.: R$ 5,00) to cents (represented by an int).
9
     *
10
     * @param float $amount
11
     *
12
     * @throws \UnexpectedValueException
13
     *
14
     * @return int
15
     */
16
    public static function toCents($amount)
17
    {
18
        /*
19
         * There's probably a better way, but this is what i could come up with
20
         * to avoid rounding errors
21
         * todo: search for a better way
22
         */
23
24
        if (!is_float($amount)) {
25
            $type = gettype($amount);
26
            throw new \UnexpectedValueException("Needs a float! not $type");
27
        }
28
29
        //handle locales
30
        $locale = localeconv();
31
32
        $amount = str_replace($locale['mon_thousands_sep'], '', $amount);
33
        $amount = str_replace($locale['mon_decimal_point'], '.', $amount);
34
        $amount = str_replace($locale['decimal_point'], '.', $amount);
35
36
        $parts = explode('.', "$amount");
37
38
        // handle the case where $amount has a .0 fraction part
39
        if (count($parts) == 1) {
40
            $parts[] = '00';
41
        }
42
43
        list($whole, $fraction) = $parts;
44
45
        /*
46
         * since the documentation only mentions decimals with a precision of two
47
         * and doesn't specify any rounding method i'm truncating the number
48
         *
49
         * the str_pad is to handle the case where $amount is, for example, 6.9
50
         */
51
        $fraction = str_pad(substr($fraction, 0, 2), 2, '0');
52
53
        $whole = (int) $whole * 100;
54
        $fraction = (int) $fraction;
55
56
        return $whole + $fraction;
57
    }
58
}
59