3
3
namespace WpOrg \Requests \Tests \Transport \Curl ;
4
4
5
5
use CurlHandle ;
6
+ use WeakReference ;
6
7
use WpOrg \Requests \Exception ;
7
8
use WpOrg \Requests \Hooks ;
8
9
use WpOrg \Requests \Requests ;
@@ -15,7 +16,10 @@ final class CurlTest extends BaseTestCase {
15
16
/**
16
17
* Temporary storage of the cURL handle to assert against.
17
18
*
18
- * @var null|resource|\CurlHandle
19
+ * The handle is stored as a weak reference in order to avoid the test itself
20
+ * becoming the source of the memory leak due to locking the resource.
21
+ *
22
+ * @var null|WeakReference
19
23
*/
20
24
protected $ curl_handle ;
21
25
@@ -34,14 +38,20 @@ protected function getOptions($other = []) {
34
38
35
39
$ this ->curl_handle = null ;
36
40
41
+ // On PHP < 7.2, we lack the capability to store weak references.
42
+ // In this case, we just skip the memory leak testing.
43
+ if (version_compare (PHP_VERSION , '7.2.0 ' ) < 0 ) {
44
+ return $ options ;
45
+ }
46
+
37
47
if (!array_key_exists ('hooks ' , $ options )) {
38
48
$ options ['hooks ' ] = new Hooks ();
39
49
}
40
50
41
51
$ options ['hooks ' ]->register (
42
52
'curl.before_request ' ,
43
53
function ($ handle ) {
44
- $ this ->curl_handle = $ handle ;
54
+ $ this ->curl_handle = WeakReference:: create ( $ handle) ;
45
55
}
46
56
);
47
57
@@ -54,19 +64,19 @@ function ($handle) {
54
64
* This is used for asserting that cURL handles are not leaking memory.
55
65
*/
56
66
protected function assert_post_conditions () {
57
- if ($ this ->curl_handle === null ) {
67
+ if (version_compare ( PHP_VERSION , ' 7.2.0 ' ) < 0 || ! $ this ->curl_handle instanceof WeakReference ) {
58
68
// No cURL handle was used during this particular test scenario.
59
69
return ;
60
70
}
61
71
62
- if ($ this ->curl_handle instanceof CurlHandle) {
72
+ if ($ this ->curl_handle -> get () instanceof CurlHandle) {
63
73
// CURL handles have been changed from resources into CurlHandle
64
74
// objects starting with PHP 8.0, which don;t need to be closed.
65
75
return ;
66
76
}
67
77
68
- if ($ this ->shouldClosedResourceAssertionBeSkipped ($ this ->curl_handle ) === false ) {
69
- $ this ->assertIsClosedResource ($ this ->curl_handle );
78
+ if ($ this ->shouldClosedResourceAssertionBeSkipped ($ this ->curl_handle -> get () ) === false ) {
79
+ $ this ->assertIsClosedResource ($ this ->curl_handle -> get () );
70
80
}
71
81
}
72
82
0 commit comments