Completed
Push — master ( 644c62...cdc390 )
by Max
01:16
created

UpdateHelper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 1
dl 0
loc 34
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A updateAllFields() 0 7 2
A updateField() 0 20 5
1
<?php
2
/*
3
 *  @copyright (c) 2019 Mendel <[email protected]>
4
 *  @license see license.txt
5
 */
6
7
namespace drycart\data;
8
9
/**
10
 * Description of UpdateHelper
11
 *
12
 * @author mendel
13
 */
14
class UpdateHelper
15
{
16
    // Dont change order - longer will be first (before other started from same symbols)
17
    const RULES = ['set:', 'sum:', 'max:', 'min:'];
18
    
19
    public static function updateAllFields(&$data, array $changes) : void
20
    {
21
        foreach($changes as $key=>$value) {
22
            [$rule, $fieldName] = StrHelper::findPrefix($key, static::RULES, 'set:');
0 ignored issues
show
Bug introduced by
The variable $rule does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $fieldName does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
23
            static::updateField($data, $value, $rule, $fieldName);
24
        }
25
    }
26
    
27
    public static function updateField(&$data, $value, string $rule, string $fieldName) : void
28
    {
29
        $current = $data[$fieldName];
30
        switch ($rule) {
31
            case 'set:':
32
                $data[$fieldName] = $value;
33
                break;
34
            case 'sum:':
35
                $data[$fieldName] = ($current ?? 0) + $value;
36
                break;
37
            case 'max:':
38
                $data[$fieldName] = max([$current, $value]);
39
                break;
40
            case 'min:':
41
                $data[$fieldName] = min([$current, $value]);
42
                break;
43
            default:
44
                throw new \Exception('Unknown type '.$rule);
45
        }
46
    }
47
}
48