Currency   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 12
c 2
b 0
f 0
dl 0
loc 43
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A rates() 0 3 1
A rateFor() 0 13 4
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