PriceDifferenceWidget::areCurrenciesSame()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
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
            $widget = ResourcePriceWidget::widget([
44
                'price' => $this->old,
45
            ]);
46
            return Html::tag('span', $widget, ['class' => 'text-gray']);
47
        }
48
        return $this->renderDifferenceWidget();
49
    }
50
51
    private function renderDifferenceWidget()
52
    {
53
        $diff = $this->new->subtract($this->old);
54
        $diffAmount = $diff->getAmount();
55
        if ($diffAmount === 0) {
56
            return '';
57
        }
58
59
        return Html::tag(
60
            'span',
61
            ($diffAmount > 0 ? '+' : '') . $this->formatter->format($diff),
62
            ['class' => $diffAmount > 0 ? 'text-success' : 'text-danger']
63
        );
64
    }
65
66
    private function areCurrenciesSame(): bool
67
    {
68
        return $this->old->getCurrency()->equals($this->new->getCurrency());
69
    }
70
}
71