setContract($contractId); $this->setUser(null); $this->initialized = true; return $this; } public function initForModify(string|Contract $contractId, string|User $userId) { $this->setContract($contractId); $this->setUser($userId); $this->initialized = true; return $this; } public function getTimestamp(): Carbon { if (!$this->initialized) { throw new LogicException("初期化不正"); } return $this->user->updated_at < $this->contract->updated_at ? $this->contract->updated_at : $this->user->updated_at; } public function fill(array $attr) { if (!$this->initialized) { throw new LogicException("初期化不正"); } $this->user->fill($attr); return $this; } public function create(): array { $messages = $this->checkParam(); if (count($messages) !== 0) { return $messages; } $this->user->save(); return []; } public function update(): array { $messages = $this->checkParam(); if (count($messages) !== 0) { return $messages; } $this->user->save(); return []; } protected function setContract(string|Contract|null $contractId) { if ($contractId instanceof Contract) { $this->contract = (new Contract())->copy($contractId); $this->initialized = true; return; } else if ($contractId === null) { $this->initialized = true; return; } $this->contract = Contract::findOrFail($contractId); $this->initialized = true; return; } protected function setUser(string|User|null $userId) { if ($userId instanceof User) { $this->user = (new User())->copy($userId); return; } else if (is_string($userId)) { $this->user = User::findOrFail($userId); return; } $this->user = new User(); if ($this->contract) { $this->user->setContract($this->contract); } $this->user->role = $this->role(); } protected function checkParam() { $validator = Validator::make($this->user->toArray(), []); if ($validator->failed()) { throw new LogicException("バリデートエラー"); } $messages = []; $this->checkContract($messages); $this->checkEmailUnique($messages); $this->passwordEncrypto($messages); $this->user->role = $this->role(); return $messages; } protected function checkContract(array &$messages) { if ($this->user->role !== UserRole::SUPER_ADMIN && $this->user->contract_id === null) { throw new LogicException("契約nullエラー"); } } protected function passwordEncrypto(array &$messages) { if ($this->user->isDirty(User::COL_NAME_PASSWORD)) { $this->user->password = Hash::make($this->user->password); } } protected function checkEmailUnique(array &$messages) { if ($this->user->isDirty(User::COL_NAME_EMAIL)) { $exists = User::whereEmail($this->user->email) ->where(User::COL_NAME_ID, '<>', $this->user->id) ->exists(); if ($exists) { $messages[User::COL_NAME_EMAIL] = trans('validation.unique'); } } } abstract protected function role(): UserRole; }