-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestSession.php
More file actions
87 lines (75 loc) · 2.61 KB
/
Copy pathTestSession.php
File metadata and controls
87 lines (75 loc) · 2.61 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
<?php
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/**
* Italix Testing - TestSession
*
* @package Italix\Testing
*/
declare(strict_types=1);
namespace Italix\Testing;
/**
* Starts a real PHP session when that is still possible, and shrugs when it is
* not.
*
* Measured, not assumed, on PHP 8.1 CLI:
*
* - `session_start()` fails once anything has been printed, because CLI sets
* `headers_sent()` on the first byte of output. Options do not help; an
* active output buffer does, but only if it was opened before that byte.
* - `$_SESSION` is an ordinary superglobal. Writing to it without a session
* works, and application code that reads `$_SESSION['admin_id']`
* cannot tell the difference.
*
* So a real session is a *nicety*, not a requirement: it is worth having only
* because application middleware calls `session_start()` itself, and that call
* emits a warning into the test output when it cannot succeed. Starting the
* session first — which `Runner::suite()` does before it prints its header —
* makes the middleware's call a no-op and the output clean.
*
* When it is too late, this class does nothing and the suite still runs
* correctly. Refusing to run would be trading a working test for a tidy one.
*/
final class TestSession
{
private static bool $attempted = false;
private function __construct()
{
}
/**
* Ensure a session exists, if one still can.
*
* @return bool true when a real PHP session is active
*/
public static function ensure_started(): bool
{
if (session_status() === PHP_SESSION_ACTIVE) {
return true;
}
if (self::$attempted || headers_sent()) {
// Already tried, or too late to try. $_SESSION still works.
self::$attempted = true;
return false;
}
self::$attempted = true;
if (PHP_SAPI === 'cli') {
// The default save path is often unwritable for the CLI user, and
// a cookie has nowhere to go.
@session_save_path(sys_get_temp_dir());
@ini_set('session.use_cookies', '0');
@ini_set('session.cache_limiter', '');
}
@session_start();
return session_status() === PHP_SESSION_ACTIVE;
}
/**
* Whether a real PHP session backs $_SESSION right now.
*/
public static function is_active(): bool
{
return session_status() === PHP_SESSION_ACTIVE;
}
}