Passed
Push — master ( 017d3e...a6ee47 )
by Orkhan
02:34 queued 10s
created

Currency::rateFor()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 6
nc 4
nop 2
dl 0
loc 13
rs 10
c 0
b 0
f 0
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
    protected $table = 'currencylayer_currencies';
16
17
    public $timestamps = false;
18
19
    protected $fillable = [
20
        'code',
21
    ];
22
23
    public function rates(): HasMany
24
    {
25
        return $this->hasMany(Rate::class, 'source_currency_id');
26
    }
27
28
    /**
29
     * @param Currency|string $currency
30
     * @param Carbon|string|null $date
31
     *
32
     * @return Rate|null
33
     */
34
    public function rateFor($currency, $date = null): ?Rate
35
    {
36
        if (! $currency instanceof Currency) {
37
            $currency = Currency::where('code', $currency)->firstOrFail();
38
        }
39
40
        $query = $this->rates()->where('target_currency_id', $currency->id);
41
42
        if ($date) {
43
            $query = $query->whereDay('timestamp', $date instanceof Carbon ? $date : Carbon::parse($date));
44
        }
45
46
        return $query->orderByDesc('timestamp')->first();
47
    }
48
}
49