/**
  * @return PromiseInterface
  */
 public function execute()
 {
     return \WyriHaximus\React\childProcessPromise($this->loop, new Process('echo %NUMBER_OF_PROCESSORS%'))->then(function (ProcessOutcome $outcome) {
         if ($outcome->getExitCode() == 0) {
             return \React\Promise\resolve((int) trim($outcome->getStdout()));
         }
         return \React\Promise\reject();
     });
 }
Пример #2
0
 /**
  * @param string $program
  * @return PromiseInterface
  */
 public function execute($program = '')
 {
     return \WyriHaximus\React\childProcessPromise($this->loop, new Process('hash ' . $program))->then(function (ProcessOutcome $outcome) {
         if ($outcome->getExitCode() == 0) {
             return \React\Promise\resolve();
         }
         return \React\Promise\reject();
     });
 }
Пример #3
0
 /** @test */
 public function shouldPropagateRejectionsWhenErrbackReturnsARejection()
 {
     $adapter = $this->getPromiseTestAdapter();
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($this->identicalTo(2));
     $adapter->reject(1);
     $adapter->promise()->then($this->expectCallableNever(), function ($val) {
         return \React\Promise\reject($val + 1);
     })->then($this->expectCallableNever(), $mock);
 }
 /** @test */
 public function thenShouldSwitchFromCallbacksToErrbacksWhenCallbackReturnsARejection()
 {
     $adapter = $this->getPromiseTestAdapter();
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($this->identicalTo(2));
     $adapter->resolve(1);
     $adapter->promise()->then(function ($val) {
         return \React\Promise\reject($val + 1);
     }, $this->expectCallableNever())->then($this->expectCallableNever(), $mock);
 }
 /**
  * RPC Call - Set configuration
  *
  * @param \WyriHaximus\React\ChildProcess\Messenger\Messages\Payload $payload
  * @return \React\Promise\FulfilledPromise|\React\Promise\Promise
  */
 public function rpcConfig(Payload $payload)
 {
     try {
         $this->setAdapter(isset($payload['service']) ? $payload['service'] : self::DEFAULT_ADAPTER);
         if (!empty($payload['service_config'])) {
             $this->adapter->setConfig($payload['service_config']);
         }
     } catch (\Exception $ex) {
         return \React\Promise\reject(['success' => false, 'error' => $ex->getMessage()]);
     }
     return \React\Promise\resolve(['success' => true]);
 }
Пример #6
0
 public function work($interval = 5)
 {
     if ($this->shutdown) {
         if (!$this->waitShutdown) {
             $this->retry($this->loop, function () {
                 if ($this->processing === 0) {
                     return \React\Promise\resolve();
                 }
                 return \React\Promise\reject();
             })->then(function ($response = null) {
                 $this->loop->addTimer(3, function ($timer) {
                     $this->unregisterWorker()->then(function ($response = null) {
                         return Resque::redis()->quit()->then(function ($response = null) {
                             return Resque::redis()->close();
                         });
                     })->then(function ($response = null) {
                         $this->loop->stop();
                     }, function ($e = null) {
                         error_log($e);
                         $this->loop->stop();
                     });
                 });
             });
             $this->waitShutdown = true;
         }
         return;
     }
     $this->reserve()->then(function ($response) use($interval) {
         if (!$response) {
             return;
         }
         list($name, $payload) = $response;
         $names = explode(':', $name);
         $queueName = array_pop($names);
         $job = new Job($queueName, json_decode($payload, true));
         $job->worker = $this;
         $job->perform();
     })->then(function () use($interval) {
         $this->loop->futureTick(function () use($interval) {
             $this->work($interval);
         });
     }, function ($e = null) use($interval) {
         if ($e instanceof \Exception) {
             error_log(sprintf('%s:%s in %s at %d', get_class($e), $e->getMessage(), __FILE__, __LINE__));
         }
         error_log($e);
         $this->shutdown();
         $this->work($interval);
     });
 }
Пример #7
0
 function getConnection()
 {
     if (!empty($this->pool)) {
         $key = key($this->pool);
         $conn = $this->pool[$key];
         unset($this->pool[$key]);
         return \React\Promise\resolve($conn);
     }
     if ($this->pool_i >= $this->maxConnections) {
         $deferred = new Deferred();
         $this->waiting[] = $deferred;
         return $deferred->promise();
     }
     $conn = call_user_func($this->makeConnection);
     if ($conn !== false) {
         $this->pool_i++;
     }
     return $conn === false ? \React\Promise\reject(new \Exception(mysqli_connect_error())) : \React\Promise\resolve($conn);
 }
