public function __construct(Reactor $reactor = null) { $this->reactor = $reactor ?: \Amp\reactor(); $this->nextId = PHP_INT_MAX * -1; $this->workerStartTasks = new \SplObjectStorage(); $this->taskReflection = new \ReflectionClass('Amp\\Thread\\Task'); $this->taskNotifier = new TaskNotifier(); }
private function getReactorAndAPI() { $reactor = \Amp\reactor(); $cache = new NullResponseCache(); $client = new ArtaxClient(); $client->setOption(ArtaxClient::OP_MS_CONNECT_TIMEOUT, 5000); $client->setOption(ArtaxClient::OP_MS_KEEP_ALIVE_TIMEOUT, 1000); $githubAPI = new GithubService($client, $reactor, $cache, "Danack/test"); return [$reactor, $githubAPI]; }
/** * Create a new filesystem driver best-suited for the current environment * * @return \Amp\File\Driver */ function driver() { $reactor = \Amp\reactor(); if ($reactor instanceof \Amp\UvReactor) { return new UvDriver($reactor); } elseif (\extension_loaded("eio")) { return new EioDriver(); } else { return new BlockingDriver(); } }
public function __construct($connStr, $sslOptions = null, \Amp\Reactor $reactor = null) { $this->reactor = $reactor ?: \Amp\reactor(); if (preg_match("((?:^|;)\\s*limit\\s*=\\s*([^;]*?)\\s*(?:;|\$))is", $connStr, $match, PREG_OFFSET_CAPTURE)) { $this->limit = (int) $match[1][0]; $connStr = substr_replace($connStr, ";", $match[0][1], strlen($match[0][0])); } else { $this->limit = INF; } $this->config = Connection::parseConnStr($connStr, $sslOptions); $this->initLocal(); $this->addConnection(); }
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."); }
private function registerSignalHandler() { if (php_sapi_name() === "phpdbg") { // phpdbg captures SIGINT so don't bother inside the debugger return; } $onSignal = coroutine([$this, "stop"]); if (\Amp\reactor() instanceof UvReactor) { \Amp\onSignal(\UV::SIGINT, $onSignal, ["keep_alive" => false]); \Amp\onSignal(\UV::SIGTERM, $onSignal, ["keep_alive" => false]); } elseif (extension_loaded("pcntl")) { \Amp\repeat("pcntl_signal_dispatch", 1000, ["keep_alive" => false]); pcntl_signal(\SIGINT, $onSignal); pcntl_signal(\SIGTERM, $onSignal); } }
protected function doStart(Console $console) : \Generator { // Shutdown the whole server in case we needed to stop during startup register_shutdown_function(function () use($console) { if (!$this->server) { // ensure a clean reactor for clean shutdown $reactor = \Amp\reactor(); \Amp\reactor(\Amp\driver()); \Amp\wait((new CommandClient((string) $console->getArg("config")))->stop()); \Amp\reactor($reactor); } }); $server = (yield from $this->bootstrapper->boot($this->logger, $console)); (yield $server->start()); $this->server = $server; \Amp\onReadable($this->ipcSock, function ($watcherId) { \Amp\cancel($watcherId); yield from $this->stop(); }); }
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 require __DIR__ . '/../vendor/autoload.php'; $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);
public function testReactor() { $this->assertInstanceOf('\\Amp\\NativeReactor', \Amp\reactor()); }
protected function execute(InputInterface $input, OutputInterface $output) { set_time_limit(10800); // 3 hours is the maximum for this command. Need more? You really screwed something, full suite for all Oblivion vanilla data takes 20 minutes. :) try { $target = $input->getArgument('target'); $this->threadsNumber = $input->getArgument('threadsNumber'); $buildTarget = BuildTargetFactory::get($target); if (count(array_slice(scandir($buildTarget->getWorkspacePath()), 2)) > 0 || count(array_slice(scandir($buildTarget->getTranspiledPath()), 2)) > 0 || count(array_slice(scandir($buildTarget->getArtifactsPath()), 2)) > 0) { $output->writeln("Target " . $target . " current build dir not clean, archive it manually."); return; } $output->writeln("Starting transpiling reactor using " . $this->threadsNumber . " threads..."); $reactor = \Amp\reactor(); $reactor->run(function () use($buildTarget, $output, $reactor) { $errorLog = fopen($buildTarget->getErrorLogPath(), "w+"); $sourceFiles = array_slice(scandir($buildTarget->getSourcePath()), 2); $buildPlanBuilder = new TES5BuildPlanBuilder(unserialize(file_get_contents('app/graph'))); $buildPlan = $buildPlanBuilder->createBuildPlan($sourceFiles, $this->threadsNumber); $totalSourceFiles = count($sourceFiles); $progressBar = new CliProgressBar($totalSourceFiles); $progressBar->display(); $promises = []; foreach ($buildPlan as $threadBuildPlan) { $task = new TranspileChunkJob($buildTarget->getTargetName(), $threadBuildPlan); $deferred = new \Amp\Deferred(); \Amp\once(function () use($deferred, $task) { $task->runTask($deferred); }, 0); $promise = $deferred->promise(); $promise->when(function (\Exception $e = null, $return = null) use($output, $errorLog) { if ($e) { $output->writeln('Exception ' . get_class($e) . ' occurred in one of the threads while transpiling, progress bar will not be accurate..'); fwrite($errorLog, get_class($e) . PHP_EOL . $e->getMessage() . PHP_EOL); } }); $promise->watch(function ($data) use($progressBar, $errorLog) { $progressBar->progress(count($data['scripts'])); if (isset($data['exception'])) { fwrite($errorLog, implode(', ', $data['scripts']) . PHP_EOL . $data['exception']); } }); $promises[] = $promise; } /** * @var Promise $transpilingPromise */ $transpilingPromise = \Amp\any($promises); $transpilingPromise->when(function () use($reactor, $progressBar, $errorLog) { $progressBar->end(); fclose($errorLog); $reactor->stop(); }); }); $output->writeln("Preparing build workspace..."); /* * * @TODO - Create a factory that will provide a PrepareWorkspaceJob based on running system, so we can provide a * native implementation for Windows */ $prepareCommand = new PrepareWorkspaceJob($buildTarget->getTargetName()); $prepareCommand->run(); $output->writeln("Workspace prepared..."); $task = new CompileScriptJob($buildTarget->getTargetName()); $task->run(); $output->writeln("Build completed, archiving ..."); /* * * @TODO - Create a factory that will provide a PrepareWorkspaceJob based on running system, so we can provide a * native implementation for Windows */ $prepareCommand = new ArchiveBuildJob($buildTarget->getTargetName()); $prepareCommand->run(); } catch (\LogicException $e) { $output->writeln("Unknown target " . $target . ", exiting."); return; } catch (\Exception $e) { var_dump($e->getMessage()); exit; } }
<?php use GithubService\GithubArtaxService\GithubService; use ArtaxServiceBuilder\ResponseCache\NullResponseCache; use Amp\Artax\Client as ArtaxClient; use ArtaxServiceBuilder\BadResponseException; use ArtaxServiceBuilder\Oauth2Token; use GithubService\Hydrator\HydratorException; require_once "testBootstrap.php"; $injector = createProvider(); $reactor = \Amp\reactor(); $cache = new NullResponseCache(); $client = new ArtaxClient(); $client->setOption(ArtaxClient::OP_MS_CONNECT_TIMEOUT, 5000); $client->setOption(ArtaxClient::OP_MS_KEEP_ALIVE_TIMEOUT, 1000); $githubAPI = new GithubService($client, $reactor, $cache, "Danack/test"); $token = @file_get_contents("../../GithubToken.txt"); $oauthToken = null; if ($token) { $oauthToken = new Oauth2Token($token); } try { $tagListRequest = $githubAPI->listRepoTags(null, "Danack", "GithubArtaxService"); $tagList = $tagListRequest->execute(); foreach ($tagList as $tag) { /** @var $tag \GithubService\Model\Tag */ printf("tag name %s, commmit %s \n", $tag->name, $tag->commit->sha); } $emojiResult = $githubAPI->listEmojis(null)->execute(); foreach ($emojiResult->emojis as $emoji) { echo $emoji->name . " \n";
function createReactor() { return Amp\reactor(); }
use GithubService\Model\Commit; use GithubService\Model\SearchRepoItem; use BetterReflection\Reflector\ClassReflector; use BetterReflection\SourceLocator\Type\AggregateSourceLocator; use BetterReflection\SourceLocator\Type\SingleFileSourceLocator; use PhpParser\ParserFactory; $tokenFileLocation = __DIR__ . "/../../github_oauth_token.txt"; $existingToken = @file_get_contents($tokenFileLocation); $existingToken = trim($existingToken); if (!$existingToken) { echo "token not found\n"; exit(0); } echo "Using token from file {$tokenFileLocation} \n"; $token = new Oauth2Token($existingToken); $githubClient = new GithubService(new ArtaxClient(), \Amp\reactor(), new FileResponseCache(new FileCachePath(__DIR__ . "/fileCache")), 'Danack/GithubArtaxService'); $downloadedFiles = []; if (false) { // for debugging //$downloadedFiles[] = "./download/phanan_koel_8c862cb9cc43a6715fbd9d9a289ef7e2ac81b523.tar.gz"; } else { $downloadedFiles = downloadFiles($githubClient, $token); } analyzeFiles($downloadedFiles); echo "fin\n"; exit(0); function removeDirectory($path) { if (is_dir($path) == false) { //Directory doesn't exist. return;
<?php $autoloader = (require __DIR__ . '/../vendor/autoload.php'); use GithubService\GithubArtaxService\GithubService; use Amp\Artax\Client as ArtaxClient; use ArtaxServiceBuilder\ResponseCache\NullResponseCache; use GithubService\Model\Tags; use GithubService\AuthToken\NullToken; function displayTags(Tags $repoTags) { foreach ($repoTags as $nextRepoTag) { echo "Found tag: " . $nextRepoTag->name . "\n"; } } $github = new GithubService(new ArtaxClient(), \Amp\reactor(), new NullResponseCache(), 'Danack/GithubArtaxService'); echo "Tags on first page:\n"; //Get the first page of data $command = $github->listRepoTags(new NullToken(), 'php', 'php-src'); $repoTags = $command->execute(); displayTags($repoTags);
public function __construct($config, $sslOptions = null, Reactor $reactor = null) { $this->reactor = $reactor ?: \Amp\reactor(); $this->connInfo = new ConnectionState(); if (!$config instanceof ConnectionConfig) { $config = self::parseConnStr($config, $sslOptions); } if ($config->resolvedHost === null) { $this->resolveHost($config); } $this->config = $config; }
public function setUp() { \Amp\reactor(new \Amp\NativeReactor()); }
<?php namespace Amp\ArtaxTest; use Amp\Artax\Client; use Amp\Artax\Request; use Amp\Artax\FileBody; use Amp\Artax\FormBody; use Amp\NativeReactor; \Amp\reactor(new NativeReactor()); class ClientHttpBinIntegrationTest extends \PHPUnit_Framework_TestCase { public function testDefaultUserAgentSent() { $uri = 'http://httpbin.org/user-agent'; $client = new Client(); $promise = $client->request($uri); $response = \Amp\wait($promise); $this->assertInstanceOf('Amp\\Artax\\Response', $response); $body = $response->getBody(); $result = json_decode($body); $this->assertSame(Client::USER_AGENT, $result->{'user-agent'}); } public function testCustomUserAgentSentIfAssigned() { $uri = 'http://httpbin.org/user-agent'; $client = new Client(); $customUserAgent = 'test-user-agent'; $request = (new Request())->setUri($uri)->setHeader('User-Agent', $customUserAgent); $promise = $client->request($request); $response = \Amp\wait($promise);
public function setUp() { \Amp\reactor(new NativeReactor()); $this->memcached = new \Edo\Memcached(); $this->memcached->addServer('tcp://127.0.0.1', 11211); }