Attachment.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace app\common\model;
  3. use Throwable;
  4. use think\Model;
  5. use ba\Filesystem;
  6. use think\facade\Event;
  7. use app\admin\model\Admin;
  8. use think\model\relation\BelongsTo;
  9. /**
  10. * Attachment模型
  11. */
  12. class Attachment extends Model
  13. {
  14. protected $autoWriteTimestamp = true;
  15. protected $updateTime = false;
  16. protected $append = [
  17. 'suffix',
  18. 'full_url'
  19. ];
  20. public function getSuffixAttr($value, $row): string
  21. {
  22. if ($row['name']) {
  23. $suffix = strtolower(pathinfo($row['name'], PATHINFO_EXTENSION));
  24. return $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  25. }
  26. return 'file';
  27. }
  28. public function getFullUrlAttr($value, $row): string
  29. {
  30. return full_url($row['url']);
  31. }
  32. /**
  33. * 新增前
  34. * @throws Throwable
  35. */
  36. protected static function onBeforeInsert($model): bool
  37. {
  38. $repeat = $model->where([
  39. ['sha1', '=', $model->sha1],
  40. ['topic', '=', $model->topic],
  41. ['storage', '=', $model->storage],
  42. ])->find();
  43. if ($repeat) {
  44. $storageFile = Filesystem::fsFit(public_path() . ltrim($repeat['url'], '/'));
  45. if ($model->storage == 'local' && !file_exists($storageFile)) {
  46. $repeat->delete();
  47. return true;
  48. } else {
  49. $repeat->quote++;
  50. $repeat->last_upload_time = time();
  51. $repeat->save();
  52. return false;
  53. }
  54. }
  55. return true;
  56. }
  57. /**
  58. * 新增后
  59. */
  60. protected static function onAfterInsert($model): void
  61. {
  62. Event::trigger('AttachmentInsert', $model);
  63. if (!$model->last_upload_time) {
  64. $model->quote = 1;
  65. $model->last_upload_time = time();
  66. $model->save();
  67. }
  68. }
  69. /**
  70. * 删除后
  71. */
  72. protected static function onAfterDelete($model): void
  73. {
  74. Event::trigger('AttachmentDel', $model);
  75. $filePath = Filesystem::fsFit(public_path() . ltrim($model->url, '/'));
  76. if (file_exists($filePath)) {
  77. unlink($filePath);
  78. Filesystem::delEmptyDir(dirname($filePath));
  79. }
  80. }
  81. public function admin(): BelongsTo
  82. {
  83. return $this->belongsTo(Admin::class);
  84. }
  85. public function user(): BelongsTo
  86. {
  87. return $this->belongsTo(User::class);
  88. }
  89. }