Пример #8
0
 /**
  * @param HandBetPair $hand
  * @param DealerHand  $dealerHand
  *
  * @return Promise
  */
 public function requestAction(HandBetPair $hand, DealerHand $dealerHand)
 {
     return \Blackjack\Promise\timedResolve(self::RESPONSE_SPEED)->then(function () use($hand, $dealerHand) {
         if ($this->getSeat() === null) {
             return \React\Promise\reject(new \RuntimeException('Player kicked'));
         }
         if ($hand->getHand()->canSplitPair()) {
             return \React\Promise\resolve(new HandAction(HandAction::ACTION_SPLIT));
         }
         if ($hand->getHand()->getValue() === 10) {
             return \React\Promise\resolve(new HandAction(HandAction::ACTION_DOUBLE_DOWN));
         }
         if ($hand->getHand()->getValue() < 17) {
             return \React\Promise\resolve(new HandAction(HandAction::ACTION_HIT));
         } else {
             return \React\Promise\resolve(new HandAction(HandAction::ACTION_STAND));
         }
     });
 }
Пример #9
0
 /**
  * @it nulls out error subtrees
  */
 public function testNullsOutErrorSubtrees()
 {
     $doc = '{
   sync
   syncError
   syncRawError
   syncReturnError
   syncReturnErrorList
   async
   asyncReject
   asyncRawReject
   asyncEmptyReject
   asyncError
   asyncRawError
   asyncReturnError
     }';
     $data = ['sync' => function () {
         return 'sync';
     }, 'syncError' => function () {
         throw new \Exception('Error getting syncError');
     }, 'syncRawError' => function () {
         throw new \Exception('Error getting syncRawError');
     }, 'syncReturnError' => function () {
         return new \Exception('Error getting syncReturnError');
     }, 'syncReturnErrorList' => function () {
         return ['sync0', new \Exception('Error getting syncReturnErrorList1'), 'sync2', new \Exception('Error getting syncReturnErrorList3')];
     }, 'async' => function () {
         return new Promise(function (callable $resolve) {
             return $resolve('async');
         });
     }, 'asyncReject' => function () {
         return new Promise(function ($_, callable $reject) {
             return $reject('Error getting asyncReject');
         });
     }, 'asyncRawReject' => function () {
         return \React\Promise\reject('Error getting asyncRawReject');
     }, 'asyncEmptyReject' => function () {
         return \React\Promise\reject();
     }, 'asyncError' => function () {
         return new Promise(function () {
             throw new \Exception('Error getting asyncError');
         });
     }, 'asyncRawError' => function () {
         return new Promise(function () {
             throw new \Exception('Error getting asyncRawError');
         });
     }, 'asyncReturnError' => function () {
         return \React\Promise\resolve(new \Exception('Error getting asyncReturnError'));
     }];
     $docAst = Parser::parse($doc);
     $schema = new Schema(['query' => new ObjectType(['name' => 'Type', 'fields' => ['sync' => ['type' => Type::string()], 'syncError' => ['type' => Type::string()], 'syncRawError' => ['type' => Type::string()], 'syncReturnError' => ['type' => Type::string()], 'syncReturnErrorList' => ['type' => Type::listOf(Type::string())], 'async' => ['type' => Type::string()], 'asyncReject' => ['type' => Type::string()], 'asyncRawReject' => ['type' => Type::string()], 'asyncEmptyReject' => ['type' => Type::string()], 'asyncError' => ['type' => Type::string()], 'asyncRawError' => ['type' => Type::string()], 'asyncReturnError' => ['type' => Type::string()]]])]);
     $expected = ['data' => ['sync' => 'sync', 'syncError' => null, 'syncRawError' => null, 'syncReturnError' => null, 'syncReturnErrorList' => ['sync0', null, 'sync2', null], 'async' => 'async', 'asyncReject' => null, 'asyncRawReject' => null, 'asyncEmptyReject' => null, 'asyncError' => null, 'asyncRawError' => null, 'asyncReturnError' => null], 'errors' => [['message' => 'Error getting syncError', 'locations' => [['line' => 3, 'column' => 7]], 'path' => ['syncError']], ['message' => 'Error getting syncRawError', 'locations' => [['line' => 4, 'column' => 7]], 'path' => ['syncRawError']], ['message' => 'Error getting syncReturnError', 'locations' => [['line' => 5, 'column' => 7]], 'path' => ['syncReturnError']], ['message' => 'Error getting syncReturnErrorList1', 'locations' => [['line' => 6, 'column' => 7]], 'path' => ['syncReturnErrorList', 1]], ['message' => 'Error getting syncReturnErrorList3', 'locations' => [['line' => 6, 'column' => 7]], 'path' => ['syncReturnErrorList', 3]], ['message' => 'Error getting asyncReject', 'locations' => [['line' => 8, 'column' => 7]], 'path' => ['asyncReject']], ['message' => 'Error getting asyncRawReject', 'locations' => [['line' => 9, 'column' => 7]], 'path' => ['asyncRawReject']], ['message' => 'An unknown error occurred.', 'locations' => [['line' => 10, 'column' => 7]], 'path' => ['asyncEmptyReject']], ['message' => 'Error getting asyncError', 'locations' => [['line' => 11, 'column' => 7]], 'path' => ['asyncError']], ['message' => 'Error getting asyncRawError', 'locations' => [['line' => 12, 'column' => 7]], 'path' => ['asyncRawError']], ['message' => 'Error getting asyncReturnError', 'locations' => [['line' => 13, 'column' => 7]], 'path' => ['asyncReturnError']]]];
     Executor::setPromiseAdapter(new ReactPromiseAdapter());
     $result = Executor::execute($schema, $docAst, $data);
     $this->assertEquals($expected, self::awaitPromise($result));
 }
 /**
  * @param Rpc $message
  * @return PromiseInterface
  */
 protected function sendRpc(Rpc $message)
 {
     $messenger = $this->readyPool->dequeue();
     return $messenger->rpc($message)->then(function ($data) use($messenger) {
         $this->readyPool->enqueue($messenger);
         $this->checkQueue();
         return \React\Promise\resolve($data);
     }, function ($error) use($messenger) {
         $this->readyPool->enqueue($messenger);
         $this->checkQueue();
         return \React\Promise\reject($error);
     });
 }
