Completed
Push — master ( 46cd44...2cb6dc )
by Zura
05:26 queued 03:17
created

Promocodes::check()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Gabievi\Promocodes;
4
5
use Gabievi\Promocodes\Model\Promocode;
6
7
class Promocodes
8
{
9
    /**
10
     * Generated codes will be saved here
11
     * to be validated later.
12
     *
13
     * @var array
14
     */
15
    private $codes = [];
16
17
    /**
18
     * Length of code will be calculated from asterisks you have
19
     * set as mask in your config file.
20
     *
21
     * @var int
22
     */
23
    private $length;
24
25
    /**
26
     * Promocodes constructor.
27
     */
28
    public function __construct()
29
    {
30
        $this->codes = Promocode::pluck('code')->toArray();
31
        $this->length = substr_count(config('promocodes.mask'), '*');
32
    }
33
34
    /**
35
     * Here will be generated single code using your parameters from config.
36
     *
37
     * @return string
38
     */
39
    private function generate()
40
    {
41
        $characters = config('promocodes.characters');
42
        $mask = config('promocodes.mask');
43
        $promocode = '';
44
        $random = [];
45
46
        // take needed length of string from characters and randomize it
47
        for ($i = 1; $i <= $this->length; $i++) {
48
            $character = $characters[rand(0, strlen($characters) - 1)];
49
            $random[] = $character;
50
        }
51
52
        // shuffle randomized characters
53
        shuffle($random);
54
55
        // set prefix for promocode
56
        $promocode .= $this->getPrefix();
57
58
        // loop through asterisks and change with random symbol
59
        for ($i = 0; $i < count($random); $i++) {
60
            $mask = preg_replace('/\*/', $random[$i], $mask, 1);
61
        }
62
63
        // set updated mask as code
64
        $promocode .= $mask;
65
66
        // set suffix for promocode
67
        $promocode .= $this->getSuffix();
68
69
        return $promocode;
70
    }
71
72
    /**
73
     * Generate prefix with separator for promocode.
74
     *
75
     * @return string
76
     */
77
    private function getPrefix()
78
    {
79
        return (bool) config('promocodes.prefix') ? config('promocodes.prefix').config('promocodes.separator') : '';
80
    }
81
82
    /**
83
     * Generate suffix with separator for promocode.
84
     *
85
     * @return string
86
     */
87
    private function getSuffix()
88
    {
89
        return (bool) config('promocodes.suffix') ? config('promocodes.separator').config('promocodes.suffix') : '';
90
    }
91
92
    /**
93
     * Your code will be validated to be unique for one request.
94
     *
95
     * @param $collection
96
     * @param $new
97
     *
98
     * @return bool
99
     */
100
    private function validate($collection, $new)
101
    {
102
        return !in_array($new, array_merge($collection, $this->codes));
103
    }
104
105
    /**
106
     * Generates promocodes as many as you wish.
107
     *
108
     * @param int $amount
109
     *
110
     * @return array
111
     */
112
    public function output($amount = 1)
113
    {
114
        $collection = [];
115
116
        for ($i = 1; $i <= $amount; $i++) {
117
            $random = $this->generate();
118
119
            while (!$this->validate($collection, $random)) {
120
                $random = $this->generate();
121
            }
122
123
            $collection[] = $random;
124
        }
125
126
        return $collection;
127
    }
128
129
    /**
130
     * Save promocodes into database
131
     * Successful insert returns generated promocodes
132
     * Fail will return NULL.
133
     *
134
<<<<<<< HEAD
135
     * @param int   $amount
136
     * @param null  $reward
137
     * @param array $data
138
     *
139
     * @return static
140
     */
141
    public function create($amount = 1, $reward = null, array $data = [])
0 ignored issues
show
Coding Style introduced by
Possible parse error: non-abstract method defined as abstract
Loading history...
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
142
=======
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_IS_IDENTICAL, expecting ';' or '{'
Loading history...
143
     * @param int  $amount
144
     * @param null $reward
145
     *
146
     * @return static
147
     */
148
    public function create($amount = 1, $reward = null)
149
>>>>>>> 46cd444ffd48ecc5f447fb653487856224e958d6
150
    {
151
        $records = [];
152
153
        // loop though each promocodes required
154
        foreach ($this->output($amount) as $code) {
155
            $records[] = [
156
                'code' => $code,
157
                'reward' => $reward,
158
                'data' => json_encode($data),
159
            ];
160
        }
161
162
        // check for insertion of record
163
        if (Promocode::insert($records)) {
164
            return collect($records);
165
        }
166
167
        return collect([]);
168
    }
169
170
    /**
171
     * Check promocode in database if it is valid.
172
     *
173
     * @param $code
174
     *
175
     * @return bool
176
     */
177
    public function check($code)
178
    {
179
        return Promocode::byCode($code)->fresh()->exists();
180
    }
181
182
    /**
183
     * Apply promocode to user that it's used from now.
184
     *
185
     * @param $code
186
     *
187
     * @return mixed
188
     */
189
    public function apply($code)
190
    {
191
        $promocode = Promocode::byCode($code)->fresh();
192
193
        // check if exists not used code
194
        if ($promocode->exists()) {
195
            $record = $promocode->first();
196
            $record->is_used = true;
197
198
            // update promocode as it is used
199
            if ($record->save()) {
200
                return $record ?: true;
201
            }
202
        }
203
204
        return false;
205
    }
206
}
207