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

UserHasInteraction::likes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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