ext-php-rs 0.15.9

Bindings for the Zend API to build PHP extensions natively in Rust.
Documentation
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
//! Types related to the PHP executor, sapi and process globals.

use parking_lot::{ArcRwLockReadGuard, ArcRwLockWriteGuard, RawRwLock, RwLock};
use std::collections::HashMap;
use std::ffi::CStr;
use std::ops::{Deref, DerefMut};
use std::slice;
use std::str;
use std::sync::{Arc, LazyLock};

use crate::boxed::ZBox;
use crate::exception::PhpResult;
#[cfg(php82)]
use crate::ffi::zend_atomic_bool_store;
use crate::ffi::{
    _sapi_module_struct, _zend_compiler_globals, _zend_executor_globals, TRACK_VARS_COOKIE,
    TRACK_VARS_ENV, TRACK_VARS_FILES, TRACK_VARS_GET, TRACK_VARS_POST, TRACK_VARS_SERVER,
    ext_php_rs_compiler_globals, ext_php_rs_executor_globals, ext_php_rs_file_globals,
    ext_php_rs_process_globals, ext_php_rs_sapi_globals, ext_php_rs_sapi_module, php_core_globals,
    php_file_globals, sapi_globals_struct, sapi_header_struct, sapi_headers_struct,
    sapi_request_info, zend_ini_entry, zend_is_auto_global,
};
#[cfg(not(php81))]
use crate::ffi::{_zend_hash_find_known_hash, _zend_string};
#[cfg(php81)]
use crate::ffi::{
    _zend_known_string_id_ZEND_STR_AUTOGLOBAL_REQUEST, zend_hash_find_known_hash,
    zend_known_strings,
};

use crate::types::{ZendHashTable, ZendObject, ZendStr};

use super::linked_list::ZendLinkedListIterator;

/// Stores global variables used in the PHP executor.
pub type ExecutorGlobals = _zend_executor_globals;

