Completed
Push — master ( 42b9cd...ad572e )
by Dmitry
06:34
created

ExchangeRatesLine::sortRates()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 7
cp 0
rs 9.7998
c 0
b 0
f 0
cc 2
nc 1
nop 1
crap 6
1
<?php
2
3
namespace hipanel\modules\finance\widgets;
4
5
use hipanel\modules\finance\models\ExchangeRate;
6
use hipanel\widgets\ArraySpoiler;
7
use Tuck\Sort\Sort;
8
use Tuck\Sort\SortChain;
9
use Yii;
10
use yii\base\Widget;
11
use yii\helpers\Html;
12
13
class ExchangeRatesLine extends Widget
14
{
15
    /**
16
     * @var ExchangeRate[]
17
     */
18
    public $rates;
19
20
    /**
21
     * @var string[] pairs that should be shown first (if exist)
22
     */
23
    public $priorityPairCodes = [
24
        'USD/EUR',
25
        'EUR/USD',
26
        'USB/BTC'
27
    ];
28
29
    public function run()
30
    {
31
        if (!Yii::$app->user->can('manage') || empty($this->rates)) {
32
            return '';
33
        }
34
35
        return $this->renderLine();
36
    }
37
38
    /**
39
     * @param ExchangeRate[] $rates not sorted rates array
40
     * @return ExchangeRate[] sorted rates
41
     */
42
    private function sortRates(array $rates): array
43
    {
44
        $chain = Sort::chain()
45
            ->asc(function (ExchangeRate $rate) {
46
                $pos = array_search($rate->pairCode(), $this->priorityPairCodes, true);
47
48
                return $pos !== false ? $pos : INF;
49
            })
50
            ->compare(function (ExchangeRate $a, ExchangeRate $b) {
51
                return strnatcasecmp($a->pairCode(), $b->pairCode());
52
            });
53
54
        return $chain->values($rates);
55
    }
56
57
    protected function renderLine()
58
    {
59
        return Html::tag('span', ArraySpoiler::widget([
60
            'data' => $this->sortRates($this->rates),
61
            'visibleCount' => 3,
62
            'button' => [
63
                'label' => '+{count}',
64
                'popoverOptions' => ['html' => true],
65
            ],
66
            'hiddenDelimiter' => '<br />',
67
            'formatter' => function (ExchangeRate $model) {
68
                return Html::tag('span', $model->pairCode(), ['style' => 'font-weight: 400']) . ': ' . $model->rate;
69
            }
70
        ]), ['style' => 'padding-left: 20px; color: #737272;']);
71
    }
72
}
73