SecurityHelper   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 70
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A generatePasswordHash() 0 4 1
A generateRandomString() 0 4 1
A validatePassword() 0 4 1
A generatePassword() 0 23 3
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-usuario project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\User\Helper;
13
14
use yii\base\Exception;
15
use yii\base\Security;
16
17
class SecurityHelper
18
{
19
    /**
20
     * @var Security
21
     */
22
    protected $security;
23
24 13
    public function __construct(Security $security)
25
    {
26 13
        $this->security = $security;
27 13
    }
28
29
    /**
30
     * Generates a secure hash from a password and a random salt.
31
     *
32
     * @param string   $password
33
     * @param null|int $cost
34
     *
35
     * @throws Exception
36
     * @return string
37
     *
38
     */
39 10
    public function generatePasswordHash($password, $cost = null)
40
    {
41 10
        return $this->security->generatePasswordHash($password, $cost);
42
    }
43
44
    /**
45
     * Generates a random string
46
     *
47
     * @param int $length
48
     *
49
     * @throws Exception
50
     * @return string
51
     *
52
     */
53 11
    public function generateRandomString($length = 32)
54
    {
55 11
        return $this->security->generateRandomString($length);
56
    }
57
58 5
    public function validatePassword($password, $hash)
59
    {
60 5
        return $this->security->validatePassword($password, $hash);
61
    }
62
63 2
    public function generatePassword($length)
64
    {
65
        $sets = [
66 2
            'abcdefghjkmnpqrstuvwxyz',
67
            'ABCDEFGHJKMNPQRSTUVWXYZ',
68
            '23456789',
69
        ];
70 2
        $all = '';
71 2
        $password = '';
72 2
        foreach ($sets as $set) {
73 2
            $password .= $set[array_rand(str_split($set))];
74 2
            $all .= $set;
75
        }
76
77 2
        $all = str_split($all);
78 2
        for ($i = 0; $i < $length - count($sets); ++$i) {
79 2
            $password .= $all[array_rand($all)];
80
        }
81
82 2
        $password = str_shuffle($password);
83
84 2
        return $password;
85
    }
86
}
87