GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Server   A
last analyzed

Complexity

Total Complexity 34

Size/Duplication

Total Lines 250
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 0
Metric Value
dl 0
loc 250
rs 9.2
c 0
b 0
f 0
wmc 34
lcom 1
cbo 14

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
A shutdown() 0 10 3
A createHttpServer() 0 8 2
B listen() 0 24 6
B treatHttpInput() 0 35 6
B treatProcessInput() 0 22 6
A treatCommand() 0 21 3
A prepareStreamsState() 0 18 2
A addInput() 0 4 1
A addOutput() 0 4 1
A removeInput() 0 4 1
A removeOutput() 0 4 1
A debug() 0 6 1
1
<?php
2
3
namespace Asylamba\Classes\Daemon;
4
5
use Asylamba\Classes\Router\Router;
6
use Asylamba\Classes\Library\Http\RequestFactory;
7
use Asylamba\Classes\Library\Http\ResponseFactory;
8
use Asylamba\Classes\Daemon\ClientManager;
9
10
use Asylamba\Classes\Scheduler\RealTimeActionScheduler;
11
use Asylamba\Classes\Scheduler\CyclicActionScheduler;
12
13
use Asylamba\Classes\Event\ExceptionEvent;
14
use Asylamba\Classes\Event\ErrorEvent;
15
16
use Asylamba\Classes\DependencyInjection\Container;
17
18
use Asylamba\Classes\Exception\ErrorException;
19
20
use Asylamba\Classes\Process\ProcessManager;
21
use Asylamba\Classes\Task\TaskManager;
22
23
class Server
24
{
25
	/** @var Container **/
26
	protected $container;
27
    /** @var Router **/
28
    protected $router;
29
    /** @var RequestFactory **/
30
    protected $requestFactory;
31
    /** @var ResponseFactory **/
32
    protected $responseFactory;
33
    /** @var ClientManager **/
34
    protected $clientManager;
35
	/** @var RealTimeActionScheduler **/
36
	protected $realTimeActionScheduler;
37
	/** @var CyclicActionScheduler **/
38
	protected $cyclicActionScheduler;
39
	/** @var ProcessManager **/
40
	protected $processManager;
41
	/** @var TaskManager **/
42
	protected $taskManager;
43
    /** @var int **/
44
    protected $serverCycleTimeout;
45
    /** @var int **/
46
    protected $port;
47
    /** @var boolean **/
48
    protected $shutdown = false;
49
    /** @var array **/
50
    protected $connections;
51
    /** @var array **/
52
    protected $inputs = [];
53
    /** @var array **/
54
    protected $outputs = [];
55
    /** @var int **/
56
    protected $nbUncollectedCycles = 0;
57
    /** @var int **/
58
    protected $collectionCyclesNumber;
59
60
    /**
61
     * @param Container $container
62
     * @param int $serverCycleTimeout
0 ignored issues
show
Bug introduced by
There is no parameter named $serverCycleTimeout. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
63
     * @param int $port
0 ignored issues
show
Bug introduced by
There is no parameter named $port. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
64
     */
65
    public function __construct(Container $container)
66
    {
67
        $this->container = $container;
68
        $this->router = $container->get('router');
69
        $this->requestFactory = $container->get('request_factory');
70
        $this->responseFactory = $container->get('response_factory');
71
        $this->clientManager = $container->get('client_manager');
72
		$this->realTimeActionScheduler = $container->get('realtime_action_scheduler');
73
		$this->cyclicActionScheduler = $container->get('cyclic_action_scheduler');
74
        $this->serverCycleTimeout = $container->getParameter('server_cycle_timeout');
75
        $this->port = $container->getParameter('server_port');
76
        $this->collectionCyclesNumber = $container->getParameter('server_collection_cycles_number');
77
    }
78
	
79
    public function shutdown()
80
    {
81
        $this->shutdown = true;
82
        foreach($this->inputs as $input) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
83
            fclose($input);
84
        }
85
        foreach($this->outputs as $output) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
86
            fclose($output);
87
        }
88
    }
89
90
    public function createHttpServer()
91
    {
92
        $stream = stream_socket_server("tcp://0.0.0.0:{$this->port}", $errno, $errstr);
93
        if (!$stream) {
94
            throw new ErrorException("$errstr ($errno)");
95
        }
96
        $this->inputs['http_server'] = $stream;
97
    }
98
99
    public function listen()
100
    {
101
		$this->processManager = $this->container->get('process_manager');
102
		$this->taskManager = $this->container->get('task_manager');
103
        $inputs = $this->inputs;
104
        $outputs = $this->outputs;
105
        $errors = null;
106
        gc_disable();
107
        while ($this->shutdown === false && ($nbUpgradedStreams = stream_select($inputs, $outputs, $errors, $this->serverCycleTimeout)) !== false) {
108
            if ($nbUpgradedStreams === 0) {
109
                $this->prepareStreamsState($inputs, $outputs, $errors);
110
                continue;
111
            }
112
            foreach ($inputs as $stream) {
113
				$name = array_search($stream, $this->inputs);
114
				if ($name === 'http_server') {
115
					$this->treatHttpInput(stream_socket_accept($stream));
116
				} else {
117
					$this->treatProcessInput($name);
118
				}
119
            }
120
            $this->prepareStreamsState($inputs, $outputs, $errors);
121
        }
122
    }
123
	
124
	protected function treatHttpInput($input)
