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\Reactant\ReactionCounter\Services; |
15
|
|
|
|
16
|
|
|
use Cog\Contracts\Love\Reactant\Models\Reactant as ReactantInterface; |
17
|
|
|
use Cog\Contracts\Love\Reactant\ReactionCounter\Models\ReactionCounter as ReactionCounterInterface; |
18
|
|
|
use Cog\Contracts\Love\Reaction\Models\Reaction as ReactionInterface; |
19
|
|
|
use Cog\Contracts\Love\ReactionType\Models\ReactionType as ReactionTypeInterface; |
20
|
|
|
use Cog\Laravel\Love\Reactant\ReactionCounter\Models\NullReactionCounter; |
21
|
|
|
|
22
|
|
|
final class ReactionCounterService |
23
|
|
|
{ |
24
|
|
|
private ReactantInterface $reactant; |
25
|
|
|
|
26
|
|
|
public function __construct( |
27
|
|
|
ReactantInterface $reactant, |
28
|
|
|
) { |
29
|
|
|
$this->reactant = $reactant; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function addReaction( |
33
|
|
|
ReactionInterface $reaction, |
34
|
|
|
): void { |
35
|
|
|
$counter = $this->findOrCreateCounterOfType($reaction->getType()); |
36
|
|
|
$counter->incrementCount(1); |
37
|
|
|
$counter->incrementWeight($reaction->getWeight()); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function removeReaction( |
41
|
|
|
ReactionInterface $reaction, |
42
|
|
|
): void { |
43
|
|
|
$counter = $this->findOrCreateCounterOfType($reaction->getType()); |
44
|
|
|
|
45
|
|
|
if ($counter->getCount() === 0) { |
46
|
|
|
return; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$counter->decrementCount(1); |
50
|
|
|
$counter->decrementWeight($reaction->getWeight()); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
private function findCounterOfType( |
54
|
|
|
ReactionTypeInterface $reactionType, |
55
|
|
|
): ReactionCounterInterface { |
56
|
|
|
return $this->reactant->getReactionCounterOfType($reactionType); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function findOrCreateCounterOfType( |
60
|
|
|
ReactionTypeInterface $reactionType, |
61
|
|
|
): ReactionCounterInterface { |
62
|
|
|
$counter = $this->findCounterOfType($reactionType); |
63
|
|
|
if ($counter instanceof NullReactionCounter) { |
64
|
|
|
$this->reactant->createReactionCounterOfType($reactionType); |
65
|
|
|
$counter = $this->findCounterOfType($reactionType); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $counter; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|