Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
20.00% covered (danger)
20.00%
3 / 15
20.00% covered (danger)
20.00%
1 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
Joke
20.00% covered (danger)
20.00%
3 / 15
20.00% covered (danger)
20.00%
1 / 5
32.09
0.00% covered (danger)
0.00%
0 / 1
 casts
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 user
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 categories
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 votes
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAverageRatingAttribute
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2
3namespace App\Models;
4
5use Illuminate\Database\Eloquent\Factories\HasFactory;
6use Illuminate\Database\Eloquent\Model;
7use Illuminate\Database\Eloquent\Relations\BelongsTo;
8use Illuminate\Database\Eloquent\Relations\BelongsToMany;
9use Illuminate\Database\Eloquent\Relations\HasMany;
10use Illuminate\Database\Eloquent\SoftDeletes;
11
12class Joke extends Model
13{
14    /** @use HasFactory<\Database\Factories\JokeFactory> */
15    use HasFactory, SoftDeletes;
16
17    protected $table = 'jokes';
18
19    protected $fillable = [
20        'title',
21        'content',
22        'reference',
23        'user_id',
24        'published_at',
25    ];
26
27    protected function casts(): array
28    {
29        return [
30            'published_at' => 'datetime',
31        ];
32    }
33
34    public function user(): BelongsTo
35    {
36        return $this->belongsTo(User::class);
37    }
38
39    public function categories(): BelongsToMany
40    {
41        return $this->belongsToMany(Category::class);
42    }
43
44    public function votes(): HasMany
45    {
46        return $this->hasMany(Vote::class);
47    }
48
49    /**
50     * Get the average rating for this joke
51     */
52    public function getAverageRatingAttribute(): float
53    {
54        $votes = $this->votes;
55        if ($votes->isEmpty()) {
56            return 0.0;
57        }
58
59        $upVotes = $votes->where('rating', 1)->count();
60        $downVotes = $votes->where('rating', -1)->count();
61        $totalVotes = $upVotes + $downVotes;
62
63        if ($totalVotes === 0) {
64            return 0.0;
65        }
66
67        return (($upVotes + $downVotes) - $downVotes) / $totalVotes * 100;
68    }
69}