impl ExecutorGlobals {
    /// Returns a reference to the PHP executor globals.
    ///
    /// The executor globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    ///
    /// # Panics
    ///
    /// * If static executor globals are not set
    pub fn get() -> GlobalReadGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { ext_php_rs_executor_globals().as_ref() }
            .expect("Static executor globals were invalid");

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::GLOBALS_LOCK.with(RwLock::read_arc);
            } else {
                let guard = lock::GLOBALS_LOCK.read_arc();
            }
        }

        GlobalReadGuard { globals, guard }
    }

    /// Returns a mutable reference to the PHP executor globals.
    ///
    /// The executor globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    ///
    /// # Panics
    ///
    /// * If static executor globals are not set
    pub fn get_mut() -> GlobalWriteGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { ext_php_rs_executor_globals().as_mut() }
            .expect("Static executor globals were invalid");

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::GLOBALS_LOCK.with(RwLock::write_arc);
            } else {
                let guard = lock::GLOBALS_LOCK.write_arc();
            }
        }

        GlobalWriteGuard { globals, guard }
    }

    /// Attempts to retrieve the global class hash table.
    #[must_use]
    pub fn class_table(&self) -> Option<&ZendHashTable> {
        unsafe { self.class_table.as_ref() }
    }

    /// Attempts to retrieve the global functions hash table.
    #[must_use]
    pub fn function_table(&self) -> Option<&ZendHashTable> {
        unsafe { self.function_table.as_ref() }
    }

    /// Attempts to retrieve the global functions hash table as mutable.
    // TODO: Verify if this is safe to use, as it allows mutating the
    // hashtable while only having a reference to it. #461
    #[allow(clippy::mut_from_ref)]
    #[must_use]
    pub fn function_table_mut(&self) -> Option<&mut ZendHashTable> {
        unsafe { self.function_table.as_mut() }
    }

    /// Retrieves the ini values for all ini directives in the current executor
    /// context..
    ///
    /// # Panics
    ///
    /// * If the ini directives are not a valid hash table.
    /// * If the ini entry is not a string.
    #[must_use]
    pub fn ini_values(&self) -> HashMap<String, Option<String>> {
        let hash_table = unsafe { &*self.ini_directives };
        let mut ini_hash_map: HashMap<String, Option<String>> = HashMap::new();
        for (key, value) in hash_table {
            ini_hash_map.insert(key.to_string(), unsafe {
                let ini_entry = &*value.ptr::<zend_ini_entry>().expect("Invalid ini entry");
                if ini_entry.value.is_null() {
                    None
                } else {
                    Some(
                        (*ini_entry.value)
                            .as_str()
                            .expect("Ini value is not a string")
                            .to_owned(),
                    )
                }
            });
        }
        ini_hash_map
    }

    /// Attempts to retrieve the global constants table.
    #[must_use]
    pub fn constants(&self) -> Option<&ZendHashTable> {
        unsafe { self.zend_constants.as_ref() }
    }

    /// Attempts to extract the last PHP exception captured by the interpreter.
    /// Returned inside a [`ZBox`].
    ///
    /// This function requires the executor globals to be mutably held, which
    /// could lead to a deadlock if the globals are already borrowed immutably
    /// or mutably.
    #[must_use]
    pub fn take_exception() -> Option<ZBox<ZendObject>> {
        {
            // This avoid a write lock if there is no exception.
            if Self::get().exception.is_null() {
                return None;
            }
        }

        let mut globals = Self::get_mut();

        let mut exception_ptr = std::ptr::null_mut();
        std::mem::swap(&mut exception_ptr, &mut globals.exception);

        // SAFETY: `as_mut` checks for null.
        Some(unsafe { ZBox::from_raw(exception_ptr.as_mut()?) })
    }

    /// Checks if the executor globals contain an exception.
    #[must_use]
    pub fn has_exception() -> bool {
        !Self::get().exception.is_null()
    }

    /// Attempts to extract the last PHP exception captured by the interpreter.
    /// Returned inside a [`PhpResult`].
    ///
    /// This function requires the executor globals to be mutably held, which
    /// could lead to a deadlock if the globals are already borrowed immutably
    /// or mutably.
    ///
    /// # Errors
    ///
    /// If an exception is present, it will be returned as `Err` value inside a
    /// [`PhpResult`].
    pub fn throw_if_exception() -> PhpResult<()> {
        if let Some(e) = Self::take_exception() {
            Err(crate::error::Error::Exception(e).into())
        } else {
            Ok(())
        }
    }

    /// Request an interrupt of the PHP VM. This will call the registered
    /// interrupt handler function.
    /// set with [`crate::ffi::zend_interrupt_function`].
    pub fn request_interrupt(&mut self) {
        cfg_if::cfg_if! {
            if #[cfg(php82)] {
                unsafe {
                    zend_atomic_bool_store(&raw mut self.vm_interrupt, true);
                }
            } else {
                self.vm_interrupt = true;
            }
        }
    }

    /// Cancel a requested an interrupt of the PHP VM.
    pub fn cancel_interrupt(&mut self) {
        cfg_if::cfg_if! {
            if #[cfg(php82)] {
                unsafe {
                    zend_atomic_bool_store(&raw mut self.vm_interrupt, false);
                }
            } else {
                self.vm_interrupt = true;
            }
        }
    }
}

pub type CompilerGlobals = _zend_compiler_globals;

impl CompilerGlobals {
    /// Returns a reference to the PHP compiler globals.
    ///
    /// The compiler globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    ///
    /// # Panics
    ///
    /// * If static executor globals are not set
    pub fn get() -> GlobalReadGuard<Self> {
        // SAFETY: PHP compiler globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { ext_php_rs_compiler_globals().as_ref() }
            .expect("Static compiler globals were invalid");

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::GLOBALS_LOCK.with(RwLock::read_arc);
            } else {
                let guard = lock::GLOBALS_LOCK.read_arc();
            }
        }

        GlobalReadGuard { globals, guard }
    }

    /// Returns a mutable reference to the PHP compiler globals.
    ///
    /// The compiler globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    ///
    /// # Panics
    ///
    /// * If static compiler globals are not set
    pub fn get_mut() -> GlobalWriteGuard<Self> {
        // SAFETY: PHP compiler globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { ext_php_rs_compiler_globals().as_mut() }
            .expect("Static compiler globals were invalid");

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::GLOBALS_LOCK.with(RwLock::write_arc);
            } else {
                let guard = lock::GLOBALS_LOCK.write_arc();
            }
        }

        GlobalWriteGuard { globals, guard }
    }
}

/// Stores the SAPI module used in the PHP executor.
pub type SapiModule = _sapi_module_struct;

