Newer
Older
smart-home-server / server / SHServ / Entities / User.php
<?php

namespace SHServ\Entities;

use \SHServ\Entities\Session;
use \SHServ\Entities\Profile;

class User extends \SHServ\Middleware\Entity {
	public static $table_name = "users";
	protected static $fields = [
		"id", "role", "nickname", "password", "create_at", "update_at"
	];
	
	protected ?Profile $profile = null;

	public function __construct(Int $uid, Array $data = []) {
		parent::__construct(self::$table_name, $uid, $data);

		$profile_data = app() -> thin_builder -> select(
			Profile::$table_name,
			Profile::get_fields(),
			[["uid", "=", $uid]]
		);

		if($profile_data) {
			$this -> profile = new Profile($profile_data[0]["id"], $profile_data[0]);
		}
	}

	public function profile(): ?Profile {
		return $this -> profile;
	}

	public function last_session(): ?\SHServ\Entities\Session {
		return $this -> get_pet_instance("Session", function() {
			return app() -> factory -> getter() -> get_session_by("uid", $this -> id());
		});
	}

	public function role_is(String $role_name): Bool {
		return $this -> role == $role_name;
	}

	// Static methods

	public static function is_exists_by(String $field_name, String $field_value): Bool {
		return app() -> utils -> table_row_is_exists(
			app() -> thin_builder,
			self::$table_name,
			$field_name,
			$field_value
		);
	}
}