Generate, store, and return the index and token

@param string $lockTo What URI endpoint this is valid for
@return string[]
@throws \TypeError
@throws \Exception
356141
protected function generateToken(string $lockTo): array
    {
        $index = Base64UrlSafe::encode(\random_bytes(18));
        $token = Base64UrlSafe::encode(\random_bytes(33));

        $new = $this->buildBasicToken([
            'created' => \intval(
                \date('YmdHis')
            ),
            'uri' => isset($this->server['REQUEST_URI'])
                ? $this->server['REQUEST_URI']
                : $this->server['SCRIPT_NAME'],
            'token' => $token
        ]);

        if (\preg_match('#/$#', $lockTo)) {
            $lockTo = Binary::safeSubstr(
                $lockTo,
                0,
                Binary::safeStrlen($lockTo) - 1
            );
        }

        if ($this->useNativeSession) {
            /** @var array<string, array<string, string|int>> $sess */
            $sess =& $_SESSION[$this->sessionIndex];
        } else {
            /** @var array<string, array<string, string|int>> $sess */
            $sess =& $this->session[$this->sessionIndex];
        }
        $sess[$index] = $new;
        $sess[$index]['lockTo'] = $lockTo;

        $this->recycleTokens();
        return [$index, $token];
    }
1136121
public function generateTokenValues(TokenInterface $token): array
    {
        $tokenValue     = bin2hex(random_bytes(16)) . uniqid();
        $tokenType      = 'bearer';
        $tokenExpiresIn = $this->getTokenExpirationPeriod();
        $refreshValue   = bin2hex(random_bytes(16)) . uniqid();

        assert(is_string($tokenValue) === true && empty($tokenValue) === false);
        assert(is_string($tokenType) === true && empty($tokenType) === false);
        assert(is_int($tokenExpiresIn) === true && $tokenExpiresIn > 0);
        assert($refreshValue === null || (is_string($refreshValue) === true && empty($refreshValue) === false));

        return [$tokenValue, $tokenType, $tokenExpiresIn, $refreshValue];
    }
1162560
public function getIndexOptions($indexData)
    {
        $options = [];

        if (isset($indexData['Key_name'])) {
            $options[] = '\'name\' => "' . $indexData['Key_name'] . '"';
        }
        if (isset($indexData['Non_unique']) && $indexData['Non_unique'] == 1) {
            $options[] = '\'unique\' => false';
        } else {
            $options[] = '\'unique\' => true';
        }
        /*
         * Number of characters for nonbinary string types (CHAR, VARCHAR, TEXT)
         * and number of bytes for binary string types (BINARY, VARBINARY, BLOB)
         */
        if (isset($indexData['Sub_part'])) {
            $options[] = '\'limit\' => ' . $indexData['Sub_part'];
        }
        // MyISAM only
        if (isset($indexData['Index_type']) && $indexData['Index_type'] == 'FULLTEXT') {
            $options[] = '\'type\' => \'fulltext\'';
        }
        $result = '[' . implode(', ', $options) . ']';

        return $result;
    }
124387
protected function getItemsIblockShard()
    {
        $items = [];

        $rsIblocks = IblockTable::query()
            ->setFilter(['ID' => $this->id])
            ->setSelect(['IBLOCK_TYPE_ID', 'CODE'])
            ->exec();

        if ($iblock = $rsIblocks->fetch()) {
            if ($iblock['CODE']) {
                $items['CODE'] = $iblock['CODE'];
            }

            $items['TYPE'] = $iblock['IBLOCK_TYPE_ID'];
        }

        if (empty($items)) {
            throw new ValueNotFoundException('Iblock', 'ID #' . $this->id);
        }

        $propIds = [];

        $rsProps = PropertyTable::query()
            ->setFilter(['IBLOCK_ID' => $this->id])
            ->setSelect(['ID', 'CODE', 'IBLOCK_ID'])
            ->exec();

        while ($prop = $rsProps->fetch()) {
            $propIds[] = $prop['ID'];
            $items['PROPS_ID'][$prop['CODE']] = $prop['ID'];
        }

        if (!empty($propIds)) {
            $rsPropsEnum = PropertyEnumerationTable::query()
                ->setFilter(['PROPERTY_ID' => $propIds])
                ->setSelect(['ID', 'XML_ID', 'PROPERTY_ID', 'PROPERTY_CODE' => 'PROPERTY.CODE'])
                ->exec();

            while ($propEnum = $rsPropsEnum->fetch()) {
                if ($propEnum['PROPERTY_CODE']) {
                    $items['PROPS_ENUM_ID'][$propEnum['PROPERTY_CODE']][$propEnum['XML_ID']] = $propEnum['ID'];
                }
            }
        }

        $this->registerCacheTag('bex_iblock_' . $this->id);

        return $items;
    }
742078
public function getRefreshToken($refreshToken)
    {
        $refreshTokenDataMapper = $this->getTokenDataMapper(Entity\RefreshToken::class);

        $token = $refreshTokenDataMapper->findByToken($refreshToken);

        if (! $token instanceof Entity\RefreshToken) {
            return;
        }

        return [
            'refresh_token' => $token->getToken(),
            'client_id'     => $token->getClient()->getUuid(),
            'user_id'       => $token->getUser() ? $token->getUser()->getUuid() : null,
            'expires'       => $token->getExpiryUTCTimestamp(),
            'scope'         => $token->getScopesString(),
        ];
    }
