has('type') && !$entity->get('type')) { $entity->set('type', 'regular'); } if ($entity->isApi()) { if ($entity->isAttributeChanged('userName')) { $entity->set('lastName', $entity->get('userName')); } if ($entity->has('authMethod') && $entity->get('authMethod') !== 'Hmac') { $entity->clear('secretKey'); } } else { if ($entity->isAttributeChanged('type')) { $entity->set('authMethod', null); } } parent::beforeSave($entity, $options); if ($entity->has('type') && !$entity->isPortal()) { $entity->set('portalRolesIds', []); $entity->set('portalRolesNames', (object)[]); $entity->set('portalsIds', []); $entity->set('portalsNames', (object)[]); } if ($entity->has('type') && $entity->isPortal()) { $entity->set('rolesIds', []); $entity->set('rolesNames', (object)[]); $entity->set('teamsIds', []); $entity->set('teamsNames', (object)[]); $entity->set('defaultTeamId', null); $entity->set('defaultTeamName', null); } if ($entity->isNew()) { $userName = $entity->get('userName'); if (empty($userName)) { throw new Error("Username can't be empty."); } $this->getEntityManager()->getLocker()->lockExclusive($this->entityType); $user = $this ->select(['id']) ->where([ 'userName' => $userName, ]) ->findOne(); if ($user) { $this->getEntityManager()->getLocker()->rollback(); throw new Conflict(json_encode(['reason' => 'userNameExists'])); } } else { if ($entity->isAttributeChanged('userName')) { $userName = $entity->get('userName'); if (empty($userName)) { throw new Error("Username can't be empty."); } $this->getEntityManager()->getLocker()->lockExclusive($this->entityType); $user = $this ->select(['id']) ->where([ 'userName' => $userName, 'id!=' => $entity->id, ]) ->findOne(); if ($user) { $this->getEntityManager()->getLocker()->rollback(); throw new Conflict(json_encode(['reason' => 'userNameExists'])); } } } } protected function afterSave(Entity $entity, array $options = []) { if ($this->getEntityManager()->getLocker()->isLocked()) { $this->getEntityManager()->getLocker()->commit(); } parent::afterSave($entity, $options); } protected function afterRemove(Entity $entity, array $options = []) { parent::afterRemove($entity, $options); $userData = $this->getEntityManager()->getRepository('UserData')->getByUserId($entity->id); if ($userData) { $this->getEntityManager()->removeEntity($userData); } } public function checkBelongsToAnyOfTeams(string $userId, array $teamIds): bool { if (empty($teamIds)) { return false; } return (bool) $this->getEntityManager() ->getRepository('TeamUser') ->where([ 'deleted' => false, 'userId' => $userId, 'teamId' => $teamIds, ]) ->findOne(); } }