Completed
Pull Request — master (#62)
by Dmitry
05:57
created

ChargesGrouper   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 44
ccs 0
cts 16
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A group() 0 15 3
A sortByServerName() 0 6 1
1
<?php
2
3
namespace hipanel\modules\finance\helpers;
4
5
use hipanel\modules\finance\models\Charge;
6
use Tuck\Sort\Sort;
7
use Tuck\Sort\SortChain;
8
9
/**
10
 * Class ChargesGrouper can be used to group charges inside $charge by common_object_id
11
 */
12
class ChargesGrouper
13
{
14
    /**
15
     * @var Charge[]
16
     */
17
    private $charges;
18
19
    /**
20
     * ChargesGrouper constructor.
21
     * @param Charge[] $charges
22
     */
23
    public function __construct(array $charges)
24
    {
25
        $this->charges = $charges;
26
    }
27
28
    /**
29
     * @return array of two elements:
30
     * 0: common_object_id => common_object_id, common_object_name
31
     * 1: common_object_id => array Charge[][] by common_object_id
32
     */
33
    public function group()
34
    {
35
        /** @var Charge[] $idToNameObject */
36
        $idToNameObject = [];
37
        /** @var Charge[][] $chargesByMainObject */
38
        $chargesByMainObject = [];
39
        foreach ($this->charges as $charge) {
40
            $chargesByMainObject[$charge->common_object_id][$charge->id] = $charge;
41
        }
42
        foreach ($this->charges as $charge) {
43
            $idToNameObject[$charge->common_object_id] = $charge;
44
        }
45
        $idToNameObject = $this->sortByServerName()->values($idToNameObject);
46
        return [$idToNameObject, $chargesByMainObject];
47
    }
48
49
    private function sortByServerName(): SortChain
50
    {
51
        return Sort::chain()->compare(function (Charge $a, Charge $b) {
52
            return strnatcasecmp($a->common_object_name, $b->common_object_name);
53
        });
54
    }
55
}
56