Completed
Push — master ( dba3c8...01cd01 )
by Jean C.
07:48 queued 01:45
created

Utils::toCents()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 42
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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