impl SapiModule {
    /// Returns a reference to the PHP SAPI module.
    ///
    /// The executor globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    ///
    /// # Panics
    ///
    /// * If static executor globals are not set
    pub fn get() -> GlobalReadGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { ext_php_rs_sapi_module().as_ref() }
            .expect("Static executor globals were invalid");
        let guard = SAPI_MODULE_LOCK.read_arc();
        GlobalReadGuard { globals, guard }
    }

    /// Returns a mutable reference to the PHP executor globals.
    ///
    /// The executor globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    ///
    /// # Panics
    ///
    /// * If static executor globals are not set
    pub fn get_mut() -> GlobalWriteGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { ext_php_rs_sapi_module().as_mut() }
            .expect("Static executor globals were invalid");
        let guard = SAPI_MODULE_LOCK.write_arc();
        GlobalWriteGuard { globals, guard }
    }
}

/// Stores global variables used in the PHP executor.
pub type ProcessGlobals = php_core_globals;

impl ProcessGlobals {
    /// Returns a reference to the PHP process globals.
    ///
    /// The process globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    pub fn get() -> GlobalReadGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { &*ext_php_rs_process_globals() };

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::PROCESS_GLOBALS_LOCK.with(RwLock::read_arc);
            } else {
                let guard = lock::PROCESS_GLOBALS_LOCK.read_arc();
            }
        }

        GlobalReadGuard { globals, guard }
    }

    /// Returns a mutable reference to the PHP executor globals.
    ///
    /// The executor globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    pub fn get_mut() -> GlobalWriteGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { &mut *ext_php_rs_process_globals() };

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::PROCESS_GLOBALS_LOCK.with(RwLock::write_arc);
            } else {
                let guard = lock::PROCESS_GLOBALS_LOCK.write_arc();
            }
        }

        GlobalWriteGuard { globals, guard }
    }

    /// Get the HTTP Server variables. Equivalent of $_SERVER.
    #[must_use]
    pub fn http_server_vars(&self) -> Option<&ZendHashTable> {
        // $_SERVER is lazy-initted, we need to call zend_is_auto_global
        // if it's not already populated.
        if !self.http_globals[TRACK_VARS_SERVER as usize].is_array() {
            let name = ZendStr::new("_SERVER", false).as_mut_ptr();
            unsafe { zend_is_auto_global(name) };
        }
        if self.http_globals[TRACK_VARS_SERVER as usize].is_array() {
            self.http_globals[TRACK_VARS_SERVER as usize].array()
        } else {
            None
        }
    }

    /// Get the HTTP POST variables. Equivalent of $_POST.
    ///
    /// # Panics
    ///
    /// * If the post global is not found or fails to be populated.
    #[must_use]
    pub fn http_post_vars(&self) -> &ZendHashTable {
        self.http_globals[TRACK_VARS_POST as usize]
            .array()
            .expect("Type is not a ZendArray")
    }

    /// Get the HTTP GET variables. Equivalent of $_GET.
    ///
    /// # Panics
    ///
    /// * If the get global is not found or fails to be populated.
    #[must_use]
    pub fn http_get_vars(&self) -> &ZendHashTable {
        self.http_globals[TRACK_VARS_GET as usize]
            .array()
            .expect("Type is not a ZendArray")
    }

    /// Get the HTTP Cookie variables. Equivalent of $_COOKIE.
    ///
    /// # Panics
    ///
    /// * If the cookie global is not found or fails to be populated.
    #[must_use]
    pub fn http_cookie_vars(&self) -> &ZendHashTable {
        self.http_globals[TRACK_VARS_COOKIE as usize]
            .array()
            .expect("Type is not a ZendArray")
    }

    /// Get the HTTP Request variables. Equivalent of $_REQUEST.
    ///
    /// # Panics
    ///
    /// * If the request global is not found or fails to be populated.
    /// * If the request global is not a [`ZendHashTable`].
    pub fn http_request_vars(&self) -> Option<&ZendHashTable> {
        cfg_if::cfg_if! {
            if #[cfg(php81)] {
                let key = unsafe {
                    *zend_known_strings.add(_zend_known_string_id_ZEND_STR_AUTOGLOBAL_REQUEST as usize)
                };
            } else {
                let key = _zend_string::new("_REQUEST", false).as_mut_ptr();
            }
        };

        // `$_REQUEST` is lazy-initted, we need to call `zend_is_auto_global` to make
        // sure it's populated.
        assert!(
            unsafe { zend_is_auto_global(key) },
            "Failed to get request global"
        );

        let symbol_table = &ExecutorGlobals::get().symbol_table;
        cfg_if::cfg_if! {
            if #[cfg(php81)] {
                let request = unsafe { zend_hash_find_known_hash(symbol_table, key) };
            } else {
                let request = unsafe { _zend_hash_find_known_hash(symbol_table, key) };
            }
        };

        if request.is_null() {
            return None;
        }

        Some(unsafe { (*request).array() }.expect("Type is not a ZendArray"))
    }

    /// Get the HTTP Environment variables. Equivalent of $_ENV.
    ///
    /// # Panics
    ///
    /// * If the environment global is not found or fails to be populated.
    #[must_use]
    pub fn http_env_vars(&self) -> &ZendHashTable {
        self.http_globals[TRACK_VARS_ENV as usize]
            .array()
            .expect("Type is not a ZendArray")
    }

    /// Get the HTTP Files variables. Equivalent of $_FILES.
    ///
    /// # Panics
    ///
    /// * If the files global is not found or fails to be populated.
    #[must_use]
    pub fn http_files_vars(&self) -> &ZendHashTable {
        self.http_globals[TRACK_VARS_FILES as usize]
            .array()
            .expect("Type is not a ZendArray")
    }
}

