78 lines
2.5 KiB
PHP
78 lines
2.5 KiB
PHP
<?php
|
|
namespace Incoviba\Repository;
|
|
|
|
use DateTimeImmutable;
|
|
use Incoviba\Common\Define;
|
|
use Incoviba\Common\Ideal;
|
|
use Incoviba\Model;
|
|
|
|
class Login extends Ideal\Repository
|
|
{
|
|
public function __construct(Define\Connection $connection, protected User $userRepository)
|
|
{
|
|
parent::__construct($connection);
|
|
$this->setTable('logins');
|
|
}
|
|
|
|
|
|
public function create(?array $data = null): Define\Model
|
|
{
|
|
$map = [
|
|
'user_id' => [
|
|
'property' => 'user',
|
|
'function' => function($data) {
|
|
return $this->userRepository->fetchById($data['user_id']);
|
|
}
|
|
],
|
|
'selector' => [],
|
|
'token' => [],
|
|
'time' => [
|
|
'property' => 'dateTime',
|
|
'function' => function($data) {
|
|
return new DateTimeImmutable($data['time']);
|
|
}
|
|
],
|
|
'status' => [
|
|
'function' => function($data) {
|
|
return $data['status'] != 0;
|
|
}
|
|
]
|
|
];
|
|
return $this->parseData(new Model\Login(), $data, $map);
|
|
}
|
|
|
|
public function save(Define\Model $model): Define\Model
|
|
{
|
|
$model->id = $this->saveNew(
|
|
['user_id', 'selector', 'token', 'time', 'status'],
|
|
[$model->user->id, $model->selector, $model->token, $model->dateTime->format('Y-m-d H:i:s'), $model->status ? 1 : 0]);
|
|
return $model;
|
|
}
|
|
|
|
public function edit(Define\Model $model, array $new_data): Define\Model
|
|
{
|
|
return $this->update($model, ['user_id', 'selector', 'token', 'time', 'status'], $new_data);
|
|
}
|
|
|
|
public function fetchByUser(int $user_id): array
|
|
{
|
|
$query = "SELECT * FROM `{$this->getTable()}` WHERE `user_id` = ?";
|
|
return $this->fetchMany($query, [$user_id]);
|
|
}
|
|
public function fetchActiveByUser(int $user_id): Model\Login
|
|
{
|
|
$query = "SELECT * FROM `{$this->getTable()}` WHERE `user_id` = ? AND `status` = 1";
|
|
return $this->fetchOne($query, [$user_id]);
|
|
}
|
|
public function fetchBySelectorAndToken(string $selector, string $token): Model\Login
|
|
{
|
|
$query = "SELECT * FROM `{$this->getTable()}` WHERE `selector` = ? AND `token` = ?";
|
|
return $this->fetchOne($query, [$selector, $token]);
|
|
}
|
|
public function fetchActiveBySelector(string $selector): Model\Login
|
|
{
|
|
$query = "SELECT * FROM `{$this->getTable()}` WHERE `selector` = ? AND `status` = 1";
|
|
return $this->fetchOne($query, [$selector]);
|
|
}
|
|
}
|