Attachment.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace app\common\model;
  3. use Throwable;
  4. use think\Model;
  5. use think\facade\Event;
  6. use app\admin\model\Admin;
  7. use app\common\library\Upload;
  8. use think\model\relation\BelongsTo;
  9. /**
  10. * Attachment模型
  11. * @property string url 文件物理路径
  12. * @property int quote 上传(引用)次数
  13. * @property int last_upload_time 最后上传时间
  14. */
  15. class Attachment extends Model
  16. {
  17. protected $autoWriteTimestamp = true;
  18. protected $updateTime = false;
  19. protected $append = [
  20. 'suffix',
  21. 'full_url'
  22. ];
  23. /**
  24. * 上传类实例,可以通过它调用上传文件驱动,且驱动类具有静态缓存
  25. */
  26. protected static Upload $upload;
  27. protected static function init(): void
  28. {
  29. self::$upload = new Upload();
  30. }
  31. public function getSuffixAttr($value, $row): string
  32. {
  33. if ($row['name']) {
  34. $suffix = strtolower(pathinfo($row['name'], PATHINFO_EXTENSION));
  35. return $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  36. }
  37. return 'file';
  38. }
  39. public function getFullUrlAttr($value, $row): string
  40. {
  41. $driver = self::$upload->getDriver($row['storage'], false);
  42. return $driver ? $driver->url($row['url']) : full_url($row['url']);
  43. }
  44. /**
  45. * 新增前
  46. * @throws Throwable
  47. */
  48. protected static function onBeforeInsert($model): bool
  49. {
  50. $repeat = $model->where([
  51. ['sha1', '=', $model->sha1],
  52. ['topic', '=', $model->topic],
  53. ['storage', '=', $model->storage],
  54. ])->find();
  55. if ($repeat) {
  56. $driver = self::$upload->getDriver($repeat->storage, false);
  57. if ($driver && !$driver->exists($repeat->url)) {
  58. $repeat->delete();
  59. return true;
  60. } else {
  61. $repeat->quote++;
  62. $repeat->last_upload_time = time();
  63. $repeat->save();
  64. return false;
  65. }
  66. }
  67. return true;
  68. }
  69. /**
  70. * 新增后
  71. */
  72. protected static function onAfterInsert($model): void
  73. {
  74. Event::trigger('AttachmentInsert', $model);
  75. if (!$model->last_upload_time) {
  76. $model->quote = 1;
  77. $model->last_upload_time = time();
  78. $model->save();
  79. }
  80. }
  81. /**
  82. * 删除后
  83. */
  84. protected static function onAfterDelete($model): void
  85. {
  86. Event::trigger('AttachmentDel', $model);
  87. $driver = self::$upload->getDriver($model->storage, false);
  88. if ($driver && $driver->exists($model->url)) {
  89. $driver->delete($model->url);
  90. }
  91. }
  92. public function admin(): BelongsTo
  93. {
  94. return $this->belongsTo(Admin::class);
  95. }
  96. public function user(): BelongsTo
  97. {
  98. return $this->belongsTo(User::class);
  99. }
  100. }