/// Stores global variables used in the SAPI.
pub type SapiGlobals = sapi_globals_struct;

impl SapiGlobals {
    /// Returns a reference to the PHP process globals.
    ///
    /// The process globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    #[must_use]
    pub fn get() -> GlobalReadGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { &*ext_php_rs_sapi_globals() };

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::SAPI_GLOBALS_LOCK.with(RwLock::read_arc);
            } else {
                let guard = lock::SAPI_GLOBALS_LOCK.read_arc();
            }
        }

        GlobalReadGuard { globals, guard }
    }

    /// Returns a mutable reference to the PHP executor globals.
    ///
    /// The executor globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    pub fn get_mut() -> GlobalWriteGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { &mut *ext_php_rs_sapi_globals() };

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::SAPI_GLOBALS_LOCK.with(RwLock::write_arc);
            } else {
                let guard = lock::SAPI_GLOBALS_LOCK.write_arc();
            }
        }

        GlobalWriteGuard { globals, guard }
    }

    /// Get the request info for the Sapi.
    #[must_use]
    pub fn request_info(&self) -> &SapiRequestInfo {
        &self.request_info
    }

    /// Get the sapi headers for the Sapi.
    #[must_use]
    pub fn sapi_headers(&self) -> &SapiHeaders {
        &self.sapi_headers
    }
}

/// Stores SAPI headers. Exposed through `SapiGlobals`.
pub type SapiHeaders = sapi_headers_struct;

impl<'a> SapiHeaders {
    /// Create an iterator over the headers.
    pub fn headers(&'a mut self) -> ZendLinkedListIterator<'a, SapiHeader> {
        self.headers.iter()
    }
}

/// Manage a key/value pair of SAPI headers.
pub type SapiHeader = sapi_header_struct;

