本文整理汇总了PHP中Amp\resolve函数的典型用法代码示例。如果您正苦于以下问题:PHP resolve函数的具体用法?PHP resolve怎么用?PHP resolve使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了resolve函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: resolveMessageText
public function resolveMessageText(Room $room, string $text, int $flags = self::MATCH_ANY) : Promise
{
if (preg_match('~^:\\d+\\s+(.+)~', $text, $match)) {
$text = $match[1];
}
return resolve(function () use($room, $text, $flags) {
if ($flags & self::MATCH_PERMALINKS) {
try {
$messageID = $this->resolveMessageIDFromPermalink($text);
$text = (yield $this->chatClient->getMessageText($room, $messageID));
return $flags & self::RECURSE ? $this->resolveMessageText($room, $text, $flags | self::MATCH_LITERAL_TEXT) : $text;
} catch (MessageIDNotFoundException $e) {
/* ignore, there may be other matches */
}
}
if ($flags & self::MATCH_MESSAGE_IDS && ctype_digit($text)) {
$text = (yield $this->chatClient->getMessageText($room, (int) $text));
return $flags & self::RECURSE ? $this->resolveMessageText($room, $text, $flags | self::MATCH_LITERAL_TEXT) : $text;
}
if ($flags & self::MATCH_LITERAL_TEXT) {
return $text;
}
throw new MessageFetchFailureException();
});
}
示例2: getAllMappedCommands
public function getAllMappedCommands(ChatRoom $room, string $plugin) : Promise
{
return resolve(function () use($room, $plugin) {
$data = (yield $this->accessor->read($this->dataFileTemplate, $room));
return $data[strtolower($plugin)]['commands'] ?? null;
});
}
示例3: isBanned
public function isBanned(ChatRoom $room, int $userId) : Promise
{
return resolve(function () use($room, $userId) {
$banned = (yield $this->accessor->read($this->dataFileTemplate, $room));
return array_key_exists($userId, $banned) && new \DateTimeImmutable($banned[$userId]) > new \DateTimeImmutable();
});
}
示例4: doLogIn
public function doLogIn(Request $request, Response $response, array $args)
{
$session = (yield (new Session($request))->read());
$provider = $this->getProviderFromString($args["provider"]);
$token = $session->get("token:oauth");
$get = $request->getQueryVars();
$code = isset($get["code"]) && is_string($get["code"]) ? $get["code"] : "";
$state = isset($get["state"]) && is_string($get["state"]) ? $get["state"] : "";
if (empty($code) || empty($state) || empty($token) || !hash_equals($token, $state)) {
$response->setStatus(400);
$response->setHeader("aerys-generic-response", "enable");
$response->send("");
return;
}
try {
$accessToken = (yield resolve($provider->getAccessTokenFromCode($code)));
} catch (OAuthException $e) {
// TODO pretty error page
$response->setStatus(403);
$response->setHeader("aerys-generic-response", "enable");
$response->send("");
return;
} catch (ResolutionException $e) {
// TODO pretty error page
$response->setStatus(503);
$response->setHeader("aerys-generic-response", "enable");
$response->send("");
return;
}
$identity = (yield resolve($provider->getIdentity($accessToken)));
if (!$identity) {
$response->setStatus(403);
$response->setHeader("aerys-generic-response", "enable");
$response->send("");
return;
}
$query = (yield $this->db->prepare("SELECT user_id FROM oauth WHERE provider = ? AND identity = ?", [$args["provider"], $identity["id"]]));
$response->setStatus(302);
$user = (yield $query->fetchObject());
$query = (yield $this->db->prepare("SELECT id, name, avatar FROM user WHERE id = ?", [$user->user_id]));
$user = (yield $query->fetchObject());
(yield $session->open());
if ($user) {
$session->set("login", $user->id);
$session->set("login:name", $user->name);
$session->set("login:avatar", $user->avatar);
$session->set("login:time", time());
$response->setHeader("location", "/");
} else {
$session->set("auth:provider", $args["provider"]);
$session->set("auth:identity:id", $identity["id"]);
$session->set("auth:identity:name", $identity["name"]);
$session->set("auth:identify:avatar", $identity["avatar"]);
$response->setHeader("location", "/join");
}
(yield $session->save());
$response->send("");
}
示例5: getRoomSessionInfo
public function getRoomSessionInfo(Identifier $identifier) : Promise
{
$deferred = new Deferred();
$this->queue->push([$identifier, $deferred]);
if (!$this->haveLoop) {
resolve($this->executeActionsFromQueue());
}
return $deferred->promise();
}
示例6: connect
public function connect(Identifier $identifier, PresenceManager $presenceManager, bool $permanent) : Promise
{
return resolve(function () use($identifier, $presenceManager, $permanent) {
/** @var Session $sessionInfo */
$sessionInfo = (yield $this->authenticator->getRoomSessionInfo($identifier));
$handshake = $this->handshakeFactory->build($sessionInfo->getWebSocketUrl())->setHeader('Origin', 'https://' . $identifier->getHost());
$handler = $this->handlerFactory->build($identifier, $presenceManager);
(yield websocket($handler, $handshake));
return $this->roomFactory->build($identifier, $sessionInfo, $handler, $presenceManager, $permanent);
});
}
示例7: isAdmin
public function isAdmin(ChatRoom $room, int $userId) : Promise
{
return resolve(function () use($room, $userId) {
// inb4 people "testing" removing me from the admin list
if ($userId === 508666) {
return true;
}
$administrators = (yield $this->getAll($room));
return $administrators['owners'] === [] && $administrators['admins'] === [] || in_array($userId, $administrators['owners'], true) || in_array($userId, $administrators['admins'], true);
});
}
示例8: executeCoroutineWithLock
protected function executeCoroutineWithLock(\Generator $generator) : Promise
{
return resolve(function () use($generator) {
/** @var Lock $lock */
$lock = (yield $this->getLock());
try {
return yield from $generator;
} finally {
$lock->release();
}
});
}
示例9: ttl
/**
* {@inheritdoc}
*
* @param string $id rate limit key
* @return Promise
*/
public function ttl(string $id) : Promise
{
$fn = function () use($id) {
$ttl = (yield $this->redis->ttl($id));
if ($ttl < 0) {
return $this->ttl;
} else {
return $ttl;
}
};
return resolve($fn());
}
示例10: log
public function log(int $logLevel, string $message, $extraData = null) : Promise
{
if (!$this->meetsLogLevel($logLevel)) {
return new Success();
}
$messages = [$message];
if ($extraData !== null && $this->meetsLogLevel(Level::EXTRA_DATA)) {
$messages[] = json_encode($extraData);
}
$this->writeQueue->push([(new \DateTime())->format('Y-m-d H:i:s'), $messages, $deferred = new Deferred()]);
if (!$this->haveWriteLoop) {
resolve($this->writeMessagesFromQueue());
}
return $deferred->promise();
}
示例11: executeForEvent
/**
* @param Event $event
* @return Promise|null
*/
public function executeForEvent(Event $event)
{
foreach ($this->predicates as $predicate) {
if (!$predicate($event)) {
return null;
}
}
$handler = $this->callback;
$result = $handler($event);
if ($result instanceof \Generator) {
return resolve($result);
} else {
if ($handler instanceof Promise) {
return $result;
}
}
return null;
}
示例12: getSupportedLanguages
public function getSupportedLanguages(string $accessToken, string $locale = 'en') : Promise
{
return resolve(function () use($accessToken, $locale) {
/** @var \DOMDocument $doc */
$doc = (yield $this->callApiGetMethod($accessToken, 'GetLanguagesForTranslate'));
$codes = [];
foreach ($doc->getElementsByTagName('string') as $string) {
$codes[] = $string->textContent;
}
$doc = (yield $this->callApiPostMethod($accessToken, 'GetLanguageNames?locale=' . urlencode($locale), $doc));
$languages = [];
foreach ($doc->getElementsByTagName('string') as $i => $string) {
$languages[$codes[$i]] = $string->textContent;
}
asort($languages);
return $languages;
});
}
示例13: doExecute
public function doExecute(Manager $args) : Generator
{
if (posix_geteuid() !== 0) {
throw new AcmeException("Please run this script as root!");
}
$email = $args->get("email");
(yield resolve($this->checkEmail($email)));
$server = $args->get("server");
$protocol = substr($server, 0, strpos("://", $server));
if (!$protocol || $protocol === $server) {
$server = "https://" . $server;
} elseif ($protocol !== "https") {
throw new \InvalidArgumentException("Invalid server protocol, only HTTPS supported");
}
$identity = str_replace(["/", "%"], "-", substr($server, 8));
$path = __DIR__ . "/../../data/accounts";
$pathPrivate = "{$path}/{$identity}.private.key";
$pathPublic = "{$path}/{$identity}.public.key";
if ((yield exists($pathPrivate)) && (yield exists($pathPublic))) {
$this->logger->info("Loading existing keys ...");
$private = file_get_contents($pathPrivate);
$public = file_get_contents($pathPublic);
$keyPair = new KeyPair($private, $public);
} else {
$this->logger->info("Generating key keys ...");
$keyPair = (new OpenSSLKeyGenerator())->generate(4096);
if (!file_exists($path) && !mkdir($path, 0700, true)) {
throw new AcmeException("Couldn't create account directory");
}
file_put_contents($pathPrivate, $keyPair->getPrivate());
file_put_contents($pathPublic, $keyPair->getPublic());
chmod($pathPrivate, 600);
chmod($pathPrivate, 600);
}
$acme = new AcmeService(new AcmeClient($server, $keyPair), $keyPair);
$this->logger->info("Registering with ACME server " . substr($server, 8) . " ...");
/** @var Registration $registration */
$registration = (yield $acme->register($email));
$this->logger->notice("Registration successful with contact " . json_encode($registration->getContact()));
}
示例14: handleCommand
public function handleCommand(Command $command) : Promise
{
return resolve(function () use($command) {
$commandName = $command->getCommandName();
if (!isset($this->commands[$commandName])) {
return;
}
$eventId = $command->getEvent()->getId();
$userId = $command->getUserId();
try {
$userIsBanned = (yield $this->banStorage->isBanned($command->getRoom(), $userId));
if ($userIsBanned) {
$this->logger->log(Level::DEBUG, "User #{$userId} is banned, ignoring event #{$eventId} for built in commands");
return;
}
$this->logger->log(Level::DEBUG, "Passing event #{$eventId} to built in command handler " . get_class($this->commands[$commandName]));
(yield $this->commands[$commandName]->handleCommand($command));
} catch (\Throwable $e) {
$this->logger->log(Level::ERROR, "Something went wrong while handling #{$eventId} for built-in commands: {$e}");
}
});
}
示例15: rateLimit
public function rateLimit(Request $request, Response $response)
{
$user = $request->getLocalVar("chat.api.user");
if (!$user) {
// if this happens, something's really wrong, e.g. wrong order of callables
$response->setStatus(500);
$response->send("");
return;
}
$count = (yield resolve($this->rateLimit->increment("limit:u:{$user->id}")));
$ttl = (yield resolve($this->rateLimit->ttl("limit:u:{$user->id}")));
$remaining = self::RATE_LIMIT - $count;
$response->setHeader("x-rate-limit-limit", self::RATE_LIMIT);
$response->setHeader("x-rate-limit-remaining", max(0, $remaining));
$response->setHeader("x-rate-limit-reset", $ttl);
if ($remaining < 0) {
$response->setHeader("retry-after", $ttl);
$error = new Error("too_many_requests", "your application exceeded its rate limit", 429);
$this->writeResponse($request, $response, $error);
}
// a callable further down the chain will send the body
}