findOrCreateReactionTotalFor()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 11
rs 10
cc 2
nc 2
nop 1
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\ReactionTotal\Services;
15
16
use Cog\Contracts\Love\Reactant\Models\Reactant as ReactantInterface;
17
use Cog\Contracts\Love\Reactant\ReactionTotal\Models\ReactionTotal as ReactionTotalInterface;
18
use Cog\Contracts\Love\Reaction\Models\Reaction as ReactionInterface;
19
use Cog\Laravel\Love\Reactant\ReactionTotal\Models\NullReactionTotal;
20
21
final class ReactionTotalService
22
{
23
    private ReactionTotalInterface $reactionTotal;
24
25
    public function __construct(
26
        ReactantInterface $reactant,
27
    ) {
28
        $this->reactionTotal = $this->findOrCreateReactionTotalFor($reactant);
29
    }
30
31
    public function addReaction(
32
        ReactionInterface $reaction,
33
    ): void {
34
        $this->reactionTotal->incrementCount(1);
35
        $this->reactionTotal->incrementWeight($reaction->getWeight());
36
    }
37
38
    public function removeReaction(
39
        ReactionInterface $reaction,
40
    ): void {
41
        if ($this->reactionTotal->getCount() === 0) {
42
            return;
43
        }
44
45
        $this->reactionTotal->decrementCount(1);
46
        $this->reactionTotal->decrementWeight($reaction->getWeight());
47
    }
48
49
    private function findOrCreateReactionTotalFor(
50
        ReactantInterface $reactant,
51
    ): ReactionTotalInterface {
52
        $total = $reactant->getReactionTotal();
53
54
        if ($total instanceof NullReactionTotal) {
55
            $reactant->createReactionTotal();
56
            $total = $reactant->getReactionTotal();
57
        }
58
59
        return $total;
60
    }
61
}
62