Currency::rates()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
nc 1
nop 0
dl 0
loc 3
c 0
b 0
f 0
cc 1
rs 10
1
<?php
2
3
namespace Orkhanahmadov\LaravelCurrencylayer\Models;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Relations\HasMany;
8
9
/**
10
 * @property int $id
11
 * @property string $code
12
 */
13
class Currency extends Model
14
{
15
    /**
16
     * @var string
17
     */
18
    protected $table = 'currencylayer_currencies';
19
    /**
20
     * @var bool
21
     */
22
    public $timestamps = false;
23
    /**
24
     * @var array<string>
25
     */
26
    protected $fillable = [
27
        'code',
28
    ];
29
30
    public function rates(): HasMany
31
    {
32
        return $this->hasMany(Rate::class, 'source_currency_id');
33
    }
34
35
    /**
36
     * Get rate for given currency and date.
37
     *
38
     * @param Currency|string $currency
39
     * @param Carbon|string|null $date
40
     *
41
     * @return Rate|null
42
     */
43
    public function rateFor($currency, $date = null): ?Rate
44
    {
45
        if (! $currency instanceof self) {
46
            $currency = self::where('code', $currency)->firstOrFail();
47
        }
48
49
        $query = $this->rates()->where('target_currency_id', $currency->id);
50
51
        if ($date) {
52
            $query = $query->whereDay('timestamp', $date instanceof Carbon ? $date : Carbon::parse($date));
53
        }
54
55
        return $query->orderByDesc('timestamp')->first();
56
    }
57
}
58