Files
landing-api/app/Models/ContentView.php
Josep Piguillem 3897113313 Initial commit: Pireon Admin — headless admin panel and public API
Laravel 13 + Filament 5 admin panel and REST API for a non-profit developer
collective, backed by the Pireon OAuth identity server. The public site is a
separate, server-rendered application consuming /api/public/v1.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 17:55:27 +02:00

78 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Facades\DB;
/**
* One record, one language, one day, one number.
*
* Everything the panel can say about being read is a sum over these. There is
* nothing else in the row on purpose: a table that also knew the address, the
* hour and the browser would be a visitor log, and this exists to answer
* editorial questions rather than to watch anybody.
*/
#[Fillable(['locale', 'day', 'count'])]
class ContentView extends Model
{
protected function casts(): array
{
return [
'day' => 'date',
'count' => 'integer',
];
}
/**
* @return MorphTo<Model, $this>
*/
public function viewable(): MorphTo
{
return $this->morphTo();
}
/**
* Add to today's tally for one record in one language.
*
* An upsert for the same reason the 404 counter uses one: these arrive in
* bursts, and two of them racing on the same day would either violate the
* unique index or lose a count.
*/
public static function record(Model $viewable, string $locale, int $count = 1): void
{
$now = now();
static::query()->upsert(
[[
'viewable_type' => $viewable->getMorphClass(),
'viewable_id' => $viewable->getKey(),
'locale' => $locale,
'day' => $now->toDateString(),
'count' => $count,
'created_at' => $now,
'updated_at' => $now,
]],
['viewable_type', 'viewable_id', 'locale', 'day'],
[
'count' => DB::raw("content_views.count + {$count}"),
'updated_at' => $now,
],
);
}
/**
* @param Builder<$this> $query
* @return Builder<$this>
*/
public function scopeSince(Builder $query, int $days): Builder
{
return $query->where('day', '>=', now()->subDays($days)->toDateString());
}
}