1 <?php
2
3 namespace PayPal\Converter;
4
5 class FormatConverter
6 {
7 /**
8 * Format the data based on the input formatter value
9 *
10 * @param $value
11 * @param $formatter
12 * @return string
13 */
14 public static function format($value, $formatter)
15 {
16 return sprintf($formatter, $value);
17 }
18
19 /**
20 * Format the input data with decimal places
21 *
22 * Defaults to 2 decimal places
23 *
24 * @param $value
25 * @param int $decimals
26 * @return null|string
27 */
28 public static function formatToNumber($value, $decimals = 2)
29 {
30 if (trim($value) != null) {
31 return number_format($value, $decimals, '.', '');
32 }
33 return null;
34 }
35
36 /**
37 * Helper method to format price values with associated currency information.
38 *
39 * It covers the cases where certain currencies does not accept decimal values. We will be adding
40 * any specific currency level rules as required here.
41 *
42 * @param $value
43 * @param null $currency
44 * @return null|string
45 */
46 public static function formatToPrice($value, $currency = null)
47 {
48 $decimals = 2;
49 $currencyDecimals = array('JPY' => 0, 'TWD' => 0);
50 if ($currency && array_key_exists($currency, $currencyDecimals)) {
51 if (strpos($value, ".") !== false && (floor($value) != $value)) {
52 //throw exception if it has decimal values for JPY and TWD which does not ends with .00
53 throw new \InvalidArgumentException("value cannot have decimals for $currency currency");
54 }
55 $decimals = $currencyDecimals[$currency];
56 } elseif (strpos($value, ".") === false) {
57 // Check if value has decimal values. If not no need to assign 2 decimals with .00 at the end
58 $decimals = 0;
59 }
60 return self::formatToNumber($value, $decimals);
61 }
62 }
63