2
0
Fork 0
forked from flashii/eeprom
eeprom-nabucco/src/User.php

91 lines
2.4 KiB
PHP

<?php
namespace EEPROM;
use Exception;
use JsonSerializable;
use Index\Data\IDbConnection;
use Index\Data\DbType;
class UserNotFoundException extends Exception {}
class User implements JsonSerializable {
private static $active;
public static function hasActive(): bool {
return !empty(self::$active);
}
public static function active(): self {
return self::$active;
}
public function __construct(
private $id = 0,
private $sizeMultiplier = 0,
private $created = 0,
private $restricted = 0,
) {}
public function __destruct() {
if($this === self::$active)
self::$active = null;
}
public function setActive(): self {
self::$active = $this;
return $this;
}
public function getId(): int {
return $this->id;
}
public function getSizeMultiplier(): int {
return $this->sizeMultiplier;
}
public function getCreated(): int {
return $this->created;
}
public function getRestricted(): int {
return $this->restricted;
}
public function isRestricted(): bool {
return $this->restricted > 0;
}
public function jsonSerialize(): mixed {
return [
'id' => $this->id,
'size_multi' => $this->sizeMultiplier,
'created' => date('c', $this->created),
'restricted' => $this->restricted < 1 ? null : date('c', $this->restricted),
];
}
public static function byId(IDbConnection $conn, int $userId): self {
if($userId < 1)
throw new UserNotFoundException;
$create = $conn->prepare('INSERT IGNORE INTO `prm_users` (`user_id`) VALUES (?)');
$create->addParameter(1, $userId, DbType::INTEGER);
$create->execute();
$get = $conn->prepare(
'SELECT `user_id`, `user_size_multiplier`, UNIX_TIMESTAMP(`user_created`) AS `user_created`,'
. ' UNIX_TIMESTAMP(`user_restricted`) AS `user_restricted` FROM `prm_users` WHERE `user_id` = ?'
);
$get->addParameter(1, $userId, DbType::INTEGER);
$get->execute();
$result = $get->getResult();
if(!$result->next())
throw new UserNotFoundException;
return new static(
$result->getInteger(0),
$result->getInteger(1),
$result->getInteger(2),
$result->getInteger(3),
);
}
}