impl<'a> SapiHeader {
    /// Get the header as a string.
    ///
    /// # Panics
    ///
    /// * If the header is not a valid UTF-8 string.
    #[must_use]
    pub fn as_str(&'a self) -> &'a str {
        unsafe {
            let slice = slice::from_raw_parts(self.header as *const u8, self.header_len);
            str::from_utf8(slice).expect("Invalid header string")
        }
    }

    /// Returns the header name (key).
    #[must_use]
    pub fn name(&'a self) -> &'a str {
        self.as_str().split(':').next().unwrap_or("").trim()
    }

    /// Returns the header value.
    #[must_use]
    pub fn value(&'a self) -> Option<&'a str> {
        self.as_str().split_once(':').map(|(_, value)| value.trim())
    }
}

pub type SapiRequestInfo = sapi_request_info;

impl SapiRequestInfo {
    /// Get the request method.
    #[must_use]
    pub fn request_method(&self) -> Option<&str> {
        if self.request_method.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.request_method).to_str().ok() }
    }

    /// Get the query string.
    #[must_use]
    pub fn query_string(&self) -> Option<&str> {
        if self.query_string.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.query_string).to_str().ok() }
    }

    /// Get the cookie data.
    #[must_use]
    pub fn cookie_data(&self) -> Option<&str> {
        if self.cookie_data.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.cookie_data).to_str().ok() }
    }

    /// Get the content length.
    #[must_use]
    pub fn content_length(&self) -> i64 {
        self.content_length
    }

    /// Get the path info.
    #[must_use]
    pub fn path_translated(&self) -> Option<&str> {
        if self.path_translated.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.path_translated).to_str().ok() }
    }

    /// Get the request uri.
    #[must_use]
    pub fn request_uri(&self) -> Option<&str> {
        if self.request_uri.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.request_uri).to_str().ok() }
    }

    // Todo: request_body _php_stream

    /// Get the content type.
    #[must_use]
    pub fn content_type(&self) -> Option<&str> {
        if self.content_type.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.content_type).to_str().ok() }
    }

    /// Whether the request consists of headers only.
    #[must_use]
    pub fn headers_only(&self) -> bool {
        self.headers_only
    }

    /// Whether the request has no headers.
    #[must_use]
    pub fn no_headers(&self) -> bool {
        self.no_headers
    }

    /// Whether the request headers have been read.
    #[must_use]
    pub fn headers_read(&self) -> bool {
        self.headers_read
    }

    // Todo: post_entry sapi_post_entry

    /// Get the auth user.
    #[must_use]
    pub fn auth_user(&self) -> Option<&str> {
        if self.auth_user.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.auth_user).to_str().ok() }
    }

    /// Get the auth password.
    #[must_use]
    pub fn auth_password(&self) -> Option<&str> {
        if self.auth_password.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.auth_password).to_str().ok() }
    }

    /// Get the auth digest.
    #[must_use]
    pub fn auth_digest(&self) -> Option<&str> {
        if self.auth_digest.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.auth_digest).to_str().ok() }
    }

    /// Get argv0.
    #[must_use]
    pub fn argv0(&self) -> Option<&str> {
        if self.argv0.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.argv0).to_str().ok() }
    }

    /// Get the current user.
    #[must_use]
    pub fn current_user(&self) -> Option<&str> {
        if self.current_user.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(self.current_user).to_str().ok() }
    }

    /// Get the current user length.
    #[must_use]
    pub fn current_user_length(&self) -> i32 {
        self.current_user_length
    }

    /// Get argvc.
    #[must_use]
    pub fn argvc(&self) -> i32 {
        self.argc
    }

    /// Get argv.
    #[must_use]
    pub fn argv(&self) -> Option<&str> {
        if self.argv.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(*self.argv).to_str().ok() }
    }

    /// Get the protocol number.
    #[must_use]
    pub fn proto_num(&self) -> i32 {
        self.proto_num
    }
}

/// Stores global variables used in the SAPI.
pub type FileGlobals = php_file_globals;

impl FileGlobals {
    /// Returns a reference to the PHP process globals.
    ///
    /// The process globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    ///
    /// # Panics
    ///
    /// * If static file globals are not set
    pub fn get() -> GlobalReadGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { ext_php_rs_file_globals().as_ref() }
            .expect("Static file globals were invalid");

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::FILE_GLOBALS_LOCK.with(RwLock::read_arc);
            } else {
                let guard = lock::FILE_GLOBALS_LOCK.read_arc();
            }
        }

        GlobalReadGuard { globals, guard }
    }

    /// Returns a mutable reference to the PHP executor globals.
    ///
    /// The executor globals are guarded by a [`RwLock`]. There can be multiple
    /// immutable references at one time but only ever one mutable reference.
    /// Attempting to retrieve the globals while already holding the global
    /// guard will lead to a deadlock. Dropping the globals guard will release
    /// the lock.
    #[must_use]
    pub fn get_mut() -> GlobalWriteGuard<Self> {
        // SAFETY: PHP executor globals are statically declared therefore should never
        // return an invalid pointer.
        let globals = unsafe { &mut *ext_php_rs_file_globals() };

        cfg_if::cfg_if! {
            if #[cfg(php_zts)] {
                let guard = lock::FILE_GLOBALS_LOCK.with(RwLock::write_arc);
            } else {
                let guard = lock::FILE_GLOBALS_LOCK.write_arc();
            }
        }

        GlobalWriteGuard { globals, guard }
    }

    /// Returns the stream wrappers
    #[must_use]
    pub fn stream_wrappers(&self) -> Option<&'static ZendHashTable> {
        unsafe { self.stream_wrappers.as_ref() }
    }
}

/// Executor globals rwlock.
///
/// PHP provides no indication if the executor globals are being accessed so
/// this is only effective on the Rust side.
#[cfg(not(php_zts))]
pub(crate) mod lock {
    use parking_lot::RwLock;
    use std::sync::{Arc, LazyLock};

