Product.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace App;
  3. use App\Traits\DateTimeTrait;
  4. use App\Traits\SoftDeleteTrait;
  5. use Exception;
  6. /**
  7. * Class Product
  8. * @property int $id
  9. * @property int $supplier_id
  10. * @property string $name
  11. * @property string $sku
  12. * @property int $type
  13. * @property string $price
  14. * @property string $url
  15. */
  16. class Product extends Model implements \JsonSerializable {
  17. protected static $table = "product";
  18. protected static $idField = "id";
  19. protected static $fillableFields = [
  20. "supplier_id",
  21. "name", "type", "sku", "price", "url",
  22. "dts_created", "dts_updated", "dts_deleted"
  23. ];
  24. use DateTimeTrait;
  25. use SoftDeleteTrait;
  26. public const TYPE_MACHINE = 1;
  27. public const TYPE_SPARE_PART = 2;
  28. public const TYPE_CONSUMABLE = 3;
  29. // Static methods
  30. public static function getTypeOptions(): array {
  31. return [
  32. self::TYPE_MACHINE => __("Machine"),
  33. self::TYPE_SPARE_PART => __("Spare Part"),
  34. self::TYPE_CONSUMABLE => __("Consumable"),
  35. ];
  36. }
  37. // Object methods
  38. /**
  39. * @return Supplier
  40. * @throws Exception
  41. */
  42. public function getSupplier(): Supplier {
  43. return Supplier::get($this->supplier_id);
  44. }
  45. public function getSlug(): string {
  46. return Util::slug("$this->name $this->id");
  47. }
  48. public function getUrl(): string {
  49. return sprintf("/products/%s", $this->getSlug());
  50. }
  51. public function getWebsiteUrl(): ?string {
  52. return $this->url;
  53. }
  54. public function getDisplayType(): string {
  55. return self::getTypeOptions()[$this->type] ?? "";
  56. }
  57. public function getDisplayPrice(): string {
  58. return number_format($this->price, 2);
  59. }
  60. public function jsonSerialize(): array {
  61. return [
  62. "id" => (int) $this->id,
  63. "supplierId" => (int) $this->supplier_id,
  64. "name" => $this->name,
  65. "sku" => $this->sku,
  66. "type" => (int) $this->type,
  67. "price" => $this->price,
  68. ];
  69. }
  70. public function getBrochurePath(): string {
  71. return $_ENV["DIR_ROOT"] . "/files/product/" . $this->id . ".pdf";
  72. }
  73. public function hasBrochure(): bool {
  74. return file_exists($this->getBrochurePath());
  75. }
  76. public function deleteBrochure(): bool {
  77. return !$this->hasBrochure() || unlink($this->getBrochurePath());
  78. }
  79. }