Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
CriticalSectionScope
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
4 / 4
7
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 __destruct
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 exit
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getId
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\RequestTimeout;
5
6/**
7 * Class for automatically ending a critical section when a variable goes out
8 * of scope.
9 */
10class CriticalSectionScope {
11    /** @var int */
12    private $id;
13
14    /** @var callable */
15    private $exitCallback;
16
17    /** @var callable|null */
18    private $implicitExitCallback;
19
20    /** @var bool */
21    private $hasExited = false;
22
23    /**
24     * @internal
25     * @param int $id
26     * @param callable $exitCallback
27     * @param callable|null $implicitExitCallback
28     */
29    public function __construct( $id, $exitCallback, $implicitExitCallback ) {
30        $this->id = $id;
31        $this->exitCallback = $exitCallback;
32        $this->implicitExitCallback = $implicitExitCallback;
33    }
34
35    /**
36     * If the section has not already been exited, exit it and call the
37     * destruct callback.
38     *
39     * @throws TimeoutException
40     */
41    public function __destruct() {
42        if ( !$this->hasExited ) {
43            $this->exit();
44            if ( $this->implicitExitCallback ) {
45                ( $this->implicitExitCallback )( $this->id );
46            }
47        }
48    }
49
50    /**
51     * Exit the critical section
52     *
53     * @throws TimeoutException
54     */
55    public function exit() {
56        if ( !$this->hasExited ) {
57            $this->hasExited = true;
58            ( $this->exitCallback )( $this->id );
59        }
60    }
61
62    /**
63     * Get an integer uniquely identifying the section (within the scope of the
64     * parent RequestTimeout object).
65     *
66     * @since 1.1.0
67     * @return int
68     */
69    public function getId() {
70        return $this->id;
71    }
72}