Delete a user

@todo (Pablo - 2019-01-22) - Use the DefaultController edit() method

@throws \Nails\Common\Exception\FactoryException
@throws \Nails\Common\Exception\ModelException
976638
public function delete(): void
    {
        if (!userHasPermission('admin:auth:accounts:delete')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        //  Get the user's details
        $oUri       = Factory::service('Uri');
        $oInput     = Factory::service('Input');
        $oSession   = Factory::service('Session', 'nails/module-auth');
        $oUserModel = Factory::model('User', 'nails/module-auth');
        $iUserId    = $oUri->segment(5);
        $oUser      = $oUserModel->getById($iUserId);

        // --------------------------------------------------------------------------

        //  Non-superusers editing superusers is not cool
        if (!isSuperuser() && userHasPermission('superuser', $oUser)) {
            $oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
            $this->returnToIndex();
        }

        // --------------------------------------------------------------------------

        //  Delete user
        $oUser = $oUserModel->getById($iUserId);

        if (!$oUser) {
            show404();
        } elseif ($oUser->id == activeUser('id')) {
            $oSession->setFlashData('error', lang('accounts_delete_error_selfie'));
            $this->returnToIndex();
        }

        // --------------------------------------------------------------------------

        //  Define messages
        if ($oUserModel->destroy($iUserId)) {

            $sStatus  = 'success';
            $sMessage = lang('accounts_delete_success', title_case($oUser->first_name . ' ' . $oUser->last_name));

            //  Update admin changelog
            $this->oChangeLogModel->add(
                'deleted',
                'a',
                'user',
                $iUserId,
                '#' . number_format($iUserId) . ' ' . $oUser->first_name . ' ' . $oUser->last_name
            );

        } else {
            $sStatus  = 'error';
            $sMessage = lang('accounts_delete_error', title_case($oUser->first_name . ' ' . $oUser->last_name));
        }

        $oSession->setFlashData($sStatus, $sMessage);

        // --------------------------------------------------------------------------

        $this->returnToIndex();
    }
302579
public function delete()
	{
        if (!$this->isXmlHttpRequest()) {
            throw new common_exception_BadRequest('wrong request mode');
        } else {
			$deleted = false;
			if($this->getRequestParameter('uri')){

				$role = $this->getCurrentInstance();

				if(!in_array($role->getUri(), $this->forbidden)){
						//check if no user is using this role:
						$userClass = $this->getClass(GenerisRdf::CLASS_GENERIS_USER);
						$options = array('recursive' => true, 'like' => false);
						$filters = array(GenerisRdf::PROPERTY_USER_ROLES => $role->getUri());
						$users = $userClass->searchInstances($filters, $options);
						if(empty($users)){
							//delete role here:
							$deleted = $this->getClassService()->removeRole($role);
						}else{
							//set message error
							throw new UserErrorException(__('This role is still given to one or more users. Please remove the role to these users first.'));
						}
				}else{
					throw new UserErrorException($role->getLabel() . ' could not be deleted');
				}
			}

			$this->returnJson(array('deleted' => $deleted));
		}
	}
1186126
public function delete()
    {
        if ($this->isNewRecord()) {
            throw new DeleteModelException("New models can't be deleted.");
        }

        $this->beforeDelete();
        $this->raiseEvent("BeforeDelete");

        $this->Deleted = true;
        $this->save();

        $this->afterDelete();
        $this->raiseEvent("AfterDelete");
    }
903625
public function actionDelete()
    {
        if (!$this->module->enableAccountDelete) {
            throw new NotFoundHttpException(\Yii::t('user', 'Not found'));
        }

        /** @var User $user */
        $user  = \Yii::$app->user->identity;
        $event = $this->getUserEvent($user);

        \Yii::$app->user->logout();

        $this->trigger(self::EVENT_BEFORE_DELETE, $event);
        $user->delete();
        $this->trigger(self::EVENT_AFTER_DELETE, $event);

        \Yii::$app->session->setFlash('info', \Yii::t('user', 'Your account has been completely deleted'));

        return $this->goHome();
    }
1174380
public function actionDelete()
    {
        if (isset($_GET['name'])) {
            $name = $_GET['name'];

            /* @var $am CAuthManager|AuthBehavior */
            $am = Yii::app()->getAuthManager();

            $item = $am->getAuthItem($name);
            if ($item instanceof CAuthItem) {
                $am->removeAuthItem($name);
                if ($am instanceof CPhpAuthManager) {
                    $am->save();
                }

                if (!isset($_POST['ajax'])) {
                    $this->redirect(array('index'));
                }
            } else {
                throw new CHttpException(404, Yii::t('AuthModule.main', 'Item does not exist.'));
            }
        } else {
            throw new CHttpException(400, Yii::t('AuthModule.main', 'Invalid request.'));
        }
    }
84959
public function down()
    {
        if (is_null($this->userClassName)) {
            throw new Exception('Admin user model not defined');
        }
        DB::transaction(function () {
            foreach ($this->users as $user) {
                $userItem = DB::table($this->userTable)->where('email', $user['email'])->first();
                if (!is_null($userItem)) {
                    AdminUser::find($userItem->id)->media()->delete();
                    DB::table($this->userTable)->where('id', $userItem->id)->delete();
                    DB::table('model_has_permissions')->where([
                        'model_id' => $userItem->id,
                        'model_type' => $this->userClassName
                    ])->delete();
                    DB::table('model_has_roles')->where([
                        'model_id' => $userItem->id,
                        'model_type' => $this->userClassName
                    ])->delete();
                }
            }

            foreach ($this->roles as $role) {
                $roleItem = DB::table('roles')->where([
                    'name' => $role['name'],
                    'guard_name' => $role['guard_name']
                ])->first();
                if (!is_null($roleItem)) {
                    DB::table('roles')->where('id', $roleItem->id)->delete();
                    DB::table('model_has_roles')->where('role_id', $roleItem->id)->delete();
                }
            }

            foreach ($this->permissions as $permission) {
                $permissionItem = DB::table('permissions')->where([
                    'name' => $permission['name'],
                    'guard_name' => $permission['guard_name']
                ])->first();
                if (!is_null($permissionItem)) {
                    DB::table('permissions')->where('id', $permissionItem->id)->delete();
                    DB::table('model_has_permissions')->where('permission_id', $permissionItem->id)->delete();
                }
            }
        });
        app()['cache']->forget(config('permission.cache.key'));
    }
542173
public function deleteUser($username) {
    $users = \Drupal::entityQuery('user')
      ->condition("name", $username)
      ->execute();

    /** @var \Drupal\user\Entity\User $users */
    $users = User::loadMultiple($users);
    foreach ($users as $user) {
      $user->delete();
    }
  }
411249
public function delete()
    {
        if ($this->request->isPost()) {
            $recordId = StaticFilter::filter(
                'text',
                $this->request->getPost('id')
            );

            $record = call_user_func_array(
                [$this->getModelName(), 'get'],
                [$recordId]
            );

            if (is_null($record)) {
                $this->addWarningMessage(
                    "The {$this->get('modelSingular')} with the provided key ".
                    "does not exists."
                );
            } else {
                if ($record->delete()) {
                    $this->addSuccessMessage(
                        "The {$this->get('modelSingular')} was successfully " .
                        "deleted."
                    );
                }
            }
        }
        return $this->redirect($this->_basePath .'/'.$this->get('modelPlural'));
    }
11471
public function delete()
    {
        if (isset($this->onDelete)) {
            return call_user_func($this->onDelete, $this);
        }

        $this->forceDelete();
    }
488308
public function actionDelete ()
		{
			if (Yii::$app->request->isAjax)
			{
				$id = Yii::$app->request->post('id');
				$menu = Menu::findOne($id);
				if ($menu !== null)
				{
					if (!$menu->deleteWithChildren())
						echo Json::encode(current($menu->firstErrors));
					else
						echo 0;
				}
			}
			Yii::$app->end();
		}
251436
public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel()->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_POST['ajax']))
				$this->redirect(array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
1341414
public function actionMassDelete()
    {
        if (($ids = Yii::$app->request->post('ids')) !== null) {
            $models = $this->findUser($ids);
            foreach ($models as $model) {
                $model->delete($model);
            }
            return $this->redirect(['index']);
        } else {
            throw new HttpException(400);
        }
    }
1271736
public function delete()
	{
		if ($this->user_id <= 0)
		{
			return false;
		}

		$db = \App::get('db');

		if (empty($db))
		{
			return false;
		}

		if (!isset($this->user_id))
		{
			$db->setQuery("SELECT user_id FROM `#__users_password` WHERE user_id" . $db->quote($this->user_id) . ";");

			$this->__set('user_id', $db->loadResult());
		}

		if (empty($this->user_id))
		{
			return false;
		}

		$db->setQuery("DELETE FROM `#__users_password` WHERE user_id= " . $db->quote($this->user_id) . ";");

		$affected = 0;

		if ($db->query())
		{
			$affected = $db->getAffectedRows();
		}

		if ($affected > 0)
		{
			\Event::trigger('user.onAfterDeletePassword', array($this));
		}

		return true;
	}
212113
public function delete($userid)
	{
		$event = new Event('onPlatformUserDelete');
		$event->addArgument('userid', $userid);
		$event->addArgument('activePlugin', $this->activePlugin);

		Factory::getDispatcher()->triggerEvent($event);

		$debug = $event->getArgument('debug', null);
		if ($debug) {
			$this->debug[] = $debug;
		}

		$error = $event->getArgument('error', null);
		if ($error) {
			$this->error[] = $error;
		}
	}
660319
public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);

        $user = $this->Users->get($id);

        //You cannot delete the admin founder
        if ($user->id === 1) {
            $this->Flash->error(__d('me_cms', 'You cannot delete the admin founder'));
        //Only the admin founder can delete others admin users
        } elseif ($user->group_id === 1 && !$this->Auth->isFounder()) {
            $this->Flash->alert(I18N_ONLY_ADMIN_FOUNDER);
        } elseif ($user->post_count) {
            $this->Flash->alert(I18N_BEFORE_DELETE);
        } else {
            $this->Users->deleteOrFail($user);

            $this->Flash->success(I18N_OPERATION_OK);
        }

        return $this->redirect(['action' => 'index']);
    }
