Completed
Branch develop (eddd33)
by wen
11:44
created

Password::hashAsMD5()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
namespace Sco\Admin\Form\Elements;
4
5
class Password extends Text
6
{
7
    protected $type = 'password';
8
9
    protected $notRequired = false;
10
11
    public function __construct(string $name, string $title)
12
    {
13
        parent::__construct($name, $title);
14
15
        $this->hashAsBcrypt(); // default hash type
16
    }
17
18
    public function save()
19
    {
20
        $value = $this->getValueFromRequest();
21
        if (empty($value)) { // empty value don't save
22
            return;
23
        }
24
25
        $this->setModelAttribute($value);
26
    }
27
28
    public function getValidationRules()
29
    {
30
        $rules = parent::getValidationRules();
31
32
        if ($this->isNotRequiredWithUpdate() && $this->getModel()->exists) {
33
            if (($key = array_search('required', $rules[$this->getName()])) !== false) {
34
                unset($rules[$this->getName()][$key]);
35
            }
36
        }
37
38
        return $rules;
39
    }
40
41
    public function getValue()
42
    {
43
        return '';
44
    }
45
46
    protected function hashAsBcrypt()
47
    {
48
        $this->setMutator(function ($value) {
49
            return bcrypt($value);
50
        });
51
52
        return $this;
53
    }
54
55
    protected function hashAsMD5()
56
    {
57
        $this->setMutator(function ($value) {
58
            return md5($value);
59
        });
60
61
        return $this;
62
    }
63
64
    protected function isNotRequiredWithUpdate()
65
    {
66
        return $this->notRequired;
67
    }
68
69
    public function notRequiredWithUpdate()
70
    {
71
        $this->notRequired = true;
72
73
        return $this;
74
    }
75
}
76