Пример #11
0
 /**
  * @describe [T!]!
  */
 public function testHandlesNonNullListOfNonNullsWithArrayPromise()
 {
     // Contains values
     $this->checkHandlesNonNullListOfNonNulls([\React\Promise\resolve(1), \React\Promise\resolve(2)], ['data' => ['nest' => ['test' => [1, 2]]]]);
     // Contains null
     $this->checkHandlesNonNullListOfNonNulls([\React\Promise\resolve(1), \React\Promise\resolve(null), \React\Promise\resolve(2)], ['data' => ['nest' => null], 'errors' => [FormattedError::create('Cannot return null for non-nullable field DataType.test.', [new SourceLocation(1, 10)])]]);
     // Contains reject
     $this->checkHandlesNonNullListOfNonNulls(function () {
         return [\React\Promise\resolve(1), \React\Promise\reject(new \Exception('bad')), \React\Promise\resolve(2)];
     }, ['data' => ['nest' => null], 'errors' => [['message' => 'bad', 'locations' => [['line' => 1, 'column' => 10]], 'path' => ['nest', 'test']]]]);
 }
Пример #12
0
 public function ensurePlayerActive(Player $player, $value = null)
 {
     if ($player->getSeat() === null || $player->getTable() !== $this) {
         return \React\Promise\reject(new \RuntimeException('Player left table'));
     }
     return \React\Promise\resolve($value);
 }
Пример #13
0
 /**
  * {@inheritDoc}
  */
 public function open($path, $flags, $mode = self::CREATION_MODE)
 {
     $flags = $this->openFlagResolver->resolve($flags);
     $mode = $this->permissionFlagResolver->resolve($mode);
     return $this->openFileLimiter->open()->then(function () use($path, $flags, $mode) {
         return $this->invoker->invokeCall('eio_open', [$path, $flags, $mode]);
     })->then(function ($fileDescriptor) use($path, $flags) {
         return Eio\StreamFactory::create($path, $fileDescriptor, $flags, $this);
     }, function ($error) {
         $this->openFileLimiter->close();
         return \React\Promise\reject($error);
     });
 }
Пример #14
0
 /**
  * Stops all processes for this command
  */
 public function stopProcess()
 {
     $promises = [];
     if (count($this->processes) < 1) {
         return \React\Promise\reject("No Process to stop");
     }
     foreach ($this->processes as $process) {
         $deffer = new Deferred();
         if ($process->isRunning()) {
             $process->terminate();
         }
         $process->on('exit', function () use($deffer) {
             $deffer->resolve();
         });
         $promises[] = $deffer->promise();
     }
     return \React\Promise\all($promises);
 }
Пример #15
0
 /**
  * @inheritdoc
  *
  * @return \React\Promise\RejectedPromise
  */
 public function createRejectedPromise($reason)
 {
     return \React\Promise\reject($reason);
 }
Пример #16
0
 /** @test */
 public function alwaysShouldRejectWhenHandlerRejectsForFulfillment()
 {
     $adapter = $this->getPromiseTestAdapter();
     $exception = new \Exception();
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($this->identicalTo($exception));
     $adapter->promise()->always(function () use($exception) {
         return \React\Promise\reject($exception);
     })->then(null, $mock);
     $adapter->resolve(1);
 }
Пример #17
0
 /**
  * @param string $class
  * @param int    $timeout
  *
  * @return Promise
  */
 public function waitOnMessage($class, $timeout = 3)
 {
     $deferred = new Deferred();
     $this->messageQueue[] = ['class' => $class, 'deferred' => $deferred];
     return \Blackjack\Promise\timeout($deferred->promise(), $timeout)->otherwise(function (\Exception $e) use($deferred) {
         $this->messageQueue = $this->messageQueue->filter(function ($entry) use($deferred) {
             return $entry['deferred'] !== $deferred;
         });
         return \React\Promise\reject($e);
     });
 }