Commits

Thomas Weinert committed c427d94

Added wrapper for the Alert\Reactor event loop

Comments (0)

Files changed (2)

src/Carica/Io/Event/Loop/AlertReactor.php

+<?php
+
+namespace Carica\Io\Event\Loop {
+
+  use Carica\Io as Io;
+  use Alert as Alert;
+
+  class AlertReactor implements Io\Event\Loop {
+
+    /**
+     * @var Alert\Reactor
+     */
+    private $_reactor = NULL;
+
+    public function reactor(Alert\Reactor $loop = NULL) {
+      if (isset($reactor)) {
+        $this->_reactor = $reactor;
+      } elseif (NULL === $this->_reactor) {
+        $this->_reactor = (new Alert\ReactorFactory)->select();;
+      }
+      return $this->_reactor;
+    }
+
+    public function setTimeout(Callable $callback, $milliseconds) {
+      return $this->reactor()->once($callback, $milliseconds / 1000);
+    }
+
+    public function setInterval(Callable $callback, $milliseconds) {
+      return $this->reactor()->repeat($callback, $milliseconds / 1000);
+    }
+
+    public function setStreamReader(Callable $callback, $stream) {
+      return $this->reactor()->onREadable($stream, $callback, TRUE);
+    }
+
+    public function remove($watcherId) {
+      $this->reactor()->cancel($watcherId);
+    }
+
+    public function run(Io\Deferred\Promise $for = NULL) {
+      $reactor = $this->reactor();
+      if (isset($for) &&
+          $for->state() === Io\Deferred::STATE_PENDING) {
+        $for->always(
+          function () use ($reactor) {
+            $reactor->stop();
+          }
+        );
+      }
+      $reactor->run();
+    }
+
+    public function stop() {
+      $this->reactor()->stop();
+    }
+
+    public function count() {
+      return -1;
+    }
+  }
+}

src/Carica/Io/Event/Loop/Factory.php

     const USE_STREAMSELECT = 'streamselect';
     const USE_LIBEVENT = 'libevent';
     const USE_REACT = 'react';
+    const USE_ALERT_REACTOR = 'alert-reactor';
 
     /**
      * @var Event\Loop
       switch (self::getImplementation($priority)) {
       case self::USE_REACT :
         return new React();
+      case self::USE_ALERT_REACTOR :
+        return new AlertReactor();
       case self::USE_LIBEVENT :
         return new Libevent(event_base_new());
       default :
           !in_array(self::$_useImplementation, $priority)) {
         foreach ($priority as $implementation) {
           switch ($implementation) {
+          case self::USE_ALERT_REACTOR :
+            if (interface_exists('\\Alert\\Reactor')) {
+              return self::$_useImplementation = self::USE_ALERT_REACTOR;
+            }
+            break;
           case self::USE_REACT :
             if (interface_exists('\\React\\EventLoop\\LoopInterface')) {
               return self::$_useImplementation = self::USE_REACT;