Completed
Push — master ( e0623f...313c90 )
by Flavio
02:57
created

TaskCoroutine::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
/**
4
 * Work
5
 *
6
 * Cooperative multitasking via coroutines.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @reference http://nikic.github.io/2012/12/22/Cooperative-multitasking-using-coroutines-in-PHP.html
11
 * @copyright Caffeina srl - 2015 - http://caffeina.it
12
 */
13
14
// version_compare(PHP_VERSION, '5.5.0', '>=')
15
//  or trigger_error('Work module need PHP 5.5 or later.',E_USER_ERROR);
16
17
class Work {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
18
  use Module;
19
20
  protected static $pool = null;
21
  protected static $workers;
22
  protected static $lastID = 0;
23
24
  public static function add($id, $job=null){
25
    self::$pool or ( self::$pool = new \SplQueue() );
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
26
    if(is_callable($id) && $job===null){
27
      $job = $id;
28
      $id = ++self::$lastID;
29
    }
30
    $task = new TaskCoroutine($id, $job instanceof \Generator ? $job : $job());
31
    self::$workers[$id] = $task;
32
    self::$pool->enqueue($task);
33
    return $task;
34
  }
35
36
  public static function send($id,$passValue) {
37
     isset(self::$workers[$id]) && self::$workers[$id]->pass($passValue);
38
  }
39
40
  public static function run(){
41
    self::$pool or ( self::$pool = new \SplQueue() );
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
42
    while (!self::$pool->isEmpty()) {
43
      $task = self::$pool->dequeue();
44
      $task->run();
45
      if ($task->complete()) {
46
         unset(self::$workers[$task->id()]);
47
      } else {
48
          self::$pool->enqueue($task);
49
      }
50
    }
51
  }
52
53
  /**
54
   * Defer callback execution after script execution
55
   * @param callable $callback The deferred callback
56
   */
57
  public static function after(callable $callback){
58
    static::$inited_shutdown || static::install_shutdown();
59
    Event::on('core.shutdown', $callback);
60
  }
61
62
  /**
63
   * Single shot defer handeler install
64
   */
65
  protected static function install_shutdown(){
66
    if (static::$inited_shutdown) return;
67
    
68
    // Disable time limit
69
    set_time_limit(0);
70
    
71
    // HHVM support
72
    if(function_exists('register_postsend_function')){
73
      register_postsend_function(function(){
74
        Event::trigger('core.shutdown');
75
      });
76
    } else if(function_exists('fastcgi_finish_request')) {
77
      register_shutdown_function(function(){
78
        fastcgi_finish_request();
79
        Event::trigger('core.shutdown');
80
      });       
81
    } else {
82
      register_shutdown_function(function(){
83
        Event::trigger('core.shutdown');
84
      });
85
    }
86
87
    static::$inited_shutdown = true;
88
  }
89
}
90
91
class TaskCoroutine {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
Coding Style introduced by
The property $inited_shutdown is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
92
93
    protected $id;
94
    protected $coroutine;
95
    protected $passValue = null;
96
    protected $beforeFirstYield = true;
97
    protected static $inited_shutdown = false;
98
99
    public function __construct($id, \Generator $coroutine) {
100
        $this->id = $id;
101
        $this->coroutine = $coroutine;
102
    }
103
104
    public function id() {
105
        return $this->id;
106
    }
107
108
    public function pass($passValue) {
109
        $this->passValue = $passValue;
110
    }
111
112
    public function run() {
113
        if ($this->beforeFirstYield) {
114
            $this->beforeFirstYield = false;
115
            return $this->coroutine->current();
116
        } else {
117
            $retval = $this->coroutine->send($this->passValue);
118
            $this->passValue = null;
119
            return $retval;
120
        }
121
    }
122
123
    public function complete() {
124
        return ! $this->coroutine->valid();
125
    }
126
127
}
128