HashHelper   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 32
c 1
b 0
f 0
dl 0
loc 78
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A hashEntities() 0 11 1
A hash2dEntities() 0 16 2
A getHash() 0 22 6
1
<?php
2
3
/*
4
 * This file is part of the TheAlternativeZurich/events project.
5
 *
6
 * (c) Florian Moser <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace App\Helper;
13
14
use App\Entity\Traits\IdTrait;
15
16
class HashHelper
17
{
18
    const HASH_LENGTH = 20;
19
20
    /**
21
     * generates a hash from alpha numeric characters of length 20.
22
     *
23
     * @return string
24
     */
25
    public static function getHash()
26
    {
27
        $newHash = '';
28
        //0-9, A-Z, a-z
29
        $allowedRanges = [[48, 57], [65, 90], [97, 122]];
30
        $rangeCount = \count($allowedRanges);
31
        for ($i = 0; $i < static::HASH_LENGTH; ++$i) {
32
            $rand = mt_rand(20, 160);
33
            $allowed = false;
34
            for ($j = 0; $j < $rangeCount; ++$j) {
35
                if ($allowedRanges[$j][0] <= $rand && $allowedRanges[$j][1] >= $rand) {
36
                    $allowed = true;
37
                }
38
            }
39
            if ($allowed) {
40
                $newHash .= \chr($rand);
41
            } else {
42
                --$i;
43
            }
44
        }
45
46
        return $newHash;
47
    }
48
49
    /**
50
     * creates a hash from the entities using the guid.
51
     *
52
     * @param $entities
53
     *
54
     * @return string
55
     */
56
    public static function hashEntities($entities)
57
    {
58
        return hash('sha256',
59
            implode(
60
                ',',
61
                array_map(
62
                    function ($issue) {
63
                        /* @var IdTrait $issue */
64
                        return $issue->getId();
65
                    },
66
                    $entities)
67
            )
68
        );
69
    }
70
71
    /**
72
     * creates a hash from a 2d arrays of entities using the guid.
73
     *
74
     * @param IdTrait[][] $entities
75
     *
76
     * @return string
77
     */
78
    public static function hash2dEntities($entities)
79
    {
80
        $res = [];
81
        foreach ($entities as $innerEntities) {
82
            $res[] = implode(
83
                ',',
84
                array_map(
85
                    function ($issue) {
86
                        /* @var IdTrait $issue */
87
                        return $issue->getId();
88
                    },
89
                    $innerEntities)
90
            );
91
        }
92
93
        return hash('sha256', implode(',', $res));
94
    }
95
}
96