Link.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace app\Types\DatabaseObjects;
  3. use app\Hajeebtok;
  4. use app\Interfaces\IDatabaseObject;
  5. use app\Logger;
  6. use app\Types\LinkEnum;
  7. use Hajeebtok\Types\Exceptions\SecurityFaultException;
  8. class Link implements IDatabaseObject
  9. {
  10. public private(set) ?int $id;
  11. public private(set) ?int $account_id;
  12. public private(set) ?LinkEnum $type;
  13. public private(set) ?string $url;
  14. public function __construct(?int $id = null, ?int $account_id = null, ?LinkEnum $type = null, ?string $url = null) {
  15. $this->id = $id;
  16. $this->account_id = $account_id;
  17. $this->type = $type;
  18. $this->url = $url;
  19. }
  20. /**
  21. * Creates the table for the object type in the database.
  22. */
  23. public static function CreateTable(): void {
  24. throw new SecurityFaultException("Attempt to create table on link object.");
  25. }
  26. /**
  27. * Drops the table for the object type from the database.
  28. */
  29. public static function DropTable(): void {
  30. throw new SecurityFaultException("Attempt to drop table on link object.");
  31. }
  32. /**
  33. * Saves the object to the database.
  34. */
  35. public function Save() {
  36. Hajeebtok::$Database->Query("INSERT INTO links (account_id, type, url) VALUES (:account_id, :type, :url)", [
  37. "account_id" => $this->account_id,
  38. "type" => $this->type->value,
  39. "url" => $this->url
  40. ]);
  41. $this->id = Hajeebtok::$Database->LastInsertId();
  42. Logger::Debug("Saved link id ($this->id).");
  43. }
  44. /**
  45. * Deletes the object from the database.
  46. */
  47. public function Delete() {
  48. Hajeebtok::$Database->Query("DELETE FROM link WHERE id = :id", ["id" => $this->id]);
  49. }
  50. /**
  51. * Loads the object from the database.
  52. */
  53. public function Load() {
  54. if($this->id === null) throw new LinkNotFoundException(0, 404);
  55. $data = Hajeebtok::$Database->Row("SELECT * FROM link WHERE id = :id", ["id" => $this->id]);
  56. if(empty($data)) throw new LinkNotFoundException($this->id, 404);
  57. $this->account_id = $data["account_id"];
  58. $this->type = LinkEnum::tryFrom($data["type"]);
  59. $this->url = $data["url"];
  60. }
  61. public function LoadMany(): array {
  62. if(empty($this->account_id)) throw new LinkNotFoundException(0, 404);
  63. $data = Hajeebtok::$Database->Query("SELECT * FROM links WHERE account_id = :account_id", ["account_id" => $this->account_id]);
  64. if(empty($data)) throw new LinkNotFoundException(0, 404);
  65. return $data;
  66. }
  67. }