. */ declare(strict_types=1); namespace FireflyIII\Repositories\Currency; use Carbon\Carbon; use FireflyIII\Models\CurrencyExchangeRate; use FireflyIII\Models\TransactionCurrency; use FireflyIII\User; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Support\Collection; /** * Class CurrencyRepository. */ class CurrencyRepository implements CurrencyRepositoryInterface { private User $user; /** * Find by currency code, return NULL if unfound. * * @param string $currencyCode * * @return TransactionCurrency|null */ public function findByCode(string $currencyCode): ?TransactionCurrency { return TransactionCurrency::where('code', $currencyCode)->first(); } /** * Returns the complete set of transactions but needs * no user object. * * @return Collection */ public function getCompleteSet(): Collection { return TransactionCurrency::orderBy('code', 'ASC')->get(); } /** * Get currency exchange rate. * * @param TransactionCurrency $fromCurrency * @param TransactionCurrency $toCurrency * @param Carbon $date * * @return CurrencyExchangeRate|null */ public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): ?CurrencyExchangeRate { if ($fromCurrency->id === $toCurrency->id) { $rate = new CurrencyExchangeRate(); $rate->rate = "1"; $rate->id = 0; return $rate; } /** @var CurrencyExchangeRate|null $rate */ $rate = $this->user->currencyExchangeRates() ->where('from_currency_id', $fromCurrency->id) ->where('to_currency_id', $toCurrency->id) ->where('date', $date->format('Y-m-d'))->first(); if (null !== $rate) { app('log')->debug(sprintf('Found cached exchange rate in database for %s to %s on %s', $fromCurrency->code, $toCurrency->code, $date->format('Y-m-d'))); return $rate; } return null; } /** * TODO must be a factory * * @param TransactionCurrency $fromCurrency * @param TransactionCurrency $toCurrency * @param Carbon $date * @param float $rate * * @return CurrencyExchangeRate */ public function setExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date, float $rate): CurrencyExchangeRate { return CurrencyExchangeRate::create( [ 'user_id' => $this->user->id, 'from_currency_id' => $fromCurrency->id, 'to_currency_id' => $toCurrency->id, 'date' => $date, 'rate' => $rate, ] ); } /** * @param User|Authenticatable|null $user */ public function setUser(User | Authenticatable | null $user): void { if ($user instanceof User) { $this->user = $user; } } }