Completed
Push — master ( 5ee4c9...308b6a )
by Antonio
05:05
created

SecurityHelper::generatePassword()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 23
ccs 0
cts 12
cp 0
rs 9.0856
cc 3
eloc 15
nc 4
nop 1
crap 12
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\Security;
15
16
class SecurityHelper
17
{
18
    /**
19
     * @var Security
20
     */
21
    protected $security;
22
23 2
    public function __construct(Security $security)
24
    {
25 2
        $this->security = $security;
26 2
    }
27
28
    /**
29
     * Generates a secure hash from a password and a random salt.
30
     *
31
     * @param string   $password
32
     * @param null|int $cost
33
     *
34
     * @return string
35
     */
36
    public function generatePasswordHash($password, $cost = null)
37
    {
38
        return $this->security->generatePasswordHash($password, $cost);
39
    }
40
41
    public function generateRandomString($length = 32)
42
    {
43
        return $this->security->generateRandomString($length);
44
    }
45
46
    public function validatePassword($password, $hash)
47
    {
48
        return $this->security->validatePassword($password, $hash);
49
    }
50
51
    public function generatePassword($length)
52
    {
53
        $sets = [
54
            'abcdefghjkmnpqrstuvwxyz',
55
            'ABCDEFGHJKMNPQRSTUVWXYZ',
56
            '23456789',
57
        ];
58
        $all = '';
59
        $password = '';
60
        foreach ($sets as $set) {
61
            $password .= $set[array_rand(str_split($set))];
62
            $all .= $set;
63
        }
64
65
        $all = str_split($all);
66
        for ($i = 0; $i < $length - count($sets); ++$i) {
67
            $password .= $all[array_rand($all)];
68
        }
69
70
        $password = str_shuffle($password);
71
72
        return $password;
73
    }
74
}
75