Example #1
0
 /**
  * @param EventInterface $value
  * @throws \Exception
  */
 public function onNext($value)
 {
     $uri = $value->getName();
     // TODO add route cache
     foreach ($this->routing as $subject) {
         /* @var ReplaySubject $subject */
         $routes = $this->routing->offsetGet($subject);
         foreach ($routes as $data) {
             if (!preg_match($data['regex'], $uri, $matches)) {
                 continue;
             }
             $vars = [];
             $i = 0;
             foreach ($data['routeMap'] as $varName) {
                 $vars[$varName] = $matches[++$i];
             }
             $labels = $value->getLabels();
             $labels = array_merge($labels, $vars);
             $value->setLabels($labels);
             $subject->onNext($value);
             return;
         }
     }
     throw new \Exception("not found");
 }
Example #2
0
 /**
  * Remove the given log message handler if it is registered.
  * 
  * @param LogHandler $handler
  */
 public function removeHandler(LogHandler $handler)
 {
     if ($this->handlers->contains($handler)) {
         $this->handlers->detach($handler);
         $this->enabled = $this->handlers->count() ? true : false;
     }
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function listen(callable $action) : Awaitable
 {
     return new Coroutine(function () use($action) {
         $factory = clone $this->factory;
         $factory->setTcpNoDelay(true);
         $this->server = (yield $factory->createSocketServer());
         $port = $this->server->getPort();
         $peer = $this->server->getAddress() . ($port ? ':' . $port : '');
         $context = new HttpDriverContext($peer, $factory->getPeerName(), $factory->isEncrypted(), $this->middlewares, $this->responders);
         $pending = new \SplObjectStorage();
         try {
             (yield $this->server->listen(function (SocketStream $socket) use($pending, $context, $action) {
                 $conn = new Connection($socket, $context);
                 if ($this->logger) {
                     $conn->setLogger($this->logger);
                 }
                 $pending->attach($conn);
                 while (null !== ($next = (yield $conn->nextRequest()))) {
                     new Coroutine($this->processRequest($conn, $context, $action, ...$next));
                 }
             }));
         } finally {
             $this->server = null;
             foreach ($pending as $task) {
                 $task->cancel(new \RuntimeException('FCGI server stopped'));
             }
         }
     });
 }
 /**
  * Removes the specified validator.
  *
  * @param \TYPO3\FLOW3\Validation\Validator\ValidatorInterface $validator The validator to remove
  * @throws \TYPO3\FLOW3\Validation\Exception\NoSuchValidatorException
  * @api
  */
 public function removeValidator(\TYPO3\FLOW3\Validation\Validator\ValidatorInterface $validator)
 {
     if (!$this->validators->contains($validator)) {
         throw new \TYPO3\FLOW3\Validation\Exception\NoSuchValidatorException('Cannot remove validator because its not in the conjunction.', 1207020177);
     }
     $this->validators->detach($validator);
 }
 /**
  * Public such that it is callable from within closures
  *
  * @param integer $uniqueCounter
  * @param RenderingContextInterface $renderingContext
  * @param string $viewHelperName
  * @return AbstractViewHelper
  * @Flow\Internal
  */
 public function getViewHelper($uniqueCounter, RenderingContextInterface $renderingContext, $viewHelperName)
 {
     if (Bootstrap::$staticObjectManager->getScope($viewHelperName) === Configuration::SCOPE_SINGLETON) {
         // if ViewHelper is Singleton, do NOT instantiate with NEW, but re-use it.
         $viewHelper = Bootstrap::$staticObjectManager->get($viewHelperName);
         $viewHelper->resetState();
         return $viewHelper;
     }
     if (isset($this->viewHelpersByPositionAndContext[$uniqueCounter])) {
         /** @var $viewHelpers \SplObjectStorage */
         $viewHelpers = $this->viewHelpersByPositionAndContext[$uniqueCounter];
         if ($viewHelpers->contains($renderingContext)) {
             $viewHelper = $viewHelpers->offsetGet($renderingContext);
             $viewHelper->resetState();
             return $viewHelper;
         } else {
             $viewHelperInstance = new $viewHelperName();
             $viewHelpers->attach($renderingContext, $viewHelperInstance);
             return $viewHelperInstance;
         }
     } else {
         $viewHelperInstance = new $viewHelperName();
         $viewHelpers = new \SplObjectStorage();
         $viewHelpers->attach($renderingContext, $viewHelperInstance);
         $this->viewHelpersByPositionAndContext[$uniqueCounter] = $viewHelpers;
         return $viewHelperInstance;
     }
 }
Example #6
0
 protected function getBlockId(Block $block)
 {
     if (!$this->blocks->contains($block)) {
         $this->blocks[$block] = count($this->blocks) + 1;
     }
     return $this->blocks[$block];
 }
 public function isVisiting($object)
 {
     if (!is_object($object)) {
         return false;
     }
     return $this->visitingSet->contains($object);
 }
 function it_should_process_the_tiebreaker_round_and_return_the_loser()
 {
     // less
     $answer1 = json_decode('{"answer":0.019,"token":"token-goes-here"}');
     $answer2 = json_decode('{"answer":0.020,"token":"token-goes-here"}');
     // more
     $answer3 = json_decode('{"answer":0.021,"token":"token-goes-here"}');
     $answer4 = json_decode('{"answer":0.020,"token":"token-goes-here"}');
     // equal
     $answer5 = json_decode('{"answer":0.020,"token":"token-goes-here"}');
     $answer6 = json_decode('{"answer":0.020,"token":"token-goes-here"}');
     // create Dummy objects
     $clients = new \SplObjectStorage();
     $conn1 = new \StdClass();
     $conn2 = new \StdClass();
     // less - answer1 wins
     $clients->attach($conn1, $answer1);
     $clients->attach($conn2, $answer2);
     $this->processTiebreaker($clients)->shouldReturn($conn2);
     // more - answer2 wins
     $clients->attach($conn1, $answer3);
     $clients->attach($conn2, $answer4);
     $this->processTiebreaker($clients)->shouldReturn($conn1);
     // equal - answer1 wins ( I know its cheating a little )
     $clients->attach($conn1, $answer5);
     $clients->attach($conn2, $answer6);
     $this->processTiebreaker($clients)->shouldReturn($conn2);
 }
Example #9
0
 public function get()
 {
     $storage = new \SplObjectStorage();
     $storage->attach($this->exampleA);
     $storage->attach($this->exampleB);
     return $storage;
 }
 /**
  * Converts string dependencies to an object storage of dependencies
  *
  * @param string $dependencies
  * @return \SplObjectStorage
  */
 public function convertDependenciesToObjects($dependencies)
 {
     $dependenciesObject = new \SplObjectStorage();
     $unserializedDependencies = unserialize($dependencies);
     if (!is_array($unserializedDependencies)) {
         return $dependenciesObject;
     }
     foreach ($unserializedDependencies as $dependencyType => $dependencyValues) {
         // Dependencies might be given as empty string, e.g. conflicts => ''
         if (!is_array($dependencyValues)) {
             continue;
         }
         foreach ($dependencyValues as $dependency => $versions) {
             if ($dependencyType && $dependency) {
                 $versionNumbers = \TYPO3\CMS\Core\Utility\VersionNumberUtility::convertVersionsStringToVersionNumbers($versions);
                 $lowest = $versionNumbers[0];
                 if (count($versionNumbers) === 2) {
                     $highest = $versionNumbers[1];
                 } else {
                     $highest = '';
                 }
                 /** @var $dependencyObject \TYPO3\CMS\Extensionmanager\Domain\Model\Dependency */
                 $dependencyObject = $this->objectManager->get(\TYPO3\CMS\Extensionmanager\Domain\Model\Dependency::class);
                 $dependencyObject->setType($dependencyType);
                 $dependencyObject->setIdentifier($dependency);
                 $dependencyObject->setLowestVersion($lowest);
                 $dependencyObject->setHighestVersion($highest);
                 $dependenciesObject->attach($dependencyObject);
                 unset($dependencyObject);
             }
         }
     }
     return $dependenciesObject;
 }
 /**
  * @param ConnectionInterface $connection
  */
 public function remove(ConnectionInterface $connection)
 {
     Debug::line(__CLASS__ . ': Remove [');
     $this->storage->detach($connection);
     Debug::line('-- WebSocket connection removed');
     Debug::line(']');
 }
Example #12
0
 public function __construct(array $users = array())
 {
     $this->users = new SplObjectStorage();
     foreach ($users as $user) {
         $this->users->attach(new User(new UserId($user['id']), new Name($user['name']), new EmailAddress($user['email'])));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function analyse(OccurrencesInterface $occurences)
 {
     $storage = new \SplObjectStorage();
     /** @var OccurrenceInterface $occurence */
     foreach ($occurences->getFirstOccurrences() as $occurence) {
         $rule = $occurence->getRule();
         $expectedCount = count($rule->getConditions());
         $counter = 1;
         $current = $occurence;
         $previous = null;
         $this->dynamicCapabilitiesProcessor->process($current);
         while ($next = $occurences->getNext($current)) {
             $previous = $current;
             $current = $next;
             if ($this->incrementation->oughtToBeIncrement($current, $previous)) {
                 $counter++;
                 $this->dynamicCapabilitiesProcessor->process($current);
             }
         }
         if ($counter === $expectedCount && !$storage->contains($rule)) {
             $storage->attach($rule);
         }
     }
     return $storage;
 }
Example #14
0
 /**
  * Removes the given comparison
  *
  * @param PropertyComparisonInterface $comparison
  * @throws Exception\InvalidComparisonException if the given comparison is not in the list
  * @return $this
  */
 public function removeComparison($comparison)
 {
     if (!$this->comparisons->contains($comparison)) {
         throw new InvalidComparisonException('Can not remove given comparison because it is not in the list', 1409600320);
     }
     $this->comparisons->detach($comparison);
 }
 public function isVisiting($object)
 {
     if (!is_object($object)) {
         throw new LogicException('Expected object but got ' . gettype($object) . '. Do you have the wrong @Type mapping or could this be a Doctrine many-to-many relation?');
     }
     return $this->visitingSet->contains($object);
 }
 /**
  * When collecting gift card totals, each gift card to be redeemed should have
  * the amount expected to be redeemed set as the amount to redeem, the order
  * address grand total should be decremented by the amount being redeemed from
  * all gift cards and data should be set on the order address indicating the
  * total amount expected to be redeemed from gift cards.
  * @param float $addressTotal Grand total of the order before gift cards
  * @param array $giftCardAmounts Expected gift card amounts by card number - balance and redeem amount
  * @param float $remainingTotal Expected address total after applying gift cards
  * @param float $redeemTotal Expected gift card amount to redeem
  * @dataProvider dataProvider
  */
 public function testCollect($addressTotal, $giftCardAmounts, $remainingTotal, $redeemTotal)
 {
     // float cast on yaml provided value to ensure it is actually a float
     $addressTotal = (double) $addressTotal;
     $remainingTotal = (double) $remainingTotal;
     $redeemTotal = (double) $redeemTotal;
     // set of gift cards that have been applied to the order and not redeemed
     $giftCards = new SplObjectStorage();
     foreach ($giftCardAmounts as $cardNumber => $amts) {
         $gc = Mage::getModel('ebayenterprise_giftcard/giftcard')->setCardNumber($cardNumber)->setBalanceAmount((double) $amts['balance'])->setIsRedeemed(false);
         $giftCards->attach($gc);
     }
     $container = $this->getModelMock('ebayenterprise_giftcard/container', ['getUnredeemedGiftCards']);
     $container->method('getUnredeemedGiftCards')->willReturn($giftCards);
     $address = Mage::getModel('sales/quote_address', array('base_grand_total' => $addressTotal, 'grand_total' => $addressTotal));
     $totalCollector = Mage::getModel('ebayenterprise_giftcard/total_quote', array('gift_card_container' => $container));
     $totalCollector->collect($address);
     // float casts on yaml provided values to ensure they are actually floats
     $this->assertSame($remainingTotal, $address->getGrandTotal());
     $this->assertSame($redeemTotal, $address->getEbayEnterpriseGiftCardBaseAppliedAmount());
     foreach ($giftCards as $card) {
         // float cast on yaml provided value to ensure it is actually a float
         $this->assertSame((double) $giftCardAmounts[$card->getCardNumber()]['redeem'], $card->getAmountToRedeem());
     }
 }
Example #17
0
 /**
  * 移除观察者
  * @param \SplObserver $observer
  */
 public function detach(\SplObserver $observer)
 {
     if ($this->_observers == null) {
         return;
     }
     $this->_observers->detach($observer);
 }
 /**
  * Handle process on close transport
  *
  * @param \React\Socket\Connection $conn
  */
 public function handleClose(Connection $conn)
 {
     Logger::debug($this, "Raw socket closed " . $conn->getRemoteAddress());
     $session = $this->sessions[$conn];
     $this->sessions->detach($conn);
     $this->router->getEventDispatcher()->dispatch('connection_close', new ConnectionCloseEvent($session));
 }
Example #19
0
public function createBatches(\SplQueue $queue)
{

 $groups = new \SplObjectStorage();
foreach ($queue as $item) {
if (!$item instanceof RequestInterface) {
throw new InvalidArgumentException('All items must implement Guzzle\Http\Message\RequestInterface');
}
$client = $item->getClient();
if (!$groups->contains($client)) {
$groups->attach($client, array($item));
} else {
$current = $groups[$client];
$current[] = $item;
$groups[$client] = $current;
}
}

$batches = array();
foreach ($groups as $batch) {
$batches = array_merge($batches, array_chunk($groups[$batch], $this->batchSize));
}

return $batches;
}
Example #20
0
 public function valuesProvider()
 {
     $obj2 = new \stdClass();
     $obj2->foo = 'bar';
     $obj3 = (object) array(1, 2, "Test\r\n", 4, 5, 6, 7, 8);
     $obj = new \stdClass();
     // @codingStandardsIgnoreStart
     $obj->null = null;
     // @codingStandardsIgnoreEnd
     $obj->boolean = true;
     $obj->integer = 1;
     $obj->double = 1.2;
     $obj->string = '1';
     $obj->text = "this\nis\na\nvery\nvery\nvery\nvery\nvery\nvery\rlong\n\rtext";
     $obj->object = $obj2;
     $obj->objectagain = $obj2;
     $obj->array = array('foo' => 'bar');
     $obj->array2 = array(1, 2, 3, 4, 5, 6);
     $obj->array3 = array($obj, $obj2, $obj3);
     $obj->self = $obj;
     $storage = new \SplObjectStorage();
     $storage->attach($obj2);
     $storage->foo = $obj2;
     return array(array($obj, spl_object_hash($obj)), array($obj2, spl_object_hash($obj2)), array($obj3, spl_object_hash($obj3)), array($storage, spl_object_hash($storage)), array($obj->array, 0), array($obj->array2, 0), array($obj->array3, 0));
 }
 public function invalidate(AbstractTerritoire $territoire)
 {
     $timestamp = $this->em->getRepository('AppBundle\\Repository\\CacheInfo\\TerritoireTimestamp')->findOneByTerritoire($territoire);
     if (!$timestamp && $this->toPersist->offsetExists($territoire)) {
         $timestamp = $this->toPersist[$territoire];
     }
     if ($timestamp) {
         $timestamp->setNow();
     }
     if (!$timestamp) {
         $timestamp = new TerritoireTimestamp($territoire);
         $this->em->persist($timestamp);
         $this->toPersist[$territoire] = $timestamp;
     }
     if ($territoire instanceof Commune) {
         $this->invalidate($territoire->getDepartement());
         return;
     }
     if ($territoire instanceof Departement) {
         $this->invalidate($territoire->getRegion());
         return;
     }
     if ($territoire instanceof Region && $territoire->getCirconscriptionEuropeenne()) {
         $this->invalidate($territoire->getCirconscriptionEuropeenne());
     }
     if ($territoire instanceof Region || $territoire instanceof CirconscriptionEuropeenne) {
         $this->invalidate($territoire->getPays());
     }
 }
 public function startWorkers($workerCount, OutputInterface $output)
 {
     $output->writeln('Workers Manager is about to start ' . $workerCount . ' workers');
     /* @var \Symfony\Component\Process\Process[] $workers */
     $workers = new \SplObjectStorage();
     for ($i = 1; $i <= $workerCount; ++$i) {
         $output->writeln('Starting worker nr: ' . $i . ' - ' . $this->workerExecCommand);
         $worker = new Process($this->workerExecCommand);
         // $worker->disableOutput();
         $workers->attach($worker);
         $worker->start();
         if ($worker->isRunning()) {
             $output->writeln('Worker started [PID = ' . $worker->getPid() . ']');
         } else {
             $output->writeln('<error>Worker start failure. ' . $worker->getErrorOutput() . '</error>');
         }
     }
     while (count($workers) > 0) {
         $output->writeln('Managing ' . count($workers) . ' worker(s) on ' . date('Y-m-d H:i:s'));
         $workersToRemove = [];
         foreach ($workers as $worker) {
             if (!$worker->isRunning()) {
                 $output->writeln('<info>Found non running worker.</info>');
                 $workersToRemove[] = $worker;
             }
         }
         foreach ($workersToRemove as $worker) {
             $workers->detach($worker);
         }
         sleep(1);
     }
     $output->writeln('Workers Manager exits.');
 }
Example #23
0
 /**
  *
  * @param TransitionInterface $transition
  */
 public function addTransition(TransitionInterface $transition)
 {
     $this->transitions->attach($transition);
     $eventName = $transition->getEventName();
     if ($eventName) {
         $this->getEvent($eventName);
     }
 }
 /**
  * Runs the close() method of a backend and removes the backend
  * from the logger.
  *
  * @param Backend\BackendInterface $backend The backend to remove
  * @return void
  * @throws NoSuchBackendException if the given backend is unknown to this logger
  * @api
  */
 public function removeBackend(Backend\BackendInterface $backend)
 {
     if (!$this->backends->contains($backend)) {
         throw new NoSuchBackendException('Backend is unknown to this logger.', 1229430381);
     }
     $backend->close();
     $this->backends->detach($backend);
 }
Example #25
0
 /**
  * @return ConnectionFactory[]
  */
 private function getConnections()
 {
     $connections = new \SplObjectStorage();
     foreach ($this->repositoryMap as $mapper) {
         $connections->attach($mapper->getConnectionFactory());
     }
     return $connections;
 }
 /**
  * Adds scope to default scopes
  *
  * @param IScope $scope
  */
 public function addDefaultScope(IScope $scope)
 {
     if (!$this->defaultScopes->contains($scope)) {
         $this->defaultScopes->attach($scope);
     } else {
         throw new \InvalidArgumentException("Scope '{$scope->getId()}' is already registered as default scope.");
     }
 }
 /**
  * verify
  * - no payments will be processed if all are in the
  *   processed list
  */
 public function testAddPaymentsToPayloadAlreadyProcessed()
 {
     $processedPayments = new SplObjectStorage();
     $processedPayments->attach($this->_paymentStubs[0]);
     $this->_payloadStub->expects($this->never())->method('setAmount');
     $handler = Mage::getModel('ebayenterprise_paypal/order_create_payment');
     $handler->addPaymentsToPayload($this->_orderStub, $this->_paymentContainer, $processedPayments);
 }
Example #28
0
  /**
   * {@inheritdoc}
   */
  public function getLocale() {
    $request = $this->requestStack->getCurrentRequest();
    if (!$this->locales->contains($request)) {
      $this->locales[$request] = $this->chainResolver->resolve();
    }

    return $this->locales[$request];
  }
Example #29
0
 /**
  * Adds the specific strategy of error handling.
  *
  * @param \Es\Error\Strategy\AbstractErrorStrategy $strategy The strategy
  */
 public function attachErrorStrategy(AbstractErrorStrategy $strategy)
 {
     if ($strategy instanceof HtmlErrorStrategy) {
         $this->setDefaultErrorStrategy($strategy);
         return;
     }
     $this->strategies->attach($strategy);
 }
Example #30
0
 public function spl_object_storage_can_be_used_like_a_set()
 {
     $spl_storage = new SplObjectStorage();
     $an_object = new ClassWithProperties();
     $spl_storage->attach($an_object);
     $spl_storage->attach($an_object);
     assert_that(count($spl_storage))->is_identical_to(__);
 }