Checksum::prepareData()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 1
1
<?php
2
3
4
namespace carono\checksum;
5
6
/**
7
 * Class Checksum
8
 *
9
 * @package carono\checksum
10
 */
11
class Checksum
12
{
13
    /**
14
     * @param $array
15
     * @param null $salt
16
     * @return string
17
     */
18
    public static function calculate($array, $salt = null)
19
    {
20
        if ($key = static::formKey($array)) {
21
            return hash('sha256', $key . $salt);
22
        }
23
24
        return null;
25
    }
26
27
    /**
28
     * @param $array
29
     * @param $hash
30
     * @param null $salt
31
     * @return bool
32
     */
33
    public static function validate($array, $hash, $salt = null)
34
    {
35
        return static::calculate($array, $salt) === $hash;
36
    }
37
38
    /**
39
     * @param $array
40
     * @return array
41
     */
42
    public static function formKeyPartials($array)
43
    {
44
        $array = static::prepareData($array);
45
        $result = [];
46
        foreach ((array)$array as $model => $values) {
47
            foreach (array_keys((array)$values) as $key) {
48
                $result[] = implode('=', [$model, $key]);
49
            }
50
        }
51
        $result = array_unique($result);
52
        sort($result);
53
        return $result;
54
    }
55
56
    /**
57
     * @param $array
58
     * @return array
59
     */
60
    protected static function prepareData($array)
61
    {
62
        return array_filter($array ?: [], 'is_array');
63
    }
64
65
    /**
66
     * @param $array
67
     * @return string
68
     */
69
    public static function formKey($array)
70
    {
71
        return implode('|', static::formKeyPartials($array));
72
    }
73
74
    /**
75
     * @param $post
76
     * @param $stack
77
     * @param null $salt
78
     * @return bool
79
     */
80
    public static function compareStacks($post, $stack, $salt = null)
81
    {
82
        $checksum = static::calculate($stack, $salt);
83
        $post = static::mergeStacks($post, $stack);
84
        return static::validate($post, $checksum, $salt);
85
    }
86
87
    /**
88
     * @param $post
89
     * @param $stack
90
     * @return mixed
91
     */
92
    protected static function mergeStacks($post, $stack)
93
    {
94
        $postPartials = static::formKeyPartials($post);
95
        $stackPartials = static::formKeyPartials($stack);
96
        foreach (array_diff($stackPartials, $postPartials) as $lostPartial) {
97
            list($formName, $attribute) = explode('=', $lostPartial);
98
            $post[$formName][$attribute] = '';
99
        }
100
        return $post;
101
    }
102
}