Passed
Pull Request — main (#4)
by Tan
20:49
created

UserHasInteraction::forgetInteractions()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 4
c 1
b 0
f 1
dl 0
loc 9
rs 10
cc 3
nc 2
nop 1
1
<?php
2
3
namespace CSlant\LaravelLike;
4
5
use CSlant\LaravelLike\Enums\InteractionTypeEnum;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Relations\HasMany;
8
9
/**
10
 * Trait UserInteraction
11
 * use this trait in your User model
12
 *
13
 * @package CSlant\LaravelLike\Traits
14
 * @mixin Model
15
 * @method HasMany hasMany(string $related, string $foreignKey = null, string $localKey = null)
16
 */
17
trait UserHasInteraction
18
{
19
    /**
20
     * Get all likes of the user. This method is used for eager loading.
21
     *
22
     * @return HasMany
23
     */
24
    public function likes(): HasMany
25
    {
26
        $interactionModel = (string) (config('like.interaction_model') ?? 'CSlant\LaravelLike\Models\Like');
27
        $userForeignKey = (string) (config('like.users.foreign_key') ?? 'user_id');
28
29
        return $this->hasMany($interactionModel, $userForeignKey);
30
    }
31
32
    /**
33
     * Check if the user has liked the given model.
34
     *
35
     * @param  string  $interactionType
36
     *
37
     * @return static
38
     */
39
    public function forgetInteractionsOfType(string $interactionType): static
40
    {
41
        $this->likes()->where('type', $interactionType)->delete();
42
43
        return $this;
44
    }
45
46
    /**
47
     * Check if the user has liked the given model.
48
     *
49
     * @param  null|string  $interactionType
50
     *
51
     * @return static
52
     */
53
    public function forgetInteractions(?string $interactionType = null): static
54
    {
55
        if ($interactionType && in_array($interactionType, InteractionTypeEnum::getValuesAsStrings())) {
56
            return $this->forgetInteractionsOfType($interactionType);
57
        }
58
59
        $this->likes()->delete();
60
61
        return $this;
62
    }
63
}
64