1361871
public function getAuthRefNum($orderIndex = 0)
    {
        $orderStatuses = $this->getOrderStatuses();
        return array_key_exists('authRefNum', $orderStatuses[$orderIndex])
            ? $orderStatuses[$orderIndex]['authRefNum'] : null;
    }
244766
function get()
    {
        foreach($this->types as $type) {
            if ($this->{$type}) {
                array_push($this->random, $this->getCharacter($type));
            }
        }

        for($i = $this->counter; $i < $this->length; $i++) {
            array_push($this->random,  $this->getCharacterFromArray());
        }

        $randomPassword = str_shuffle(implode('', $this->random));

        return new Password($randomPassword);
    }
333662
public function toArray($reindex = false)
    {
        $array = [];

        foreach ($this as $key => $path) {
            if ($reindex) {
                $array[] = (string) clone $path;
            } else {
                $array[$key] = (string) clone $path;
            }
        }

        return $array;
    }
528455
public function getIndicesWithAlias($alias)
    {
        $endpoint = new Get();
        $endpoint->setName($alias);

        $response = null;

        try {
            $response = $this->_client->requestEndpoint($endpoint);
        } catch (ResponseException $e) {
            // 404 means the index alias doesn't exist which means no indexes have it.
            if (404 === $e->getResponse()->getStatus()) {
                return [];
            }
            // If we don't have a 404 then this is still unexpected so rethrow the exception.
            throw $e;
        }
        $indices = [];
        foreach ($response->getData() as $name => $unused) {
            $indices[] = new Index($this->_client, $name);
        }

        return $indices;
    }
801452
public function _singleUpdateLock($lockFile)
    {
        $lockData = [
            'pid' => getmypid(),
            'expires_at' => time() + $this->singleSleep + $this->singleLockTimeout,
        ];

        return file_put_contents($lockFile, json_encode($lockData));
    }
346296
public function find($id, $lockMode = LockMode::NONE, $lockVersion = null)
    {
        // Check identity map first
        if ($entity = $this->xem->getUnitOfWork()->tryGetById($id, $this->class->rootXmlEntityName)) {
            if ($lockMode != LockMode::NONE) {
                $this->xem->lock($entity, $lockMode, $lockVersion);
            }

            return $entity; // Hit!
        }

        if ($lockMode == LockMode::NONE) {
            return $this->xem->getUnitOfWork()->getXmlEntityPersister($this->entityName)->load($id);
        } else if ($lockMode == LockMode::OPTIMISTIC) {
            if (!$this->class->isVersioned) {
                throw OptimisticLockException::notVersioned($this->entityName);
            }
            $entity = $this->xem->getUnitOfWork()->getXmlEntityPersister($this->entityName)->load($id);

            $this->xem->getUnitOfWork()->lock($entity, $lockMode, $lockVersion);

            return $entity;
        } else {
            if (!$this->xem->getConnection()->isTransactionActive()) {
                throw TransactionRequiredException::transactionRequired();
            }

            return $this->xem->getUnitOfWork()->getXmlEntityPersister($this->entityName)->load($id, null, null, array(), $lockMode);
        }
    }
471723
private static function getByIndexes(array $original, array $positions)
    {
        $result = [];

        foreach ($positions as $key => $position) {
            $result[$key] = $original[$key][$position];
        }

        return $result;
    }
685738
public function getAndStoreToken()
    {
        $token = $this->generateToken(6);
        
        $this->setAttribute('secure_token', sha1($token));
        $this->setAttribute('secure_token_timestamp', time());
        $this->update(false);

        return $token;
    }
1346639
public static function toKeyIndex($collection, $key, $useDotSyntax = false)
    {
        $keyIndexArray = [];
        foreach ($collection as $item) {
            $itemArray = is_array($item) ? $item : (method_exists($item, 'toArray') ? $item->toArray() : []);
            $keyValue = self::get($itemArray, $key, null, $useDotSyntax);
            $keyIndexArray[$keyValue] = $itemArray;
        }

        return $keyIndexArray;
    }
357350
public function getLockedDocuments($fromDateTime = null , $tillDateTime = null)
    {
        $query = array();
        if(!empty($fromDateTime) || !empty($tillDateTime)){
            $query[_LOCKED_FOR_TRANS_TS] = array();

            if (!empty($fromDateTime)) {
                $query[_LOCKED_FOR_TRANS_TS][MONGO_OPERATION_GTE] = \Tripod\Mongo\DateUtil::getMongoDate(strtotime($fromDateTime)*1000);
            }
            if (!empty($tillDateTime)) {
                $query[_LOCKED_FOR_TRANS_TS][MONGO_OPERATION_LTE] = \Tripod\Mongo\DateUtil::getMongoDate(strtotime($tillDateTime)*1000);
            }
        }
        $docs = $this->getLocksCollection()->find($query, array('sort' => array(_LOCKED_FOR_TRANS => 1)));

        if($this->getLocksCollection()->count($query) == 0 ) {
            return array();
        }

        $res = array();
        foreach($docs as $doc){
            $res[] = $doc;
        }
        return $res;
    }
609836
public function offsetGet($offset)
	{
		if(empty($this->tokens[$offset]))
		{
			throw new \OutOfBoundsException('No token found at offset ' . $offset);
		}

		return $this->tokens[$offset];
	}
443033
public function getIndexMap(string $indexKey = null)
    {
        if (null === $indexKey) {
            return $this->getEntries();
        }

        // Get storage keys for the objects.
        $index = [];
        foreach ($this->getEntries() as $key => $value) {
            $index[$key] = $value[$indexKey] ?? null;
        }

        return $index;
    }