File: D:/HostingSpaces/Eurotools/euro-tools.nl/app/KommaApp/Kms/ActionLog/ActionLogService.php
<?php
namespace App\KommaApp\Kms\ActionLog;
use App\KommaApp\Kms\Core\Sections\SectionService;
use App\KommaApp\Users\Models\User;
use Carbon\Carbon;
/**
* Class ImportExportService
*
* Directs Import and Export services to do their job.
* And is responsible for loading and offering files for download
*
* @package App\KommaApp\Kms\Transfer
*/
class ActionlogService extends SectionService
{
public function __construct()
{
$this->forModelName = ActionLog::class;
}
/**
* Log an action to the database
*
*
* @param string $actionText
* @param null $payLoad Example: "['route' => '/login']". Don't make it to big!
* @param User|null $user The user or null for the authenticated user / anonymous
* @return ActionLog
*/
public static function Log(string $actionText, $payLoad = null, User $user = null):ActionLog
{
if(!$user) if(\Auth::user()) $user = \Auth::user();
$action = new ActionLog();
$action->User()->associate($user);
$action->action = $actionText;
if($payLoad) $action->payload = $payLoad;
$action->save();
return $action;
}
/**
* Returns the logs between a date range
*
* @param null|string|Carbon $from
* @param null|string|Carbon $trough
*
* @return ActionLog
*/
public static function getLogs($from = null, $trough = null, int $userFilter = 0)
{
if(!is_string($from) && !is_a($from, Carbon::class)) throw new \RuntimeException('from must be either a time string or a '.Carbon::class.' instance');
if(!is_string($trough) && !is_a($trough, Carbon::class)) throw new \RuntimeException('trough must be either a time string or a '.Carbon::class.' instance');
if(!is_a($from, Carbon::class)) $from = Carbon::createFromFormat('Y-m-d H:i:s', $from, 'Europe/Amsterdam');
if(!is_a($trough, Carbon::class)) $trough = Carbon::createFromFormat('Y-m-d H:i:s', $trough, 'Europe/Amsterdam');
$logsQueryBuilder = ActionLog::with('user')
->where([
['created_at', '>=', $from],
['created_at', '<=', $trough]
])->orderByDesc('created_at');
if($userFilter !== 0) {
$logsQueryBuilder->where('user_id', '=', $userFilter);
}
return $logsQueryBuilder;
}
}