Passed
Push — doc_updates ( ba208a...464c24 )
by Fabio
08:10
created

TStreamNotificationCallback::__invoke()   C

Complexity

Conditions 17
Paths 78

Size

Total Lines 73
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 58
c 1
b 0
f 0
nc 78
nop 6
dl 0
loc 73
rs 5.2166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * TStreamNotificationCallback class file
4
 *
5
 * @author Brad Anderson <[email protected]>
6
 * @link https://github.com/pradosoft/prado
7
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
8
 */
9
10
namespace Prado\IO;
11
12
use Prado\Collections\TWeakCallableCollection;
13
use Prado\Prado;
14
15
/**
16
 * TStreamNotificationCallback class.
17
 *
18
 * This class is used to listen into the connections of fopen(), file_get_contents(),
19
 * and file_put_contents() by patching into context 'notification' parameter
20
 * callback.
21
 *
22
 * This class is an invokable callback that is notified as the connection unfolds.
23
 * Of particular use is listening to the progress of data transfer with {@see TStreamNotificationCallback::onProgress()}
24
 * The {@see TStreamNotificationCallback::filterStreamContext()}
25
 * method can accept a TStreamNotificationCallback or an array of options that includes
26
 * "notification".  The array of options are the options for stream_context_create
27
 * and can include events as keys and event handlers (or an array of Event Handlers)
28
 * to patch into the "notification" callback.  Within the array of options, "notification"
29
 * can be a TStreamNotificationCallback or an array of events as keys and event
30
 * handlers as values.
31
 *
32
 * The following event handlers are available to listen to the file connection and
33
 * transfer:
34
 *   - onResolve: Raised when the Notification Code is STREAM_NOTIFY_RESOLVE.
35
 *   - onConnected: Raised when the Notification Code is STREAM_NOTIFY_CONNECT.
36
 *   - onAuthRequired: Raised when the Notification Code is STREAM_NOTIFY_AUTH_REQUIRED.
37
 *   - onAuthResult: Raised when the Notification Code is STREAM_NOTIFY_AUTH_RESULT.
38
 *   - onRedirected: Raised when the Notification Code is STREAM_NOTIFY_REDIRECTED.
39
 *   - onMimeType: Raised when the Notification Code is STREAM_NOTIFY_MIME_TYPE_IS.
40
 *       This parses the $message Mime Type and Charset and is retrievable with
41
 *       {@see TStreamNotificationCallback::getMimeType()} and {@see TStreamNotificationCallback::getCharset()}.
42
 *   - onFileSize: Raised when the Notification Code is STREAM_NOTIFY_FILE_SIZE_IS.
43
 *       This stores the file size and is retrievable with {@see TStreamNotificationCallback::getFileSize()}.
44
 *   - onProgress: Raised when the Notification Code is STREAM_NOTIFY_PROGRESS.
45
 *       This stores the bytes Transferred and is retrievable with {@see TStreamNotificationCallback::getBytesTransferred()}.
46
 *   - onCompleted: Raised when the Notification Code is STREAM_NOTIFY_COMPLETED.
47
 *		 This sets the {@see TStreamNotificationCallback::getIsCompleted()} to true (from false).
48
 *   - onFailure: Raised when the Notification Code is STREAM_NOTIFY_FAILURE.
49
 *		 This sets the {@see TStreamNotificationCallback::getIsFailure()} to true (from
50
 *       false) and stores the Message Code for retrieval with {@see TStreamNotificationCallback::getMessageCode()}.
51
 *
52
 * These events pass the {@see TStreamNotificationParameter} as the parameter. It
53
 * contains the arguments of the Stream Notification Callback and is reused in each
54
 * notification.
55
 *
56
 * @author Brad Anderson <[email protected]>
57
 * @since 4.2.3
58
 */
