<?php
namespace Cart;
/**
* 货币类
* @package Cart
*/
class Currency {
// 货币种类
private $currencies = array();
public function __construct($registry) {
// 加载数据库类
$this->db = $registry->get('db');
// 加载语言类
$this->language = $registry->get('language');
// 查询货币
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "currency");
// 查询结果进行遍历
foreach ($query->rows as $result) {
$res = $this->currencies[$result['code']] = array(
'currency_id' => $result['currency_id'],
'title' => $result['title'],
'symbol_left' => $result['symbol_left'],
'symbol_right' => $result['symbol_right'],
'decimal_place' => $result['decimal_place'],
'value' => $result['value']
);
}
}
// 格式化
public function format($number, $currency, $value = '', $format = true) {
$symbol_left = $this->currencies[$currency]['symbol_left'];
$symbol_right = $this->currencies[$currency]['symbol_right'];
$decimal_place = $this->currencies[$currency]['decimal_place'];
if (!$value) {
$value = $this->currencies[$currency]['value'];
}
$amount = $value ? (float)$number * $value : (float)$number;
// 四舍五入
$amount = round($amount, (int)$decimal_place);
if (!$format) {
return $amount;
}
$string = '';
if ($symbol_left) {
$string .= $symbol_left;
}
// 通过千位分组来格式化数字
$string .= number_format($amount, (int)$decimal_place, $this->language->get('decimal_point'), $this->language->get('thousand_point'));
if ($symbol_right) {
$string .= $symbol_right;
}
return $string;
}
// 转换
public function convert($value, $from, $to) {
if (isset($this->currencies[$from])) {
$from = $this->currencies[$from]['value'];
} else {
$from = 1;
}
if (isset($this->currencies[$to])) {
$to = $this->currencies[$to]['value'];
} else {
$to = 1;
}
return $value * ($to / $from);
}
// 获取货币id
public function getId($currency) {
if (isset($this->currencies[$currency])) {
return $this->currencies[$currency]['currency_id'];
} else {
return 0;
}
}
// 货币符号在在金额左边显示
public function getSymbolLeft($currency) {
if (isset($this->currencies[$currency])) {
return $this->currencies[$currency]['symbol_left'];
} else {
return '';
}
}
// 货币符号在在金额右边显示
public function getSymbolRight($currency) {
if (isset($this->currencies[$currency])) {
return $this->currencies[$currency]['symbol_right'];
} else {
return '';
}
}
// 保留小数点后几位有效数字
public function getDecimalPlace($currency) {
if (isset($this->currencies[$currency])) {
return $this->currencies[$currency]['decimal_place'];
} else {
return 0;
}
}
public function getValue($currency) {
if (isset($this->currencies[$currency])) {
return $this->currencies[$currency]['value'];
} else {
return 0;
}
}
// 判断是否存在
public function has($currency) {
return isset($this->currencies[$currency]);
}
}