Vouchers::getUniqueVoucher()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace BeyondCode\Vouchers;
4
5
use BeyondCode\Vouchers\Exceptions\VoucherExpired;
6
use BeyondCode\Vouchers\Exceptions\VoucherIsInvalid;
7
use BeyondCode\Vouchers\Models\Voucher;
8
use Illuminate\Database\Eloquent\Model;
9
10
class Vouchers
11
{
12
    /** @var VoucherGenerator */
13
    private $generator;
14
    /** @var \BeyondCode\Vouchers\Models\Voucher  */
15
    private $voucherModel;
16
17
    public function __construct(VoucherGenerator $generator)
18
    {
19
        $this->generator = $generator;
20
        $this->voucherModel = app(config('vouchers.model', Voucher::class));
21
    }
22
23
    /**
24
     * Generate the specified amount of codes and return
25
     * an array with all the generated codes.
26
     *
27
     * @param int $amount
28
     * @return array
29
     */
30
    public function generate(int $amount = 1): array
31
    {
32
        $codes = [];
33
34
        for ($i = 1; $i <= $amount; $i++) {
35
            $codes[] = $this->getUniqueVoucher();
36
        }
37
38
        return $codes;
39
    }
40
41
    /**
42
     * @param Model $model
43
     * @param int $amount
44
     * @param array $data
45
     * @param null $expires_at
46
     * @return array
47
     */
48
    public function create(Model $model, int $amount = 1, array $data = [], $expires_at = null)
49
    {
50
        $vouchers = [];
51
52
        foreach ($this->generate($amount) as $voucherCode) {
53
            $vouchers[] = $this->voucherModel->create([
54
                'model_id' => $model->getKey(),
55
                'model_type' => $model->getMorphClass(),
56
                'code' => $voucherCode,
57
                'data' => $data,
58
                'expires_at' => $expires_at,
59
            ]);
60
        }
61
62
        return $vouchers;
63
    }
64
65
    /**
66
     * @param string $code
67
     * @throws VoucherIsInvalid
68
     * @throws VoucherExpired
69
     * @return Voucher
70
     */
71
    public function check(string $code)
72
    {
73
        $voucher = $this->voucherModel->whereCode($code)->first();
74
75
        if (is_null($voucher)) {
76
            throw VoucherIsInvalid::withCode($code);
77
        }
78
        if ($voucher->isExpired()) {
79
            throw VoucherExpired::create($voucher);
80
        }
81
82
        return $voucher;
83
    }
84
85
    /**
86
     * @return string
87
     */
88
    protected function getUniqueVoucher(): string
89
    {
90
        $voucher = $this->generator->generateUnique();
91
92
        while ($this->voucherModel->whereCode($voucher)->count() > 0) {
93
            $voucher = $this->generator->generateUnique();
94
        }
95
96
        return $voucher;
97
    }
98
}
99