Completed
Push — master ( 4b3a6a...ccebfa )
by Dmitry
04:39
created

PriceDifferenceWidget::renderDifferenceWidget()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 12
cp 0
rs 9.7998
c 0
b 0
f 0
cc 4
nc 2
nop 0
crap 20
1
<?php
2
/**
3
 * Finance module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-finance
6
 * @package   hipanel-module-finance
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\finance\widgets;
12
13
use Money\Money;
14
use Money\MoneyFormatter;
15
use yii\base\Widget;
16
use yii\helpers\Html;
17
18
class PriceDifferenceWidget extends Widget
19
{
20
    /**
21
     * @var Money
22
     */
23
    public $old;
24
25
    /**
26
     * @var Money
27
     */
28
    public $new;
29
    /**
30
     * @var MoneyFormatter
31
     */
32
    private $formatter;
33
34
    public function __construct(MoneyFormatter $formatter, $config = [])
35
    {
36
        parent::__construct($config);
37
        $this->formatter = $formatter;
38
    }
39
40
    public function run()
41
    {
42
        if (!$this->areCurrenciesSame()) {
43
            return ResourcePriceWidget::widget([
44
                'price' => $this->old,
45
            ]);
46
        }
47
        return $this->renderDifferenceWidget();
48
    }
49
50
    private function renderDifferenceWidget()
51
    {
52
        $diff = $this->new->subtract($this->old);
53
        $diffAmount = $diff->getAmount();
54
        if ($diffAmount === 0) {
55
            return '';
56
        }
57
58
        return Html::tag(
59
            'span',
60
            ($diffAmount > 0 ? '+' : '') . $this->formatter->format($diff),
61
            ['class' => $diffAmount > 0 ? 'text-success' : 'text-danger']
62
        );
63
    }
64
65
    private function areCurrenciesSame(): bool
66
    {
67
        return $this->old->getCurrency()->equals($this->new->getCurrency());
68
    }
69
}
70