1004288
public function edit(): void
    {
        $oUri   = Factory::service('Uri');
        $oInput = Factory::service('Input');

        if ($oUri->segment(5) != activeUser('id') && !userHasPermission('admin:auth:accounts:editOthers')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        /**
         * Get the user's data; loaded early because it's required for the user_meta_cols
         * (we need to know the group of the user so we can pull up the correct cols/rules)
         */

        $oSession   = Factory::service('Session', 'nails/module-auth');
        $oUserModel = Factory::model('User', 'nails/module-auth');
        $oUser      = $oUserModel->getById($oUri->segment(5));

        if (!$oUser) {
            $oSession->setFlashData('error', lang('accounts_edit_error_unknown_id'));
            $this->returnToIndex();
        }

        //  Non-superusers editing superusers is not cool
        if (!$oUserModel->isSuperuser() && userHasPermission('superuser', $oUser)) {
            $oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
            $sReturnTo = $oInput->get('return_to') ? $oInput->get('return_to') : 'admin/dashboard';
            redirect($sReturnTo);
        }

        //  Is this user editing someone other than themselves? If so, do they have permission?
        if (activeUser('id') != $oUser->id && !userHasPermission('admin:auth:accounts:editOthers')) {
            $oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
            $sReturnTo = $oInput->get('return_to') ? $oInput->get('return_to') : 'admin/dashboard';
            redirect($sReturnTo);
        }

        // --------------------------------------------------------------------------

        /**
         * Load the user_meta_cols; loaded here because it's needed for both the view
         * and the form validation
         */

        $oDb           = Factory::service('Database');
        $oConfig       = Factory::service('Config');
        $aUserMetaCols = $oConfig->item('user_meta_cols');
        $iGroupId      = (int) $oInput->post('group_id') ?: $oUser->group_id;

        if (isset($aUserMetaCols[$iGroupId])) {
            $this->data['user_meta_cols'] = $aUserMetaCols[$oUser->group_id];
        } else {
            $this->data['user_meta_cols'] = null;
        }

        //  Set fields to ignore by default
        $this->data['ignored_fields'] = [
            'id',
            'user_id',
        ];

        /**
         * If no cols were found, DESCRIBE the user_meta_app table - where possible you
         * should manually set columns, including datatypes
         */

        if (is_null($this->data['user_meta_cols'])) {

            $aResult                      = $oDb->query('DESCRIBE `' . NAILS_DB_PREFIX . 'user_meta_app`')->result();
            $this->data['user_meta_cols'] = [];

            foreach ($aResult as $col) {

                //  Always ignore some fields
                if (array_search($col->Field, $this->data['ignored_fields']) !== false) {
                    continue;
                }

                // --------------------------------------------------------------------------

                //  Attempt to detect datatype
                $sDataType = 'string';
                $type      = 'text';

                switch (strtolower($col->Type)) {

                    case 'text':
                        $type = 'textarea';
                        break;

                    case 'date':
                        $sDataType = 'date';
                        break;

                    case 'tinyint(1) unsigned':
                        $sDataType = 'bool';
                        break;
                }

                // --------------------------------------------------------------------------

                $this->data['user_meta_cols'][$col->Field] = [
                    'datatype' => $sDataType,
                    'type'     => $type,
                    'label'    => ucwords(str_replace('_', ' ', $col->Field)),
                ];
            }
        }

        // --------------------------------------------------------------------------

        //  Validate if we're saving, otherwise get the data and display the edit form
        if ($oInput->post()) {

            //  Load validation library
            $oFormValidation = Factory::service('FormValidation');

            // --------------------------------------------------------------------------

            //  Define user table rules
            $oFormValidation->set_rules('first_name', '', 'trim|required');
            $oFormValidation->set_rules('last_name', '', 'trim|required');
            $oFormValidation->set_rules('gender', '', 'required');
            $oFormValidation->set_rules('dob', '', 'valid_date');
            $oFormValidation->set_rules('timezone', '', 'required');
            $oFormValidation->set_rules('datetime_format_date', '', 'required');
            $oFormValidation->set_rules('datetime_format_time', '', 'required');

            // --------------------------------------------------------------------------

            //  Define user_meta table rules
            foreach ($this->data['user_meta_cols'] as $col => $value) {

                $sDataType = isset($value['datatype']) ? $value['datatype'] : 'string';
                $label     = isset($value['label']) ? $value['label'] : ucwords(str_replace('_', ' ', $col));

                //  Some data types require different handling
                switch ($sDataType) {

                    case 'date':
                        //  Dates must validate
                        if (isset($value['validation'])) {
                            $oFormValidation->set_rules($col, $label, $value['validation'] . '|valid_date[' . $col . ']');
                        } else {
                            $oFormValidation->set_rules($col, $label, 'valid_date[' . $col . ']');
                        }
                        break;

                    // --------------------------------------------------------------------------

                    case 'file':
                    case 'upload':
                    case 'string':
                    default:
                        if (isset($value['validation'])) {
                            $oFormValidation->set_rules($col, $label, $value['validation']);
                        }
                        break;
                }
            }

            // --------------------------------------------------------------------------

            //  Set messages
            $oFormValidation->set_message('required', lang('fv_required'));
            $oFormValidation->set_message('min_length', lang('fv_min_length'));
            $oFormValidation->set_message('alpha_dash_period', lang('fv_alpha_dash_period'));
            $oFormValidation->set_message('is_natural_no_zero', lang('fv_required'));
            $oFormValidation->set_message('valid_date', lang('fv_valid_date'));
            $oFormValidation->set_message('valid_datetime', lang('fv_valid_datetime'));

            // --------------------------------------------------------------------------

            //  Data is valid; ALL GOOD :]
            if ($oFormValidation->run()) {

                //  Define the data var
                $aData = [];

                // --------------------------------------------------------------------------

                //  If we have a profile image, attempt to upload it
                if (isset($_FILES['profile_img']) && $_FILES['profile_img']['error'] != UPLOAD_ERR_NO_FILE) {

                    $oCdn   = Factory::service('Cdn', 'nails/module-cdn');
                    $object = $oCdn->objectReplace($oUser->profile_img, 'profile-images', 'profile_img');

                    if ($object) {

                        $aData['profile_img'] = $object->id;

                    } else {

                        $this->data['upload_error'] = $oCdn->getErrors();
                        $this->data['error']        = lang('accounts_edit_error_profile_img');
                    }
                }

                // --------------------------------------------------------------------------

                if (!isset($this->data['upload_error'])) {

                    //  Set basic data

                    $aData['temp_pw']              = stringToBoolean($oInput->post('temp_pw', true));
                    $aData['reset_mfa_question']   = stringToBoolean($oInput->post('reset_mfa_question', true));
                    $aData['reset_mfa_device']     = stringToBoolean($oInput->post('reset_mfa_device', true));
                    $aData['first_name']           = $oInput->post('first_name', true);
                    $aData['last_name']            = $oInput->post('last_name', true);
                    $aData['username']             = $oInput->post('username', true);
                    $aData['gender']               = $oInput->post('gender', true);
                    $aData['dob']                  = $oInput->post('dob', true);
                    $aData['dob']                  = !empty($aData['dob']) ? $aData['dob'] : null;
                    $aData['timezone']             = $oInput->post('timezone', true);
                    $aData['datetime_format_date'] = $oInput->post('datetime_format_date', true);
                    $aData['datetime_format_time'] = $oInput->post('datetime_format_time', true);

                    if ($oInput->post('password', true)) {
                        $aData['password'] = $oInput->post('password', true);
                    }

                    //  Set meta data
                    foreach ($this->data['user_meta_cols'] as $col => $value) {

                        $mValue = $oInput->post($col, true);

                        //  Should the field be made null on empty?
                        if (!empty($value['nullOnEmpty']) && empty($mValue)) {
                            $mValue = null;
                        }

                        switch ($value['datatype']) {

                            case 'bool':
                            case 'boolean':
                                //  Convert all to boolean from string
                                $aData[$col] = stringToBoolean($mValue);
                                break;

                            case 'file':
                            case 'upload':
                                //  File uploads should be an integer, or if empty, null
                                $aData[$col] = (int) $mValue ?: null;
                                break;

                            default:
                                $aData[$col] = $mValue;
                                break;
                        }
                    }

                    // --------------------------------------------------------------------------

                    //  Update account
                    if ($oUserModel->update($oInput->post('id'), $aData)) {

                        $name                  = $oInput->post('first_name', true) . ' ' . $oInput->post('last_name', true);
                        $this->data['success'] = lang('accounts_edit_ok', [title_case($name)]);
                        // --------------------------------------------------------------------------

                        //  Set Admin changelogs
                        $name = '#' . number_format($oInput->post('id'));

                        if ($aData['first_name']) {
                            $name .= ' ' . $aData['first_name'];
                        }

                        if ($aData['last_name']) {
                            $name .= ' ' . $aData['last_name'];
                        }

                        foreach ($aData as $field => $value) {
                            if (isset($oUser->$field)) {
                                $this->oChangeLogModel->add(
                                    'updated',
                                    'a',
                                    'user',
                                    $oInput->post('id'),
                                    $name,
                                    'admin/auth/accounts/edit/' . $oInput->post('id'),
                                    $field,
                                    $oUser->$field,
                                    $value,
                                    false
                                );
                            }
                        }

                        // --------------------------------------------------------------------------

                        //  refresh the user object
                        $oUser = $oUserModel->getById($oInput->post('id'));

                        //  The account failed to update, feedback to user
                    } else {

                        $this->data['error'] = lang(
                            'accounts_edit_fail',
                            implode(', ', $oUserModel->getErrors())
                        );
                    }
                }

                //  Update failed for another reason
            } else {

                $this->data['error'] = lang('fv_there_were_errors');
            }
        }
        //  End POST() check

        // --------------------------------------------------------------------------

        //  Get the user's meta data
        if ($this->data['user_meta_cols']) {

            $oDb->select(implode(',', array_keys($this->data['user_meta_cols'])));
            $oDb->where('user_id', $oUser->id);
            $aUserMeta = (array) $oDb->get(NAILS_DB_PREFIX . 'user_meta_app')->row();

        } else {
            $aUserMeta = [];
        }

        // --------------------------------------------------------------------------

        //  Get the user's email addresses
        $this->data['user_emails'] = $oUserModel->getEmailsForUser($oUser->id);

        // --------------------------------------------------------------------------

        $this->data['user_edit'] = $oUser;
        $this->data['user_meta'] = $aUserMeta;

        //  Page Title
        $this->data['page']->title = lang(
            'accounts_edit_title',
            title_case($oUser->first_name . ' ' . $oUser->last_name)
        );

        //  Get the groups, timezones and languages
        $oUserGroupModel      = Factory::model('UserGroup', 'nails/module-auth');
        $this->data['groups'] = $oUserGroupModel->getAll();

        $oLanguageService        = Factory::service('Language');
        $this->data['languages'] = $oLanguageService->getAllEnabledFlat();

        $oDateTimeService               = Factory::service('DateTime');
        $this->data['timezones']        = $oDateTimeService->getAllTimezone();
        $this->data['date_formats']     = $oDateTimeService->getAllDateFormat();
        $this->data['time_formats']     = $oDateTimeService->getAllTimeFormat();
        $this->data['default_timezone'] = $oDateTimeService->getTimezoneDefault();

        //  Fetch any user uploads
        if (Components::exists('nails/module-cdn')) {
            $oCdn                       = Factory::service('Cdn', 'nails/module-cdn');
            $this->data['user_uploads'] = $oCdn->getObjectsForUser($oUser->id);
        }

        // --------------------------------------------------------------------------

        if (activeUser('id') == $oUser->id) {

            switch (strtolower(activeUser('gender'))) {

                case 'male':
                    $this->data['notice'] = lang('accounts_edit_editing_self_m');
                    break;

                case 'female':
                    $this->data['notice'] = lang('accounts_edit_editing_self_f');
                    break;

                default:
                    $this->data['notice'] = lang('accounts_edit_editing_self_u');
                    break;
            }
        }

        $oUserPasswordModel          = Factory::model('UserPassword', 'nails/module-auth');
        $this->data['passwordRules'] = $oUserPasswordModel->getRulesAsString($oUser->group_id);

        // --------------------------------------------------------------------------

        //  Load views
        Helper::loadView('edit');
    }
664078
public function delete()
    {
        /*
         * TODO: https://github.com/sulu-io/sulu/pull/1171
         * This method needs to be refactored since in the first
         * iteration the logic was just moved from the Controller
         * to this class due to better reusability.
         */
        $delete = function($id) {
            /** @var Contact $contact */
            $contact = $this->contactRepository->findByIdAndDelete($id);

            if (!$contact) {
                throw new EntityNotFoundException($this->contactRepository->getClassName(), $id);
            }

            $addresses = $contact->getAddresses();
            /** @var Address $address */
            foreach ($addresses as $address) {
                if (!$address->hasRelations()) {
                    $this->em->remove($address);
                }
            }

            $phones = $contact->getPhones()->toArray();
            /** @var Phone $phone */
            foreach ($phones as $phone) {
                if (0 == $phone->getAccounts()->count() && 1 == $phone->getContacts()->count()) {
                    $this->em->remove($phone);
                }
            }
            $emails = $contact->getEmails()->toArray();
            /** @var Email $email */
            foreach ($emails as $email) {
                if (0 == $email->getAccounts()->count() && 1 == $email->getContacts()->count()) {
                    $this->em->remove($email);
                }
            }

            $urls = $contact->getUrls()->toArray();
            /** @var Url $url */
            foreach ($urls as $url) {
                if (0 == $url->getAccounts()->count() && 1 == $url->getContacts()->count()) {
                    $this->em->remove($url);
                }
            }

            $faxes = $contact->getFaxes()->toArray();
            /** @var Fax $fax */
            foreach ($faxes as $fax) {
                if (0 == $fax->getAccounts()->count() && 1 == $fax->getContacts()->count()) {
                    $this->em->remove($fax);
                }
            }

            $socialMediaProfiles = $contact->getSocialMediaProfiles()->toArray();
            /** @var SocialMediaProfile $socialMediaProfile */
            foreach ($socialMediaProfiles as $socialMediaProfile) {
                if (0 == $socialMediaProfile->getAccounts()->count()
                    && 1 == $socialMediaProfile->getContacts()->count()
                ) {
                    $this->em->remove($socialMediaProfile);
                }
            }

            $notes = $contact->getNotes()->toArray();
            /** @var Note $note */
            foreach ($notes as $note) {
                if (0 == $note->getAccounts()->count() && 1 == $note->getContacts()->count()) {
                    $this->em->remove($note);
                }
            }

            $this->em->remove($contact);
            $this->em->flush();
        };

        return $delete;
    }