62 lines
2 KiB
PHP
62 lines
2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Traits\HasCreatorAndUpdater;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Illuminate\Support\Str;
|
|
use Kalnoy\Nestedset\NodeTrait;
|
|
|
|
class File extends Model
|
|
{
|
|
use HasFactory, HasCreatorAndUpdater, NodeTrait, SoftDeletes; // adds node and recycle bin functionality to files
|
|
|
|
// returns the user this file or folder belongs to
|
|
public function user(): BelongsTo {
|
|
return $this->belongsTo(User::class, 'created_by');
|
|
}
|
|
|
|
// returns the parent file or folder for this file or folder
|
|
public function parent(): BelongsTo {
|
|
return $this->belongsTo(File::class, 'parent_id');
|
|
}
|
|
|
|
// returns whether or not the current folder is a root-level folder
|
|
public function isRoot() {
|
|
// is there a parent_id for this folder?
|
|
return $this->parent_id == null;
|
|
}
|
|
|
|
// returns simple boolean whether or not the passed userID is the creator of the file
|
|
public function isOwner($userID): bool
|
|
{
|
|
return $this->created_by = $userID;
|
|
}
|
|
|
|
// additional bootstrapping on top of default Model model
|
|
protected static function boot()
|
|
{
|
|
// start with parent Model
|
|
parent::boot();
|
|
|
|
// define new bootstrapping
|
|
static::creating(function ($model) {
|
|
// check for parent - if one exists, exit function
|
|
if (!$model->parent) return;
|
|
|
|
// if file or folder is NOT a root-level folder
|
|
if (!$model->parent->isRoot()) {
|
|
// path is a node off the parent path
|
|
$model->path = $model->parent->path . '/';
|
|
}
|
|
// otherwise free-standing
|
|
else $model->path = '';
|
|
|
|
// append current file or folder name to path name
|
|
$model->path = $model->path . Str::slug($model->name);
|
|
});
|
|
}
|
|
}
|