|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of Laravel Love. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Anton Komarev <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
declare(strict_types=1); |
|
13
|
|
|
|
|
14
|
|
|
namespace Cog\Laravel\Love\Reactable\Models\Traits; |
|
15
|
|
|
|
|
16
|
|
|
use Cog\Contracts\Love\Reactable\Exceptions\AlreadyRegisteredAsLoveReactant; |
|
17
|
|
|
use Cog\Contracts\Love\Reactant\Facades\Reactant as ReactantFacadeInterface; |
|
18
|
|
|
use Cog\Contracts\Love\Reactant\Models\Reactant as ReactantInterface; |
|
19
|
|
|
use Cog\Laravel\Love\Reactable\Observers\ReactableObserver; |
|
20
|
|
|
use Cog\Laravel\Love\Reactant\Facades\Reactant as ReactantFacade; |
|
21
|
|
|
use Cog\Laravel\Love\Reactant\Models\NullReactant; |
|
22
|
|
|
use Cog\Laravel\Love\Reactant\Models\Reactant; |
|
23
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @mixin \Cog\Contracts\Love\Reactable\Models\Reactable |
|
27
|
|
|
*/ |
|
28
|
|
|
trait Reactable |
|
29
|
|
|
{ |
|
30
|
|
|
protected static function bootReactable(): void |
|
31
|
|
|
{ |
|
32
|
|
|
static::observe(ReactableObserver::class); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function loveReactant(): BelongsTo |
|
36
|
|
|
{ |
|
37
|
|
|
return $this->belongsTo(Reactant::class, 'love_reactant_id'); |
|
|
|
|
|
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function getLoveReactant(): ReactantInterface |
|
41
|
|
|
{ |
|
42
|
|
|
return $this->getAttribute('loveReactant') ?? new NullReactant($this); |
|
|
|
|
|
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function viaLoveReactant(): ReactantFacadeInterface |
|
46
|
|
|
{ |
|
47
|
|
|
return new ReactantFacade($this->getLoveReactant()); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function isRegisteredAsLoveReactant(): bool |
|
51
|
|
|
{ |
|
52
|
|
|
return !$this->isNotRegisteredAsLoveReactant(); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
public function isNotRegisteredAsLoveReactant(): bool |
|
56
|
|
|
{ |
|
57
|
|
|
return $this->getAttributeValue('love_reactant_id') === null; |
|
|
|
|
|
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public function registerAsLoveReactant(): void |
|
61
|
|
|
{ |
|
62
|
|
|
if ($this->isRegisteredAsLoveReactant()) { |
|
63
|
|
|
throw new AlreadyRegisteredAsLoveReactant(); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** @var \Cog\Contracts\Love\Reactant\Models\Reactant $reactant */ |
|
67
|
|
|
$reactant = $this->loveReactant()->create([ |
|
68
|
|
|
'type' => $this->getMorphClass(), |
|
|
|
|
|
|
69
|
|
|
]); |
|
70
|
|
|
|
|
71
|
|
|
$this->setAttribute('love_reactant_id', $reactant->getId()); |
|
|
|
|
|
|
72
|
|
|
$this->save(); |
|
|
|
|
|
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|