Completed
Pull Request — master (#51)
by Бабичев
07:35
created

CanExchange::exchange()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Bavix\Wallet\Traits;
4
5
use Bavix\Wallet\Interfaces\Wallet;
6
use Bavix\Wallet\Models\Transfer;
7
use Bavix\Wallet\Objects\Bring;
8
use Bavix\Wallet\Services\CommonService;
9
use Bavix\Wallet\Services\CurrencyService;
10
use Illuminate\Support\Facades\DB;
11
12
trait CanExchange
13
{
14
15
    /**
16
     * @inheritDoc
17
     */
18
    public function exchange(Wallet $to, int $amount): Transfer
19
    {
20
        // todo: check
21
        return $this->forceExchange($to, $amount);
22
    }
23
24
    /**
25
     * @inheritDoc
26
     */
27
    public function safeExchange(Wallet $to, int $amount): ?Transfer
28
    {
29
       try {
30
           return $this->exchange($to, $amount);
31
       } catch (\Throwable $throwable) {
32
           return null;
33
       }
34
    }
35
36
    /**
37
     * @inheritDoc
38
     */
39
    public function forceExchange(Wallet $to, int $amount): Transfer
40
    {
41
        /**
42
         * @var Wallet $from
43
         */
44
        $from = $this;
45
46
        return DB::transaction(function () use ($from, $to, $amount) {
47
            $rate = app(CurrencyService::class)->rate($from, $to);
48
            $withdraw = $this->withdraw($amount);
0 ignored issues
show
Bug introduced by
It seems like withdraw() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

48
            /** @scrutinizer ignore-call */ 
49
            $withdraw = $this->withdraw($amount);
Loading history...
49
            $deposit = $to->deposit($amount * $rate);
0 ignored issues
show
Bug introduced by
$amount * $rate of type double is incompatible with the type integer expected by parameter $amount of Bavix\Wallet\Interfaces\Wallet::deposit(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

49
            $deposit = $to->deposit(/** @scrutinizer ignore-type */ $amount * $rate);
Loading history...
50
51
            $transfers = app(CommonService::class)->multiBrings([
52
                (new Bring())
53
                    ->setStatus(Transfer::STATUS_EXCHANGE)
54
                    ->setDeposit($deposit)
55
                    ->setWithdraw($withdraw)
56
                    ->setFrom($from)
57
                    ->setTo($to)
58
            ]);
59
60
            return current($transfers);
61
        });
62
    }
63
64
}
65