    pub(crate) static GLOBALS_LOCK: LazyLock<Arc<RwLock<()>>> =
        LazyLock::new(|| Arc::new(RwLock::new(())));
    pub(crate) static PROCESS_GLOBALS_LOCK: LazyLock<Arc<RwLock<()>>> =
        LazyLock::new(|| Arc::new(RwLock::new(())));
    pub(crate) static SAPI_GLOBALS_LOCK: LazyLock<Arc<RwLock<()>>> =
        LazyLock::new(|| Arc::new(RwLock::new(())));
    pub(crate) static FILE_GLOBALS_LOCK: LazyLock<Arc<RwLock<()>>> =
        LazyLock::new(|| Arc::new(RwLock::new(())));
}

/// Executor globals rwlock.
///
/// PHP provides no indication if the executor globals are being accessed so
/// this is only effective on the Rust side.
#[cfg(php_zts)]
pub(crate) mod lock {
    use parking_lot::{RwLock, const_rwlock};
    use std::sync::Arc;

    thread_local! {
        pub(crate) static GLOBALS_LOCK: Arc<RwLock<()>> =  Arc::new(const_rwlock(()));
        pub(crate) static PROCESS_GLOBALS_LOCK: Arc<RwLock<()>> = Arc::new( const_rwlock(()) );
        pub(crate) static SAPI_GLOBALS_LOCK: Arc<RwLock<()>> = Arc::new( const_rwlock(()) );
        pub(crate) static FILE_GLOBALS_LOCK: Arc<RwLock<()>> = Arc::new( const_rwlock(()) );
    }
}

/// SAPI globals rwlock.
///
/// PHP provides no indication if the executor globals are being accessed so
/// this is only effective on the Rust side.
static SAPI_MODULE_LOCK: LazyLock<Arc<RwLock<()>>> = LazyLock::new(|| Arc::new(RwLock::new(())));

/// Wrapper guard that contains a reference to a given type `T`. Dropping a
/// guard releases the lock on the relevant rwlock.
pub struct GlobalReadGuard<T: 'static> {
    globals: &'static T,
    #[allow(dead_code)]
    guard: ArcRwLockReadGuard<RawRwLock, ()>,
}

impl<T> Deref for GlobalReadGuard<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.globals
    }
}

/// Wrapper guard that contains a mutable reference to a given type `T`.
/// Dropping a guard releases the lock on the relevant rwlock.
pub struct GlobalWriteGuard<T: 'static> {
    globals: &'static mut T,
    #[allow(dead_code)]
    guard: ArcRwLockWriteGuard<RawRwLock, ()>,
}

impl<T> Deref for GlobalWriteGuard<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.globals
    }
}

impl<T> DerefMut for GlobalWriteGuard<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.globals
    }
}

#[cfg(feature = "embed")]
#[cfg(test)]
mod embed_tests {
    use super::*;
    use crate::embed::Embed;
    use std::os::raw::c_char;

    #[test]
    fn test_sapi_header() {
        Embed::run(|| {
            let headers = [
                ("Content-Type: text/html", "Content-Type", "text/html"),
                ("X: Custom:Header", "X", "Custom:Header"),
            ];

            for (header_text, name, value) in headers {
                let header = SapiHeader {
                    header: header_text.as_bytes().as_ptr() as *mut c_char,
                    header_len: header_text.len(),
                };
                assert_eq!(header.name(), name, "Header name mismatch");
                assert_eq!(header.value(), Some(value), "Header value mismatch");
                assert_eq!(
                    header.as_str(),
                    format!("{name}: {value}"),
                    "Header string mismatch"
                );
            }
        });
    }

    #[test]
    fn test_executor_globals() {
        Embed::run(|| {
            let state = ExecutorGlobals::get().active;
            ExecutorGlobals::get_mut().active = !state;
            let changed = ExecutorGlobals::get().active;
            ExecutorGlobals::get_mut().active = state;
            assert_eq!(changed, !state);
        });
    }

    #[test]
    fn test_compiler_globals() {
        Embed::run(|| {
            let state = CompilerGlobals::get().in_compilation;
            CompilerGlobals::get_mut().in_compilation = !state;
            let changed = CompilerGlobals::get().in_compilation;
            CompilerGlobals::get_mut().in_compilation = state;
            assert_eq!(changed, !state);
        });
    }
}