Link.php 2.4 KB

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