2023-06-11 12:14:03 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Modules\Currency\Entities;
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
use Illuminate\Http\JsonResponse;
|
2023-06-11 12:14:03 +00:00
|
|
|
use Modules\Support\Eloquent\Model;
|
|
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
use Modules\Currency\Admin\CurrencyRateTable;
|
|
|
|
use Modules\Currency\Services\CurrencyRateExchanger;
|
|
|
|
|
|
|
|
class CurrencyRate extends Model
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* The attributes that are mass assignable.
|
|
|
|
*
|
|
|
|
* @var array
|
|
|
|
*/
|
|
|
|
protected $fillable = ['currency', 'rate'];
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
2023-06-11 12:14:03 +00:00
|
|
|
/**
|
|
|
|
* Perform any actions required after the model boots.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public static function booted()
|
|
|
|
{
|
|
|
|
static::saved(function ($currencyRate) {
|
|
|
|
Cache::forget(md5("currency_rate.{$currencyRate->currency}"));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
2023-06-11 12:14:03 +00:00
|
|
|
/**
|
|
|
|
* Refresh all supported currencies exchange rate.
|
|
|
|
*
|
2023-12-03 14:07:47 +00:00
|
|
|
* @param CurrencyRateExchanger $exchanger
|
|
|
|
*
|
2023-06-11 12:14:03 +00:00
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public static function refreshRates(CurrencyRateExchanger $exchanger)
|
|
|
|
{
|
|
|
|
$fromCurrency = setting('default_currency');
|
|
|
|
|
|
|
|
foreach (setting('supported_currencies') as $toCurrency) {
|
|
|
|
$rate = $exchanger->exchange($fromCurrency, $toCurrency);
|
|
|
|
|
|
|
|
static::where('currency', $toCurrency)->first()->update(['rate' => $rate]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
2023-06-11 12:14:03 +00:00
|
|
|
/**
|
|
|
|
* Get currency rate for the given currency.
|
|
|
|
*
|
|
|
|
* @param string $currency
|
2023-12-03 14:07:47 +00:00
|
|
|
*
|
2023-06-11 12:14:03 +00:00
|
|
|
* @return int|float
|
|
|
|
*/
|
|
|
|
public static function for($currency)
|
|
|
|
{
|
|
|
|
return Cache::rememberForever(md5("currency_rate.{$currency}"), function () use ($currency) {
|
|
|
|
return static::where('currency', $currency)->value('rate');
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-12-03 14:07:47 +00:00
|
|
|
|
2023-06-11 12:14:03 +00:00
|
|
|
/**
|
|
|
|
* Get table data for the resource
|
|
|
|
*
|
2023-12-03 14:07:47 +00:00
|
|
|
* @return JsonResponse
|
2023-06-11 12:14:03 +00:00
|
|
|
*/
|
|
|
|
public function table()
|
|
|
|
{
|
|
|
|
return new CurrencyRateTable($this->newQuery());
|
|
|
|
}
|
|
|
|
}
|