VoucherGenerator   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 92
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 2
dl 0
loc 92
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setPrefix() 0 4 1
A setSuffix() 0 4 1
A setSeparator() 0 4 1
A generateUnique() 0 11 2
A generate() 0 17 2
A getPrefix() 0 4 2
A getSuffix() 0 4 2
1
<?php
2
3
namespace BeyondCode\Vouchers;
4
5
use Illuminate\Support\Str;
6
7
class VoucherGenerator
8
{
9
    protected $characters;
10
    protected $mask;
11
    protected $prefix;
12
    protected $suffix;
13
    protected $separator = '-';
14
    protected $generatedCodes = [];
15
16
    public function __construct(string $characters = 'ABCDEFGHJKLMNOPQRSTUVWXYZ234567890', string $mask = '****-****')
17
    {
18
        $this->characters = $characters;
19
        $this->mask = $mask;
20
    }
21
22
    /**
23
     * @param string $prefix
24
     */
25
    public function setPrefix(?string $prefix): void
26
    {
27
        $this->prefix = $prefix;
28
    }
29
30
    /**
31
     * @param string $suffix
32
     */
33
    public function setSuffix(?string $suffix): void
34
    {
35
        $this->suffix = $suffix;
36
    }
37
38
    /**
39
     * @param string $separator
40
     */
41
    public function setSeparator(string $separator): void
42
    {
43
        $this->separator = $separator;
44
    }
45
46
    /**
47
     * @return string
48
     */
49
    public function generateUnique(): string
50
    {
51
        $code = $this->generate();
52
53
        while (in_array($code, $this->generatedCodes) === true) {
54
            $code = $this->generate();
55
        }
56
57
        $this->generatedCodes[] = $code;
58
        return $code;
59
    }
60
61
    /**
62
     * @return string
63
     */
64
    public function generate(): string
65
    {
66
        $length = substr_count($this->mask, '*');
67
68
        $code = $this->getPrefix();
69
        $mask = $this->mask;
70
        $characters = collect(str_split($this->characters));
71
72
        for ($i = 0; $i < $length; $i++) {
73
            $mask = Str::replaceFirst('*', $characters->random(1)->first(), $mask);
74
        }
75
76
        $code .= $mask;
77
        $code .= $this->getSuffix();
78
79
        return $code;
80
    }
81
82
    /**
83
     * @return string
84
     */
85
    protected function getPrefix(): string
86
    {
87
        return $this->prefix !== null ? $this->prefix . $this->separator : '';
88
    }
89
90
    /**
91
     * @return string
92
     */
93
    protected function getSuffix(): string
94
    {
95
        return $this->suffix !== null ? $this->separator . $this->suffix : '';
96
    }
97
98
}
99