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"
	];

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

	public function profile(): ?Profile {
		return $this -> get_pet_instance("Profile", function() {
			$profile_data = app() -> thin_builder -> select(
				Profile::$table_name,
				Profile::get_fields(),
				[["uid", "=", $this -> id()]]
			);

			return $profile_data ? new Profile($profile_data[0]["id"], $profile_data[0]) : null;
		});
	}

	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
		);
	}
}