59
class TStreamNotificationCallback extends \Prado\TComponent
60
{
61
	public const NOTIFICATION = 'notification';
62
63
	/** @var ?TWeakCallableCollection The registered direct callbacks. */
64
	private ?TWeakCallableCollection $_callbacks = null;
65
66
	/** @var ?int The severity of the failure. */
67
	private ?int $_severity = null;
68
69
	/** @var ?string The message of the notification. */
70
	private ?string $_message = null;
71
72
	/** @var ?int The message code of the failure. */
73
	private ?int $_messageCode = null;
74
75
	/** @var ?int The bytes transferred. */
76
	private ?int $_bytesTrasferred = null;
77
78
	/** @var ?int The total bytes of the file. */
79
	private ?int $_fileSize = null;
80
81
	/** @var ?string The mime type of the file. */
82
	private ?string $_mimeType = null;
83
84
	/** @var ?string The charset in the mime type of the file. */
85
	private ?string $_charset = null;
86
87
	/** @var bool Was the completed notification code sent. */
88
	private bool $_completed = false;
89
90
	/** @var bool Was the failure notification code sent. */
91
	private bool $_failure = false;
92
93
	/**
94
	 * @var ?TStreamNotificationParameter The Parameter with the callback arguments
95
	 *   for the events.
96
	 */
97
	private ?TStreamNotificationParameter $_parameter = null;
98
99
	/**
100
	 * This converts the input TStreamNotificationCallback or array into a proper stream
101
	 * context with options and parameters (notification).  If $context is an array
102
	 * this can use or convert the "notification" into a stream context parameter.
103
	 * When "notifications" are an array, the keys are events for the TStreamNotificationCallback
104
	 * and values could be a single event handler callback or an array of event handler
105
	 * callbacks.
106
	 * ```php
107
	 *   $callback = new TStreamNotificationCallback();
108
	 *   $callback->onConnected[] = function($sender, $param) {...};
109
	 *   $context = TStreamNotificationCallback::filterStreamContext($callback);
110
	 *   $context = TStreamNotificationCallback::filterStreamContext(['notification' => $callback,
111
	 * 				'onProgress' => [$this, 'progressHandler'], 'onFileSize' =>
112
	 *					[new TEventHandler([$this, 'fileSizeHandler'], $someData), ...]);
113
	 *   // if you don't need the TStreamNotificationCallback, but get the callback as the event handler $sender
114
	 *   $context = TStreamNotificationCallback::filterStreamContext(['notification' => [
115
	 * 				'onProgress' => [$this, 'progressHandler'], 'onFileSize' =>
116
	 *					[new TEventHandler([$this, 'fileSizeHandler'], $someData), ...],
117
	 * 				'http' => [...], ...]);
118
	 *   $context = TStreamNotificationCallback::filterStreamContext([
119
	 * 				'onProgress' => [$this, 'progressHandler'], 'onFileSize' =>
120
	 *					[new TEventHandler([$this, 'fileSizeHandler'], $someData), ...],
121
	 * 				'http' => [...], 'onMimeType' => function($sender, $param) {...},
122
	 *				'onFileSize' => [$behavior, 'otherHandler']]);
123
	 *	$stream = fopen($url, 'rb', false, $context);
124
	 * ```
125
	 *
126
	 * If Event Handlers for TStreamNotificationCallback are in the array, and the
127
	 * TStreamNotificationCallback notification is not instanced, it will be created.
128
	 * If the "notification" is a callable that is not a TStreamNotificationCallback
129
	 * then the "notification" callable is wrapped in a TStreamNotificationCallback.
130
	 * @param mixed $context A Stream Context, TStreamNotificationCallback, or array
131
	 *   of options with notification.
132
	 * @return mixed The Streaming Context.
133
	 */
134
	public static function filterStreamContext(mixed $context): mixed
135
	{
136
		if (is_callable($context)) {
137
			$context = stream_context_create(null, [self::NOTIFICATION => $context]);
138
		} elseif (is_array($context)) {
139
			$notification = array_key_exists(self::NOTIFICATION, $context) ? $context[self::NOTIFICATION] : null;
140
			unset($context[self::NOTIFICATION]);
141
			if (is_array($notification)) {
142
				$notification['class'] ??= TStreamNotificationCallback::class;
143
				$notification = Prado::createComponent($notification);
144
			}
145
			$contextKeys = $context;
146
			$contextKeys = array_change_key_case($contextKeys);
147
			$contextEvents = array_intersect_key($contextKeys, ['onresolve' => true, 'onauthrequired' => true, 'onfailure' => true, 'onauthresult' => true, 'onredirect' => true, 'onconnected' => true, 'onfilesize' => true, 'onmimetype' => true, 'onprogress' => true, 'oncompleted' => true]);
148
			if (!empty($contextEvents)) {
149
				if (empty($notification)) {
150
					$notification = new TStreamNotificationCallback();
151
				} elseif (!($notification instanceof TStreamNotificationCallback)) {
152
					$notification = new TStreamNotificationCallback($notification);
153
				}
154
			}
155
			if ($notification instanceof TStreamNotificationCallback) {
156
				foreach($context as $property => $value) {
157
					if (property_exists($notification, $property) || $notification->canSetProperty($property) || $notification->hasEvent($property)) {
158
						$notification->setSubProperty($property, $value);
159
						unset($context[$property]);
160
					}
161
				}
162
			}
163
			$param = null;
164
			if($notification) {
165
				$param = [self::NOTIFICATION => $notification];
166
			}
167
			if (empty($context)) {
168
				$context = null;
169
			}
170
			$context = stream_context_create($context, $param);
171
		}
172
		return $context;
173
	}
174
175
	/**
176
	 * Given a Stream Context, this returns that stream context "notification" callback.
177
	 * In this context, it is likely a TStreamNotificationCallback.
178
	 * @param mixed $context The Stream Context to retrieve the "notification" callback from.
179
	 * @return mixed The "notification" callback or null if nothing.
180
	 */
181
	public static function getContextNotificationCallback(mixed $context): mixed
182
	{
183
		$params = stream_context_get_params($context);
184
185
		return $params[self::NOTIFICATION] ?? null;
186
	}
187
188
	/**
189
	 * The registers the callbacks.
190
	 * @param array $args Callable or null
191
	 */
192
	public function __construct(...$args)
193
	{
194
		if (count($args)) {
195
			$callbacks = $this->getCallbacks();
196
			$callbacks->mergeWith($args);
197
		}
198
		parent::__construct();
199
	}
200
201
	/**
202
	 * This holds any direct notification callbacks so multiple callbacks are supported.
203
	 * @return TWeakCallableCollection The direct notification callbacks.
204
	 */
205
	public function getCallbacks(): TWeakCallableCollection
206
	{
207
		if (!$this->_callbacks) {
208
			$this->_callbacks = new TWeakCallableCollection();
209
		}
210
		return $this->_callbacks;
211
	}
212
213
	/**
214
	 * @return ?int The severity of the failure.
215
	 */
216
	public function getSeverity(): ?int
217
	{
218
		return $this->_severity;
219
	}
220
221
	/**
222
	 * @return ?string The Message from the notification.
223
	 */
224
	public function getMessage(): ?string
225
	{
226
		return $this->_message;
227
	}
228
229
	/**
230
	 * @return ?int The Message Code from the failure.
231
	 */
232
	public function getMessageCode(): ?int
233
	{
234
		return $this->_messageCode;
235
	}
236
237
	/**
238
	 * @return ?int The total bytes transferred of the streaming file.
239
	 */
240
	public function getBytesTransferred(): ?int
241
	{
242
		return $this->_bytesTrasferred;
243
	}
244
245
	/**
246
	 * @return ?int The File Size of the streaming file.
247
	 */
248
	public function getFileSize(): ?int
249
	{
250
		return $this->_fileSize;
251
	}
252
253
	/**
254
	 * @return ?string The MimeType of the file.
255
	 */
256
	public function getMimeType(): ?string
257
	{
258
		return $this->_mimeType;
259
	}
260
261
	/**
262
	 * @return ?string The charset of the MimeType.
263
	 */
264
	public function getCharset(): ?string
265
	{
266
		return $this->_charset;
267
	}
268
269
	/**
270
	 * @return bool Was the Notification Code STREAM_NOTIFY_COMPLETED raised.
271
	 */
272
	public function getIsCompleted(): bool
273
	{
274
		return $this->_completed;
275
	}
276
277
	/**
278
	 * @return bool Was the Notification Code STREAM_NOTIFY_FAILURE at any point.
279
	 */
280
	public function getIsFailure(): bool
281
	{
282
		return $this->_failure;
283
	}
284
285
	/**
286
	 * @return ?TStreamNotificationParameter The event parameter object.
287
	 */
288
	public function getParameter(): ?TStreamNotificationParameter
289
	{
290
		return $this->_parameter;
291
	}
292
293
	/**
294
	 * The callback for stream notifications.
295
	 * @param int $notification_code One of the STREAM_NOTIFY_* notification constants.
296
	 * @param int $severity One of the STREAM_NOTIFY_SEVERITY_* notification constants.
297
	 * @param ?string $message Passed if a descriptive message is available for the event.
298
	 * @param int $message_code Passed if a descriptive message code is available for the event.
299
	 * @param int $bytes_transferred If applicable, the bytes_transferred will be populated.
300
	 * @param int $bytes_max If applicable, the bytes_max will be populated.
301
	 */
302
	public function __invoke(int $notification_code, int $severity, ?string $message, int $message_code, int $bytes_transferred, int $bytes_max): void
303
	{
304
		$this->_message = $message;
305
		if (!$this->_parameter) {
306
			$this->_parameter = new TStreamNotificationParameter($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max);
307
		} else {
308
			$this->_parameter->setNotificationCode($notification_code);
309
			$this->_parameter->setSeverity($severity);
310
			$this->_parameter->setMessage($message);
311
			$this->_parameter->setMessageCode($message_code);
312
			$this->_parameter->setBytesTransferred($bytes_transferred);
313
			$this->_parameter->setBytesMax($bytes_max);
314
		}
315
		switch($notification_code) {
316
			case STREAM_NOTIFY_RESOLVE: // value: 1
317
				$this->onResolve($this->_parameter);
318
				break;
319
320
			case STREAM_NOTIFY_CONNECT: // value: 2
321
				$this->onConnected($this->_parameter);
322
				break;
323
324
			case STREAM_NOTIFY_AUTH_REQUIRED: // value: 3
325
				$this->onAuthRequired($this->_parameter);
326
				break;
327
328
			case STREAM_NOTIFY_AUTH_RESULT: // value: 10
329
				$this->onAuthResult($this->_parameter);
330
				break;
331
332
			case STREAM_NOTIFY_REDIRECTED: // value: 6
333
				$this->onRedirected($this->_parameter);
334
				break;
335
336
			case STREAM_NOTIFY_MIME_TYPE_IS: // value: 4
337
				if (strpos($message, ';') !== false) {
0 ignored issues
show
Bug introduced by
It seems like $message can also be of type null; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

337
				if (strpos(/** @scrutinizer ignore-type */ $message, ';') !== false) {
Loading history...
338
					$mimeData = explode(';', $message, 2);
0 ignored issues
show
Bug introduced by
It seems like $message can also be of type null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

338
					$mimeData = explode(';', /** @scrutinizer ignore-type */ $message, 2);
Loading history...
339
					$message = $mimeData[0];
340
					if (strpos($mimeData[1] ?? '', '=') !== false) {
341
						$this->_charset = explode('=', $mimeData[1])[1];
342
					}
343
				}
344
				$this->_mimeType = $message;
345
				$this->onMimeType($this->_parameter);
346
				break;
347
348
			case STREAM_NOTIFY_FILE_SIZE_IS: // value: 5
349
				$this->_bytesTrasferred = $bytes_transferred;
350
				$this->_fileSize = $bytes_max;
351
				$this->onFileSize($this->_parameter);
352
				break;
353
354
			case STREAM_NOTIFY_PROGRESS: // value: 7
355
				$this->_bytesTrasferred = $bytes_transferred;
356
				$this->_fileSize = $bytes_max;
357
				$this->onProgress($this->_parameter);
358
				break;
359
360
			case STREAM_NOTIFY_COMPLETED: // value: 8
361
				$this->_completed = true;
362
				$this->onCompleted($this->_parameter);
363
				break;
364
365
			case STREAM_NOTIFY_FAILURE: // value: 9
366
				$this->_failure = true;
367
				$this->_severity = $severity;
368
				$this->_messageCode = $message_code;
369
				$this->onFailure($this->_parameter);
370
				break;
371
		}
372
		if ($this->_callbacks && $this->_callbacks->getCount()) {
373
			foreach($this->_callbacks as $callback) {
374
				$callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max);
375
			}
376
		}
377
	}
378
379
	/**
380
	 * Raised when the Notification Code is STREAM_NOTIFY_RESOLVE.
381
	 * @param ?TStreamNotificationParameter $param
382
	 */
383
	public function onResolve(?TStreamNotificationParameter $param): array
384
	{
385
		return $this->raiseEvent('onResolve', $this, $param);
386
	}
387
388
	/**
389
	 * Raised when the Notification Code is STREAM_NOTIFY_CONNECT.
390
	 * @param ?TStreamNotificationParameter $param
391
	 */
392
	public function onConnected(?TStreamNotificationParameter $param): array
393
	{
394
		return $this->raiseEvent('onConnected', $this, $param);
395
	}
396
397
	/**
398
	 * Raised when the Notification Code is STREAM_NOTIFY_AUTH_REQUIRED.
399
	 * @param ?TStreamNotificationParameter $param
400
	 */
401
	public function onAuthRequired(?TStreamNotificationParameter $param): array
402
	{
403
		return $this->raiseEvent('onAuthRequired', $this, $param);
404
	}
405
406
	/**
407
	 * Raised when the Notification Code is STREAM_NOTIFY_AUTH_RESULT.
408
	 * @param ?TStreamNotificationParameter $param
409
	 */
410
	public function onAuthResult(?TStreamNotificationParameter $param): array
411
	{
412
		return $this->raiseEvent('onAuthResult', $this, $param);
413
	}
414
415
	/**
416
	 * Raised when the Notification Code is STREAM_NOTIFY_REDIRECTED.
417
	 * @param ?TStreamNotificationParameter $param
418
	 */
419
	public function onRedirected(?TStreamNotificationParameter $param): array
420
	{
421
		return $this->raiseEvent('onRedirected', $this, $param);
422
	}
423
424
	/**
425
	 * Raised when the Notification Code is STREAM_NOTIFY_MIME_TYPE_IS.
426
	 * @param ?TStreamNotificationParameter $param
427
	 */
428
	public function onMimeType(?TStreamNotificationParameter $param): array
429
	{
430
		return $this->raiseEvent('onMimeType', $this, $param);
431
	}
432
433
	/**
434
	 * Raised when the Notification Code is STREAM_NOTIFY_FILE_SIZE_IS.
435
	 * @param ?TStreamNotificationParameter $param
436
	 */
437
	public function onFileSize(?TStreamNotificationParameter $param): array
438
	{
439
		return $this->raiseEvent('onFileSize', $this, $param);
440
	}
441
442
	/**
443
	 * Raised when the Notification Code is STREAM_NOTIFY_PROGRESS.
444
	 * @param ?TStreamNotificationParameter $param
445
	 */
446
	public function onProgress(?TStreamNotificationParameter $param): array
447
	{
448
		return $this->raiseEvent('onProgress', $this, $param);
449
	}
450
451
	/**
452
	 * Raised when the Notification Code is STREAM_NOTIFY_COMPLETED.
453
	 * @param ?TStreamNotificationParameter $param
454
	 */
455
	public function onCompleted(?TStreamNotificationParameter $param): array
456
	{
457
		return $this->raiseEvent('onCompleted', $this, $param);
458
	}
459
460
	/**
461
	 * Raised when the Notification Code is STREAM_NOTIFY_FAILURE.
462
	 * @param ?TStreamNotificationParameter $param
463
	 */
464
	public function onFailure(?TStreamNotificationParameter $param): array
465
	{
466
		return $this->raiseEvent('onFailure', $this, $param);
467
	}
468
}
469