PublishedTrait   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
dl 0
loc 38
rs 10
c 1
b 0
f 0
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A applyPublisedConditions() 0 6 1
A applyNotPublisedConditions() 0 5 1
1
<?php
2
3
namespace Jidaikobo\Kontiki\Models\Traits;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Query\Builder;
7
8
trait PublishedTrait
9
{
10
    protected string $publishedField = 'published_at';
11
12
    /**
13
     * Apply conditions to retrieve published posts.
14
     *
15
     * Conditions:
16
     * - Includes posts where `published_at` is `NULL` (considered as already published).
17
     * - Includes posts where `published_at` is in the past or equal to the current time.
18
     *
19
     * @param Builder $query The query builder instance.
20
     * @return Builder The modified query with applied conditions.
21
     */
22
    public function applyPublisedConditions(Builder $query): Builder
23
    {
24
        $currentTime = Carbon::now('UTC')->format('Y-m-d H:i:s');
25
        return $query->where(function ($q) use ($currentTime) {
26
            $q->whereNull($this->publishedField) // Consider NULL as published
27
              ->orWhere($this->publishedField, '<=', $currentTime);
28
        });
29
    }
30
31
    /**
32
     * Apply conditions to retrieve scheduled (future) posts.
33
     *
34
     * Conditions:
35
     * - Excludes posts where `published_at` is `NULL` (not scheduled).
36
     * - Includes posts where `published_at` is in the future.
37
     *
38
     * @param Builder $query The query builder instance.
39
     * @return Builder The modified query with applied conditions.
40
     */
41
    public function applyNotPublisedConditions(Builder $query): Builder
42
    {
43
        $currentTime = Carbon::now('UTC')->format('Y-m-d H:i:s');
44
        return $query->whereNotNull($this->publishedField) // Exclude NULL (not scheduled)
45
                     ->where($this->publishedField, '>', $currentTime);
46
    }
47
}
48