ChargesGrouper::sortByServerName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 5
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\helpers;
12
13
use hipanel\modules\finance\models\Charge;
14
use Tuck\Sort\Sort;
15
use Tuck\Sort\SortChain;
16
17
/**
18
 * Class ChargesGrouper can be used to group charges inside $charge by commonObject->id.
19
 */
20
class ChargesGrouper
21
{
22
    /**
23
     * @var Charge[]
24
     */
25
    private $charges;
26
27
    /**
28
     * ChargesGrouper constructor.
29
     * @param Charge[] $charges
30
     */
31
    public function __construct(array $charges)
32
    {
33
        $this->charges = $charges;
34
    }
35
36
    /**
37
     * @return array of two elements:
38
     * 0: commonObject->id => commonObject->id, commonObject->name
39
     * 1: commonObject->id => array Charge[][] by commonObject->id
40
     */
41
    public function group()
42
    {
43
        /** @var Charge[] $idToNameObject */
44
        $idToNameObject = [];
45
        /** @var Charge[][] $chargesByMainObject */
46
        $chargesByMainObject = [];
47
        foreach ($this->charges as $charge) {
48
            $chargesByMainObject[$charge->commonObject->id][$charge->id] = $charge;
49
        }
50
        foreach ($this->charges as $charge) {
51
            $idToNameObject[$charge->commonObject->id] = $charge;
52
        }
53
        $idToNameObject = $this->sortByServerName()->values($idToNameObject);
54
55
        return [$idToNameObject, $chargesByMainObject];
56
    }
57
58
    private function sortByServerName(): SortChain
59
    {
60
        return Sort::chain()->compare(function (Charge $a, Charge $b) {
61
            return strnatcasecmp($a->commonObject->name, $b->commonObject->name);
62
        });
63
    }
64
}
65