chartboard/app/Models/SharedLinkModel.php
2026-03-30 09:51:33 +05:30

85 lines
2.1 KiB
PHP

<?php
namespace App\Models;
use CodeIgniter\Model;
class SharedLinkModel extends Model
{
protected $table = 'shared_links';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $protectFields = true;
protected $allowedFields = [
'token',
'type',
'resource_id',
'workspace_id',
'password_hash',
'expires_at',
'view_count',
'is_active',
'created_by',
];
protected bool $allowEmptyInserts = false;
protected bool $updateOnlyChanged = true;
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
public function findActiveByToken(string $token): ?array
{
$token = trim($token);
if ($token === '') {
return null;
}
$row = $this->where('token', $token)->where('is_active', 1)->first();
if (! $row) {
return null;
}
$exp = $row['expires_at'] ?? null;
if ($exp && strtotime((string) $exp) < time()) {
return null;
}
return $row;
}
public function incrementViewCount(int $id): void
{
$this->builder()->where('id', $id)->set('view_count', 'view_count + 1', false)->update();
}
/**
* @return list<array<string, mixed>>
*/
public function forResource(string $type, int $resourceId, int $workspaceId): array
{
return $this->where('type', $type)
->where('resource_id', $resourceId)
->where('workspace_id', $workspaceId)
->where('is_active', 1)
->orderBy('id', 'DESC')
->findAll();
}
public function findOwned(int $id, int $workspaceId): ?array
{
$row = $this->where('id', $id)->where('workspace_id', $workspaceId)->first();
return $row ?: null;
}
public static function generateToken(): string
{
return bin2hex(random_bytes(32));
}
}