'datetime', ]; /** * Maker * * @param array $attributes */ public function __construct(array $attributes = []) { self::$editableProperties = [ 'label' => [ 'label' => trans('Nom'), 'type' => CrudType::string(), 'validate' => [ 'string', 'min:4', 'max:255' ], 'required' => true, 'nullable' => false, 'actions' => [ CrudAction::viewAny(), CrudAction::view(), CrudAction::create(), CrudAction::update(), ] ], 'marker' => [ 'label' => trans('Marqueur'), 'type' => CrudType::datetime(), 'validate' => [ 'string', 'max:255' ], 'required' => true, 'nullable' => false, 'actions' => [ CrudAction::viewAny(), CrudAction::view(), CrudAction::create(), CrudAction::update(), ] ] ]; parent::__construct($attributes); } /** * Perform any actions required after the model boots. * * @return void */ protected static function booted() { static::creating(function (self $marker) { if ($marker->markersThisSameDay()) { throw ValidationException::withMessages(['Un marqueur existe déjà pour ce projet ce même jour']); } }); static::updating(function (self $marker) { if ($marker->markersThisSameDay()) { throw ValidationException::withMessages(['Un marqueur existe déjà pour ce projet ce même jour']); } }); // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass static::created(function (self $marker) { Cache::delete('markerLabels'); }); // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass static::updated(function (self $marker) { Cache::delete('markerLabels'); }); // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass static::deleted(function (self $marker) { Cache::delete('markerLabels'); }); } // * METHODS /** * Get all available labels from cache. * If cache was reset, it will fetch them from DB. * * @return \Illuminate\Database\Eloquent\Collection */ public static function getCachedLabels() { if (!Cache::has('markerLabels')) { self::setCachedLabels(); } return Cache::get('markerLabels'); } /** * Put all available labels into cache. * * @return void */ protected static function setCachedLabels(): void { /** @var \Illuminate\Database\Eloquent\Builder $markerLabels */ $markerLabels = self::select(DB::raw('LOWER(label) AS label')); $markerLabels->groupBy('label'); Cache::put('markerLabels', $markerLabels->get()->pluck('label')); } /** * Count markers this same day * * @return integer */ public function markersThisSameDay(): int { /** @var \Illuminate\Database\Eloquent\Builder */ $query = self::where('marker', '>=', $this->marker->setHour(0, 0)->format('Y-m-d')) ->where('marker', '<', $this->marker->setHour(0, 0)->addDay()->format('Y-m-d')) ->whereHas('project', function ($q) { $q->whereId($this->project->id); }); if ($this->id) { $query->where('id', '!=', $this->id); } return $query->count(); } // * RELATIONSHIPS. /** * BelongsTo Project * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function project() { return $this->belongsTo(Project::class); } }