ModLogService.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace App\Services;
  3. use App\ModLog;
  4. use App\User;
  5. class ModLogService {
  6. protected $log;
  7. public function __construct()
  8. {
  9. $this->log = new \StdClass;
  10. }
  11. public static function boot()
  12. {
  13. return new self;
  14. }
  15. public function user(User $user)
  16. {
  17. $this->log->user = $user;
  18. return $this;
  19. }
  20. public function objectUid($val = null)
  21. {
  22. $this->log->object_uid = $val;
  23. return $this;
  24. }
  25. public function objectId($val = null)
  26. {
  27. $this->log->object_id = $val;
  28. return $this;
  29. }
  30. public function objectType($val = null)
  31. {
  32. $this->log->object_type = $val;
  33. return $this;
  34. }
  35. public function action($val = null)
  36. {
  37. $this->log->action = $val;
  38. return $this;
  39. }
  40. public function message($val = null)
  41. {
  42. $this->log->message = $val;
  43. return $this;
  44. }
  45. public function metadata(array $val = null)
  46. {
  47. $this->log->metadata = json_encode($val);
  48. return $this;
  49. }
  50. public function accessLevel($val = null)
  51. {
  52. if(!in_array($val, ['admin', 'mod'])) {
  53. return $this;
  54. }
  55. $this->log->access_level = $val;
  56. return $this;
  57. }
  58. public function save($res = false)
  59. {
  60. $log = $this->log;
  61. if(!isset($log->user)) {
  62. throw new \Exception('Invalid ModLog attribute.');
  63. }
  64. $ml = new ModLog();
  65. $ml->user_id = $log->user->id;
  66. $ml->user_username = $log->user->username;
  67. $ml->object_uid = $log->object_uid ?? null;
  68. $ml->object_id = $log->object_id ?? null;
  69. $ml->object_type = $log->object_type ?? null;
  70. $ml->action = $log->action ?? null;
  71. $ml->message = $log->message ?? null;
  72. $ml->metadata = $log->metadata ?? null;
  73. $ml->access_level = $log->access_level ?? 'admin';
  74. $ml->save();
  75. if($res == true) {
  76. return $ml;
  77. } else {
  78. return;
  79. }
  80. }
  81. }