public function test_amp_1() { echo "before run()\n"; \Amp\run(function () { \Amp\repeat(function () { echo "tick\n"; }, $msInterval = 1000); \Amp\once("\\Amp\\stop", $msDelay = 5000); }); echo "after run()\n"; }
public function run(InputInterface $inputInterface, OutputInterface $outputInterface) { register_shutdown_function(array($this, 'terminate'), $inputInterface, $outputInterface); \Amp\run(function () use($inputInterface, $outputInterface) { \Amp\repeat(function () use($inputInterface, $outputInterface) { if ($leaking = $this->isLeaking()) { $this->getContainer()->get('logger')->alert('Memory leaked.', $leaking); } parent::run($inputInterface, $outputInterface); }, 1); $outputInterface->writeln('The command has <info>successfully</info> started.'); }); }
public function testKillSignals() { \Amp\run(function () { $process = new Process(self::CMD_PROCESS); $promise = $process->exec(); $process->kill(); $return = (yield $promise); $this->assertObjectHasAttribute('signal', $return); $this->assertObjectHasAttribute('exit', $return); $this->assertInternalType('int', $return->signal); $this->assertInternalType('int', $return->exit); $this->assertEquals(15, $return->signal); $this->assertEquals(-1, $return->exit); }); }
function testVirtualConnection() { $complete = false; \Amp\reactor(\Amp\driver()); \Amp\run(function () use(&$complete) { $db = new Pool("host=" . DB_HOST . ";user="******";pass="******";db=connectiontest"); /* Multiple queries one after the other must be hold back and dispatched to new connections */ for ($i = 0; $i < 5; $i++) { $pings[] = $db->ping(); } (yield \Amp\all($pings)); $complete = true; }); $this->assertEquals(true, $complete, "Database commands did not complete."); }
public function testWatch() { \Amp\run(function () { $process = new Process(self::CMD_PROCESS); $this->assertNull($process->pid()); $promise = $process->exec(); $msg = ""; $promise->watch(function ($update) use(&$msg) { list($type, $partMsg) = $update; $this->assertSame("out", $type); $msg .= $partMsg; }); (yield $promise); $this->assertSame("foo\n", $msg); }); }
<?php use Amp\Process; include __DIR__ . "/../vendor/autoload.php"; \Amp\run(function () { $proc = new Process("echo 1"); $result = (yield $proc->exec(Process::BUFFER_ALL)); var_dump($result->stdout); // "1" });
<?php use Amp\Process; include __DIR__ . "/../vendor/autoload.php"; \Amp\run(function () { $proc = new Process("echo 1; sleep 1; echo 2; sleep 1; echo 3"); $promise = $proc->exec(); $promise->watch(function ($data) { // $data[0] is either "out" or "err", $data[1] the actual data list($type, $msg) = $data; // "1" ... 2 seconds ... "2" ... 2 seconds ... "3" print "{$type}: {$msg}"; }); $result = (yield $promise); // we aren't buffering by default (Process::BUFFER_NONE is default) ... so only exit code present and eventually the killing signal var_dump($result); });
<?php require './example_bootstrap.php'; require 'support/generic_table.php'; \Amp\run(function () { $db = new \Amp\Mysql\Pool("host=" . DB_HOST . ";user="******";pass="******";db=" . DB_NAME); /* create same table than in 003_generic_with_yield.php */ (yield genTable($db)); /* yeah, we need a lot of yields and assigns here... With PHP 7 we finally can drop a lot of stupid parenthesis! */ $query = (yield $db->query("SELECT a * b FROM tmp")); while ((list($result) = (yield $query->fetchRow())) !== null) { var_dump($result); // outputs each row of the resultset returned by SELECT a * b FROM tmp } /* or, maybe, wait until they're all fetched (because you anyway only can continue after having full resultset */ $query = (yield $db->query("SELECT a * b FROM tmp")); $objs = (yield $query->fetchObjects()); var_dump($objs); // outputs all the rows as objects of the resultset returned by SELECT a * b FROM tmp $db->close(); });
<?php require './example_bootstrap.php'; \Amp\run(function () { $db = new \Amp\Mysql\Pool("host=" . DB_HOST . ";user="******";pass="******";db=" . DB_NAME); /* Create table and insert a few rows */ /* we need to wait until table is finished, so that we can insert. */ (yield $db->query("CREATE TABLE IF NOT EXISTS tmp SELECT 1 AS a, 2 AS b")); $promises = []; foreach (range(1, 5) as $num) { $promises[] = $db->query("INSERT INTO tmp (a, b) VALUES ({$num}, {$num} * 2)"); } /* wait until everything is inserted (in case where we wouldn't have to wait, we also could just */ (yield \Amp\all($promises)); print "Insertion successful (if it wasn't, an exception would have been thrown by now)\n"; $db->close(); });
$iterator = 0; echo get_class(\Amp\reactor()) . "\n"; $operations = 10000; $values = array(); for ($iterator = 0; $iterator < $operations; $iterator++) { $values[sprintf('%020s', $iterator)] = sha1($iterator); } \Amp\run(function () use(&$i, $values) { $memcached = new \Edo\Memcached(); $memcached->addServer('tcp://127.0.0.1', 11211); $start = microtime(true); foreach ($values as $k => $v) { $stats = (yield $memcached->set($k, $v, 3600)); } $time = microtime(true) - $start; echo "amp-memcached set: {$time}\n"; $start = microtime(true); foreach ($values as $k => $v) { $stats = (yield $memcached->get($k)); } $time = microtime(true) - $start; echo "amp-memcached get: {$time}\n"; \Amp\stop(); }); if (extension_loaded('memcache')) { $memached = new Memcache(); $memached->addServer('127.0.0.1', 11211); $start = microtime(true); foreach ($values as $k => $v) { $memached->set($k, $v, 3600); }
require __DIR__ . '/../vendor/autoload.php'; $i = 0; \Amp\repeat(function () use(&$i) { echo "\n{$i} iterations"; $i = 0; }, 1000); \Amp\once(function () { \Amp\stop(); }, 5000); \Amp\once(function () { \Amp\stop(); }, 10000); echo "##### SET OP/S"; \Amp\run(function () use(&$i) { $memcached = new \Edo\Memcached(); $memcached->addServer('tcp://127.0.0.1', 11211); while (true) { $stats = (yield $memcached->set('key', 'value_key')); $i++; } }); echo "\n##### GET OP/S"; \Amp\run(function () use(&$i) { $memcached = new \Edo\Memcached(); $memcached->addServer('tcp://127.0.0.1', 11211); while (true) { $stats = (yield $memcached->get('key')); $i++; } });
<?php require './example_bootstrap.php'; require 'support/generic_table.php'; \Amp\run(function () { $db = new \Amp\Mysql\Pool("host=" . DB_HOST . ";user="******";pass="******";db=" . DB_NAME); /* create same table than in 003_generic_with_yield.php */ (yield \Amp\resolve(genTable($db))); /* multi statements are enabled by default, but generally stored procedures also might return multiple resultsets anyway */ $promise = $db->query("SELECT a + b FROM tmp; SELECT a - b FROM tmp;"); for ($rows = (yield $promise); $rows !== null; $rows = (yield $rows->next())) { while (($row = (yield $rows->fetch())) !== null) { var_dump($row); // associative array paired with numeric indices } /* be aware that it is *not* optimal to fetch rowCount before fetching data. We only know rowCount when all data has been fetched! So, it has to fetch everything first before knowing rowCount. */ var_dump((yield $rows->rowCount())); } $db->close(); });
<?php require './example_bootstrap.php'; \Amp\run(function () { $db = new \Amp\Mysql\Pool("host=" . DB_HOST . ";user="******";pass="******";db=" . DB_NAME); /* yeah, we need a lot of yields and assigns here... With PHP 7 we finally can drop a lot of stupid parenthesis! */ $query = (yield $db->query("SELECT 1")); list($one) = (yield $query->fetchRow()); var_dump($one); // should output string(1) "1" $db->close(); });
public function testGetStats() { \Amp\run(function () { $stats = (yield $this->memcached->getStats()); $this->assertInternalType('array', $stats); $this->assertArrayHasKey('pid', $stats); \Amp\stop(); }); }
private function registerShutdownHandler() { register_shutdown_function(function () { if (!($err = \error_get_last())) { return; } switch ($err["type"]) { case E_ERROR: case E_PARSE: case E_USER_ERROR: case E_CORE_ERROR: case E_CORE_WARNING: case E_COMPILE_ERROR: case E_COMPILE_WARNING: case E_RECOVERABLE_ERROR: break; default: return; } $this->exitCode = 1; $msg = "{$err["message"]} in {$err["file"]} on line {$err["line"]}"; // FIXME: Fatal error: Uncaught LogicException: Cannot run() recursively; event reactor already active \Amp\run(function () use($msg) { $this->logger->critical($msg); yield from $this->stop(); }); }); }
<?php /* * Generic example for establishing a connection */ require './example_bootstrap.php'; \Amp\run(function () { /* If you want ssl, pass as second argument an array with ssl options (an empty options array is valid too); if null is passed, ssl is not enabled either */ $db = new \Amp\Mysql\Pool("host=" . DB_HOST . ";user="******";pass="******";db=" . DB_NAME); /* use an alternative charset... Default is utf8mb4_general_ci */ $db->setCharset("latin1_general_ci"); /* do something with your connection(s) maintained by Pool */ /* we always close the database here so that there is no read/write watcher anymore and Reactor terminates itself */ $db->close(); });
namespace Room11\Jeeves; use Amp\Artax\Client as HttpClient; use Room11\Jeeves\Fkey\Retriever as FkeyRetriever; use Room11\Jeeves\OpenId\Client; use Room11\Jeeves\Chat\Command\Factory as CommandFactory; use Room11\Jeeves\Chat\Plugin\Collection as PluginCollection; use Room11\Jeeves\Chat\Message\Factory as MessageFactory; use Room11\Jeeves\Chat\Plugin\Version as VersionPlugin; use Room11\Jeeves\Chat\Plugin\Urban as UrbanPlugin; use Room11\Jeeves\Chat\Plugin\Wikipedia as WikipediaPlugin; use Room11\Jeeves\Chat\Plugin\SwordFight as SwordFightPlugin; use Room11\Jeeves\Chat\Plugin\Docs as DocsPlugin; use Room11\Jeeves\Chat\Plugin\Imdb as ImdbPlugin; use Room11\Jeeves\Chat\Client\Xhr as ChatClient; use Amp\Websocket\Handshake; use Room11\Jeeves\WebSocket\Handler; require_once __DIR__ . '/../bootstrap.php'; $httpClient = new HttpClient(); $fkeyRetriever = new FkeyRetriever($httpClient); $openIdClient = new Client($openIdCredentials, $httpClient, $fkeyRetriever); $openIdClient->logIn(); $chatClient = new ChatClient($httpClient, $fkeyRetriever->get('http://chat.stackoverflow.com/rooms/' . $roomId . '/php'), $roomId); $commands = (new PluginCollection(new CommandFactory()))->register(new VersionPlugin($chatClient))->register(new UrbanPlugin($chatClient))->register(new WikipediaPlugin($chatClient))->register(new SwordFightPlugin($chatClient))->register(new DocsPlugin($chatClient))->register(new ImdbPlugin($chatClient)); $webSocketUrl = $openIdClient->getWebSocketUri($roomId); \Amp\run(function () use($webSocketUrl, $commands, $logger) { $handshake = new Handshake($webSocketUrl . '?l=57365782'); $handshake->setHeader('Origin', "http://chat.stackoverflow.com"); $webSocket = new Handler(new MessageFactory(), $commands, $logger); (yield \Amp\websocket($webSocket, $handshake)); });
* * All successful responses are modeled as an Amp\Artax\Response and this result is used to resolve * the promise result. Status codes are accessible via the standard Amp\Artax\Response::getStatus() * method. These should be consulted to determine the success or failure of completed responses. */ $badUri = "this isn't even a real URI!"; $client = new Amp\Artax\Client(); // Yielding a promise that fails will result in an exception // being thrown back into your generator. Amp\run(function () use($client, $badUri) { try { $response = (yield $client->request($badUri)); } catch (Exception $e) { echo $e->getMessage(), "\n"; } }); // Synchronously waiting on a promise that fails will throw. try { $response = Amp\wait($client->request($badUri)); } catch (Exception $e) { echo $e->getMessage(), "\n"; } // Amp\Promise::when() will never throw; errors are passed to // the error-first callback. Amp\run(function () use($client, $badUri) { $client->request($badUri)->when(function ($error, $result) { assert($error instanceof Exception); assert(is_null($result)); echo $error->getMessage(), "\n"; }); });
function testPreparedWithNegativeValue() { \Amp\reactor(\Amp\driver()); \Amp\run(function () { $db = new Connection("host=" . DB_HOST . ";user="******";pass="******";db=connectiontest"); $db->connect(); $db->query("DROP TABLE tmp"); // just in case it would exist... (yield $db->prepare("CREATE TABLE tmp SELECT ? AS a", [-1])); $result = (yield $db->prepare("SELECT a FROM tmp", [])); $this->assertEquals((yield $result->fetchRow()), [-1]); }); }
<?php use Amp\Process; include __DIR__ . "/../vendor/autoload.php"; \Amp\run(function () { $proc = new Process('read ; echo "$REPLY"'); $promise = $proc->exec(Process::BUFFER_ALL); /* send to stdin */ $proc->write("abc\n"); /* wait for process end */ $result = (yield $promise); var_dump($result->stdout); // "abc" });
/** * @throws \Exception */ public function run() { if (!is_callable($this->updateCallback)) { throw new NotCallableException(sprintf('"%s" is not a callable function. Set it via "%s".', 'updateCallback', 'onUpdate')); } \Amp\run(function () { \Amp\repeat(function () { foreach ($this->getUpdates() as $update) { $this->runCallback($update); $this->incrementOffset($update); } }, $this->getTimeout()); }); }