-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScopedCallback.php
More file actions
100 lines (88 loc) · 2.3 KB
/
ScopedCallback.php
File metadata and controls
100 lines (88 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
declare( strict_types = 1 );
/**
* This file deals with RAII style scoped callbacks.
*
* Copyright (C) 2016 Aaron Schulz <[email protected]>
*
* @license GPL-2.0-or-later
* @file
*/
namespace Wikimedia;
use UnexpectedValueException;
/**
* Make a callback run when a dummy object leaves the scope.
*/
class ScopedCallback {
/** @var callable|null */
protected $callback;
/** @var array */
protected $params;
/**
* @param callable|null $callback
* @param array $params Callback arguments (since 1.0.0, MediaWiki 1.25)
*/
public function __construct( ?callable $callback, array $params = [] ) {
$this->callback = $callback;
$this->params = $params;
}
/**
* Trigger a scoped callback and destroy it.
* This is the same as just setting it to null.
*/
public static function consume( ?ScopedCallback &$sc ) {
$sc = null;
}
/**
* Destroy a scoped callback without triggering it.
*/
public static function cancel( ?ScopedCallback &$sc ) {
if ( $sc ) {
$sc->callback = null;
}
$sc = null;
}
/**
* Make PHP ignore user aborts/disconnects until the returned
* value leaves scope. This returns null and does nothing in CLI mode.
*
* @since 3.0.0
*
* @codeCoverageIgnore CI is only run via CLI, so this will never be exercised.
* Also no benefit testing a function just returns null.
*/
#[\NoDiscard]
public static function newScopedIgnoreUserAbort(): ?ScopedCallback {
// ignore_user_abort previously caused an infinite loop on CLI
// https://bugs.php.net/bug.php?id=47540
if ( PHP_SAPI != 'cli' ) {
// avoid half-finished operations
$old = ignore_user_abort( true );
return new ScopedCallback( static function () use ( $old ) {
ignore_user_abort( (bool)$old );
} );
}
return null;
}
/**
* Trigger the callback when it leaves scope.
*/
public function __destruct() {
if ( $this->callback !== null ) {
( $this->callback )( ...$this->params );
}
}
/**
* Do not allow this class to be serialized
*/
public function __sleep(): never {
throw new UnexpectedValueException( __CLASS__ . ' cannot be serialized' );
}
/**
* Protect the caller against arbitrary code execution
*/
public function __wakeup(): never {
$this->callback = null;
throw new UnexpectedValueException( __CLASS__ . ' cannot be unserialized' );
}
}