Associate identity

@param int $userId
@param string $identity
@return int affected rows (with insert)
186589
public function associateIdentity( $userId, $identity )
    {
        if ( $this->hasAssociatedIdentity( $userId, $identity ) )
        {
            return 0;
        }

        $sql    = $this->sql( $this->getTableInSchema( 'user_identity' ) );
        $insert = $sql->insert()
                      ->values( array(
                          'userId'    => (int)    $userId,
                          'identity'  => (string) $identity,
                      ) );

        $result = $sql->prepareStatementForSqlObject( $insert )
                      ->execute();

        return $result->getAffectedRows();
    }
67357
public function mergeIdentity($identity, $allow)
	{
		$identity = (int) $identity;
		$allow = (int) ((boolean) $allow);

		// Check that the identity exists.
		if (isset($this->data[$identity]))
		{
			// Explicit deny always wins a merge.
			if ($this->data[$identity] !== 0)
			{
				$this->data[$identity] = $allow;
			}
		}
		else
		{
			$this->data[$identity] = $allow;
		}
	}
835914
function giveIdentity(iIdentity $identity)
    {
        if ($this->identity)
            throw new \Exception('Identity is immutable.');
        
        $defIdentity = $this->_newDefaultIdentity();
        $defIdentity->import($identity);
        if (!$defIdentity->isFulfilled())
            throw new \InvalidArgumentException(sprintf(
                'Identity (%s) not fulfillment (%s).'
                , \Poirot\Std\flatten($identity)
                , \Poirot\Std\flatten($defIdentity)
            ));
        
        $this->identity = $defIdentity;
        return $this;
    }
1042517
function validateUserIdentifier($userId, $identifierName)
    {
        $response = $this->call( new Command\Members\ValidateUserIdentifier($userId, $identifierName) );
        if ( $ex = $response->hasException() )
            throw $ex;


        $r = $response->expected();
        $r = ($r instanceof iDataEntity) ? $r->get('result') : $r;
        return $r;
    }
897843
public function setIdentity(IdentityInterface $identity): void
    {
        // save identity to Auth
        $this->identity = $identity;
        // regenerate session
        if (PHP_SAPI !== 'cli') {
            Session::regenerateId();
        }
        // save identity to session
        Session::set('auth:identity', $identity);
        // save user agent to session
        Session::set('auth:agent', Request::getServer('HTTP_USER_AGENT'));
    }
874572
public function isUserInRoleById(int $userId): bool
    {
        if (isset($this->users[$userId])) {
            return true;
        }

        return false;
    }
855782
public static function get_uniqueid_for_user_static($assignid, $userid) {
        global $DB;

        // Search for a record.
        $params = array('assignment'=>$assignid, 'userid'=>$userid);
        if ($record = $DB->get_record('assign_user_mapping', $params, 'id')) {
            return $record->id;
        }

        // Be a little smart about this - there is no record for the current user.
        // We should ensure any unallocated ids for the current participant
        // list are distrubited randomly.
        self::allocate_unique_ids($assignid);

        // Retry the search for a record.
        if ($record = $DB->get_record('assign_user_mapping', $params, 'id')) {
            return $record->id;
        }

        // The requested user must not be a participant. Add a record anyway.
        $record = new stdClass();
        $record->assignment = $assignid;
        $record->userid = $userid;

        return $DB->insert_record('assign_user_mapping', $record);
    }
115779
static function removeIdentity(\Db\Connection $db, User $user, $openid) {
    if (!$user) {
      throw new \InvalidArgumentException("No user provided.");
    }

    $q = $db->prepare("DELETE FROM user_openid_identities WHERE user_id=? AND identity=? LIMIT 1");
    return $q->execute(array($user->getId(), $openid));
  }
187734
public function getById($identity) {
        $path = $this->path . "/" . $identity;
        return $this->openSearchClient->get($path);
    }
184436
public function stateFor(Identity $identity): State
    {
        foreach ($this->states as $state => $entities) {
            if ($entities->contains($identity)) {
                return $state;
            }
        }

        throw new IdentityNotManaged;
    }
325776
public function SetIdentity($UserID, $Persist = FALSE) {
      if (is_null($UserID)) {
         $this->_ClearIdentity();
         return;
      }
      
      $this->UserID = $UserID;
      
      // If we're persisting, both the cookie and its payload expire in 30days
      $PayloadExpires = time();
      if ($Persist) {
         
         $PayloadExpires += (86400 * self::COOKIE_PERSIST_DAYS);
         $CookieExpires = $PayloadExpires;
         
      // Otherwise the payload expires in 2 days and the cookie expires on borwser restart
      } else {
         // Note: $CookieExpires = 0 causes cookie to die when browser closes.
         
         $PayloadExpires += (86400 * self::COOKIE_SESSION_DAYS);
         $CookieExpires = 0;
      }

      // Create the cookie
      $KeyData = $UserID.'-'.$PayloadExpires;
      $this->_SetCookie($this->CookieName, $KeyData, array($UserID, $PayloadExpires), $CookieExpires);
      $this->SetVolatileMarker($UserID);
   }
1027833
public static function deletePatient($id, $userId = 0) {
		$entityManager = ( object ) DoctrineBootstrap::getEntityManager ();
		$type = 'Hospitalplugin\Entities\Patient';
		$patient = $entityManager->getRepository ( $type )->findOneBy ( array (
				'id' => $id 
		) );
		$entityManager->remove ( $patient );
		$log = strval($patient);
		$audit = new PatientDeleted();
		$audit->deletedAt = new \DateTime ();
		$audit->deletedByUserId = $userId;
		$audit->log = $log;
		$entityManager->persist ( $audit );
		$entityManager->flush ();
	}
1159060
public function isThrottled($identity)
    {
        $identity = $this->parseIdentity($identity);

        // Retuns the current count
        $count = $this->countThrottle($identity, 0);

        return $count >= config('store.throttle_limit', 10);
    }
505161
public function removeById($identity) {
        $path = $this->path . "/" . $identity;
        return $this->openSearchClient->delete($path);
    }
170591
private function checkTwoStepAuthStatus(int $userId)
    {
        $twoStepAuth = TwoStepAuth::firstOrCreate(
            [
                'userId' => $userId,
            ],
            [
                'userId'    => $userId,
                'authCode'  => $this->generateCode(),
                'authCount' => 0,
            ]
        );

        return $twoStepAuth;
    }
583858
public function toOpenId($userId, $agentId)
    {
        $params = [
            'userid'  => $userId,
            'agentid' => $agentId,
        ];

        return $this->parseJSON('json', [self::API_TO_OPENID, $params]);
    }
345208
public function findByIdentity($identity)
    {
        $account = $this->model();

        $account = $account->where(function ($query) use ($identity){

            $firstWhere = true;

            foreach($identity as $attribute => $value){

                if($firstWhere) $query->where($attribute, '=', $value);

                else $query->orWhere($attribute, '=', $value);

                $firstWhere = false;
            }
        });

        $account = $account->get()->first();

        return $account;
    }