125
	{
126
		$client = $request = $response = null;
127
		try {
128
			$data = fread($input, 8192);
129
			if (empty($data)) {
130
				fclose($input);
131
				return;
132
			}
133
			$request = $this->requestFactory->createRequestFromInput($data);
0 ignored issues
show
Documentation introduced by
$data is of type string, but the function expects a resource.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
134
			$this->container->set('app.request', $request);
135
			if (($client = $this->clientManager->getClient($request)) === null) {
136
				$client = $this->clientManager->createClient($request);
137
			}
138
			$response = $this->router->processRequest($request);
139
			$this->container->set('app.response', $response);
140
			$this->responseFactory->processResponse($request, $response, $client);
141
		} catch (\Exception $ex) {
142
			$this->container->get('event_dispatcher')->dispatch($event = new ExceptionEvent($request, $ex));
0 ignored issues
show
Bug introduced by
It seems like $request defined by $response = null on line 126 can be null; however, Asylamba\Classes\Event\E...ionEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
143
			$response = $event->getResponse();
144
			$this->responseFactory->processResponse($request, $response, $client);
0 ignored issues
show
Bug introduced by
It seems like $request defined by $response = null on line 126 can be null; however, Asylamba\Classes\Library...tory::processResponse() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Bug introduced by
It seems like $client defined by $request = $response = null on line 126 can be null; however, Asylamba\Classes\Library...tory::processResponse() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
145
		} catch (\Error $err) {
146
			$this->container->get('event_dispatcher')->dispatch($event = new ErrorEvent($request, $err));
0 ignored issues
show
Bug introduced by
It seems like $request defined by $response = null on line 126 can be null; however, Asylamba\Classes\Event\ErrorEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
147
			$response = $event->getResponse();
148
			$this->responseFactory->processResponse($request, $response, $client);
0 ignored issues
show
Bug introduced by
It seems like $request defined by $response = null on line 126 can be null; however, Asylamba\Classes\Library...tory::processResponse() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Bug introduced by
It seems like $client defined by $request = $response = null on line 126 can be null; however, Asylamba\Classes\Library...tory::processResponse() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
149
		} finally {
150
			// @TODO Needs further investigation
151
			if ($response !== null) {
152
				fputs ($input, $response->send());
0 ignored issues
show
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
153
				fclose($input);
154
			}
155
			$this->nbUncollectedCycles++;
156
			$this->container->get('session_wrapper')->clearWrapper();
157
		}
158
	}
159
	
160
	protected function treatProcessInput($name)
161
	{
162
		$process = $this->processManager->getByName($name);
163
		$content = fgets($process->getInput(), 1024);
164
		if ($content === false) {
165
			$this->processManager->removeProcess($name, 'The process failed');
166
			return;
167
		}
168
		if (empty($content)) {
169
			return;
170
		}
171
		$data = json_decode($content, true);
172
		if (isset($data['technical'])) {
173
			$this->processManager->updateTechnicalData($process, $data['technical']);
174
		}
175
		if (isset($data['command'])) {
176
			return $this->treatCommand($data);
177
		}
178
		if (isset($data['task'])) {
179
			return $this->taskManager->validateTask($process, $data);
180
		}
181
	}
182
	
183
	/**
184
	 * @param array $data
185
	 */
186
	public function treatCommand($data)
187
	{
188
		switch ($data['command']) {
189
			case 'schedule':
190
				$this->realTimeActionScheduler->scheduleFromProcess(
191
					$data['data']['manager'],
192
					$data['data']['method'],
193
					$data['data']['object_class'],
194
					$data['data']['object_id'],
195
					$data['data']['date']
196
				);
197
				break;
198
			case 'cancel':
199
				$this->realTimeActionScheduler->cancelFromProcess(
200
					$data['data']['object_class'],
201
					$data['data']['object_id'],
202
					$data['data']['date']
203
				);
204
				break;
205
		}
206
	}
207
    
208
	/**
209
	 * @param array $inputs
210
	 * @param array $outputs
211
	 * @param array $errors
212
	 */
213
    protected function prepareStreamsState(&$inputs, &$outputs, &$errors)
214
    {
215
		$this->container->cleanApplication();
216
		
217
        $inputs = $this->inputs;
218
        $outputs = $this->outputs;
219
        $errors = null;
220
		
221
		$this->realTimeActionScheduler->execute();
222
		$this->cyclicActionScheduler->execute();
223
		
224
        if ($this->nbUncollectedCycles > $this->collectionCyclesNumber) {
225
			$this->container->get('database')->refresh();
226
			$this->clientManager->clear();
227
            gc_collect_cycles();
228
            $this->nbUncollectedCycles = 0;
229
        }
230
    }
231
    
232
	/**
233
	 * @param string $name
234
	 * @param resource $input
235
	 */
236
    public function addInput($name, $input)
237
    {
238
        $this->inputs[$name] = $input;
239
    }
240
    
241
	/**
242
	 * @param string $name
243
	 * @param resource $output
244
	 */
245
    public function addOutput($name, $output)
246
    {
247
        $this->outputs[$name] = $output;
248
    }
249
    
250
	/**
251
	 * @param string $name
252
	 */
253
    public function removeInput($name)
254
    {
255
		unset($this->inputs[$name]);
256
    }
257
    
258
	/**
259
	 * @param string $name
260
	 */
261
    public function removeOutput($name)
262
    {
263
		unset($this->outputs[$name]);
264
    }
265
    
266
    public static function debug($debug)
267
    {
268
        ob_start();
269
        var_dump($debug);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($debug); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
270
        file_put_contents('/srv/logs/php/test.log', PROCESS_NAME . ': ' . ob_get_clean() . "\n\n", FILE_APPEND);
271
    }
272
}