<?php
namespace App\Entity;
use \App\Entity\User;
class Session {
protected static $tablename = "session";
protected User $user_instance;
use \libs\DataContain;
use \libs\DataStorage;
public function __construct() {
$this -> set_fields([
"user_id", "token", "state", "last_activity", "create_at"
]);
}
public function force_activity() {
$this -> last_activity = get_formatted_timestamp();
$this -> update();
}
public function user() :User {
if(!isset($this -> user_instance)) {
if(!$this -> user_id) {
return throw new \Exception("Error of creating User instance. User_id is undefined");
}
$this -> user_instance = new User();
$this -> user_instance -> init_by_id($this -> user_id);
}
return $this -> user_instance;
}
public function init_for_user(int $user_id) {
$this -> user_instance = new User();
if(!$this -> user() -> init_by_id($user_id)) {
return false;
}
$this -> user_id = $this -> user() -> get_id();
$this -> state = "active";
$this -> token = gen_token($this -> user() -> get_id());
$this -> last_activity = get_formatted_timestamp();
$this -> create_at = get_formatted_timestamp();
$this -> create_new();
return $this;
}
public function init_by_token(String $token) :bool {
return $this -> init_by_field("token", $token);
}
public function kill() :bool {
if(!$this -> id) {
return throw new \Exception("Tried to kill uninitialized session");
}
$this -> state = "closed";
return $this -> update();
}
}