118 lines
3.3 KiB
PHP
118 lines
3.3 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\CrudAction;
|
|
use App\Enums\CrudType;
|
|
use App\Enums\Role;
|
|
use App\Traits\IsCrudModel;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Site extends Model
|
|
{
|
|
use HasFactory;
|
|
use IsCrudModel;
|
|
use SoftDeletes;
|
|
|
|
protected $crudLabelColumn = 'name';
|
|
|
|
protected $crudValueColumn = 'id';
|
|
|
|
protected $fillable = ['name'];
|
|
|
|
public function __construct($attributes = [])
|
|
{
|
|
self::$editableProperties = [
|
|
'name' => [
|
|
'label' => trans('Nom'),
|
|
'type' => CrudType::string(),
|
|
'validate' => [
|
|
'string',
|
|
'max:255'
|
|
],
|
|
'required' => true,
|
|
'nullable' => false,
|
|
'actions' => [
|
|
CrudAction::viewAny(),
|
|
CrudAction::view(),
|
|
CrudAction::create(),
|
|
CrudAction::update(),
|
|
]
|
|
],
|
|
'users' => [
|
|
'label' => trans('Utilisateurs'),
|
|
'type' => CrudType::belongsToMany(),
|
|
'belongsToMany' => User::class,
|
|
'belongsToManyLabel' => 'name',
|
|
'nullable' => true,
|
|
'readonly' => function () {
|
|
/** @var \App\Models\User */
|
|
$user = auth()->user();
|
|
return $user->isAdmin();
|
|
},
|
|
'actions' => [
|
|
CrudAction::viewAny(),
|
|
CrudAction::view(),
|
|
CrudAction::create(),
|
|
CrudAction::update(),
|
|
]
|
|
]
|
|
];
|
|
parent::__construct($attributes);
|
|
}
|
|
|
|
protected static function booted()
|
|
{
|
|
static::created(function (Site $site) {
|
|
$path = Site::ticketAssetsFullPath($site->slug_name);
|
|
if (!File::exists($path)) {
|
|
File::makeDirectory($path, 0755, true);
|
|
}
|
|
});
|
|
static::updating(function (Site $site) {
|
|
$oldName = Site::where('id', $site->id)->first()->name;
|
|
$oldPath = Site::ticketAssetsFullPath($oldName);
|
|
$newPath = Site::ticketAssetsFullPath($site->slug_name);
|
|
if (File::exists($oldPath)) {
|
|
File::move($oldPath, $newPath);
|
|
} else {
|
|
File::makeDirectory($newPath, 0755, true);
|
|
}
|
|
});
|
|
static::deleted(function (Site $site) {
|
|
$path = Site::ticketAssetsFullPath($site->slug_name);
|
|
if (File::exists($path)) {
|
|
File::deleteDirectory($path);
|
|
}
|
|
});
|
|
}
|
|
|
|
public function users()
|
|
{
|
|
return $this->belongsToMany(User::class);
|
|
}
|
|
|
|
public function tickets()
|
|
{
|
|
return $this->hasMany(Ticket::class, 'site_id');
|
|
}
|
|
|
|
public function getSlugNameAttribute()
|
|
{
|
|
return Str::slug($this->name);
|
|
}
|
|
|
|
public static function ticketAssetsFullPath(string $str)
|
|
{
|
|
return public_path(self::ticketAssetsPath($str));
|
|
}
|
|
|
|
public static function ticketAssetsPath(string $str)
|
|
{
|
|
return sprintf('fichiers/%s', $str);
|
|
}
|
|
}
|