1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Gabievi\Promocodes\Traits; |
4
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
6
|
|
|
use Gabievi\Promocodes\Models\Promocode; |
7
|
|
|
use Gabievi\Promocodes\Facades\Promocodes; |
8
|
|
|
use Gabievi\Promocodes\Exceptions\AlreadyUsedException; |
9
|
|
|
|
10
|
|
|
trait Rewardable |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Get the promocodes that are related to user. |
14
|
|
|
* |
15
|
|
|
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany |
16
|
|
|
*/ |
17
|
|
|
public function promocodes() |
18
|
|
|
{ |
19
|
|
|
return $this->belongsToMany(Promocode::class, config('promocodes.relation_table')) |
|
|
|
|
20
|
|
|
->withPivot('used_at'); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Redeem promocode to user and get callback. |
25
|
|
|
* |
26
|
|
|
* @param string $code |
27
|
|
|
* @param null|\Closure $callback |
28
|
|
|
* |
29
|
|
|
* @return null|\Gabievi\Promocodes\Models\Promocode |
30
|
|
|
* @throws AlreadyUsedException |
31
|
|
|
*/ |
32
|
|
|
public function redeemCode($code, $callback = null) |
33
|
|
|
{ |
34
|
|
|
return $this->applyCode($code, $callback); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Apply promocode to user and get callback. |
39
|
|
|
* |
40
|
|
|
* @param string $code |
41
|
|
|
* @param null|\Closure $callback |
42
|
|
|
* |
43
|
|
|
* @return bool|null|\Gabievi\Promocodes\Models\Promocode |
44
|
|
|
* @throws AlreadyUsedException |
45
|
|
|
*/ |
46
|
|
|
public function applyCode($code, $callback = null) |
47
|
|
|
{ |
48
|
|
|
if ($promocode = Promocodes::check($code)) { |
49
|
|
|
if ($promocode->isDisposable() && $promocode->users()->wherePivot(config('promocodes.related_pivot_key'), $this->id)->exists()) { |
|
|
|
|
50
|
|
|
throw new AlreadyUsedException; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$promocode->users()->attach($this->id, [ |
54
|
|
|
config('promocodes.foreign_pivot_key') => $promocode->id, |
55
|
|
|
'used_at' => Carbon::now(), |
56
|
|
|
]); |
57
|
|
|
|
58
|
|
|
if (!is_null($promocode->quantity)) { |
59
|
|
|
$promocode->quantity -= 1; |
60
|
|
|
$promocode->save(); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$promocode->load('users'); |
64
|
|
|
|
65
|
|
|
if (is_callable($callback)) { |
66
|
|
|
$callback($promocode); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $promocode; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if (is_callable($callback)) { |
73
|
|
|
$callback(null); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return false; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.