Operator::operation()   C
last analyzed

Complexity

Conditions 12
Paths 30

Size

Total Lines 45
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 5.1612
c 0
b 0
f 0
cc 12
eloc 32
nc 30
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Dwo\Aggregator;
4
5
use Dwo\Aggregator\Model\Aggregate;
6
use Malenki\Math\Stats\Stats;
7
8
/**
9
 * Class Operator
10
 *
11
 * @author Dave Www <[email protected]>
12
 */
13
class Operator
14
{
15
    const MEAN = 'mean';
16
    const MEAN_HARMONIC = 'mean_harmonic';
17
    const MEDIAN = 'median';
18
19
    /**
20
     * @param Aggregate $aggregate
21
     * @param array     $saveKeys
22
     */
23
    public static function operation(Aggregate $aggregate, array $saveKeys = [])
24
    {
25
        $data = $aggregate->getData();
26
27
        $operations = [];
28
        foreach (array_keys($data) as $key) {
29
            if (isset($saveKeys[$key])) {
30
                $operations[$key] = $saveKeys[$key];
31
            }
32
        }
33
34
        foreach ($operations as $key => $operation) {
35
            if (!count($data[$key])) {
36
                switch ($operation) {
37
                    default:
38
                    case self::MEAN:
39
                    case self::MEAN_HARMONIC:
40
                    case self::MEDIAN:
41
                        $data[$key] = 0;
42
                        break;
43
                }
44
                continue;
45
            }
46
47
            $stats = new Stats($data[$key]);
48
            switch ($operation) {
49
                default:
50
                    if (!method_exists($stats, $operation)) {
51
                        $operation = self::MEAN;
52
                    }
53
                    $data[$key] = $stats->$operation();
54
                case self::MEAN:
55
                    $data[$key] = $stats->mean();
56
                    break;
57
                case self::MEAN_HARMONIC:
58
                    $data[$key] = $stats->harmonicMean();
59
                    break;
60
                case self::MEDIAN:
61
                    $data[$key] = $stats->median();
62
                    break;
63
            }
64
        }
65
66
        $aggregate->setData($data);
67
    }
68
69
}