Passed
Pull Request — 8.x-1.x (#11)
by Frédéric G.
01:11
created

Same::age()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 9
rs 10
cc 3
nc 3
nop 0
1
<?php
2
3
namespace Drupal\qa;
4
5
/**
6
 * A lifetime class.
7
 *
8
 * Properties are: Start, Access, Modify, End.
9
 *
10
 * Note: SAME is an old (ca 2005) OSInet PHP_lib class, which other modules may
11
 * have imported in a non-namespaced form.
12
 */
13
class Same {
14
15
  /**
16
   * Start timestamp.
17
   *
18
   * @var float
19
   */
20
  public $s;
21
22
  /**
23
   * Access timestamp.
24
   *
25
   * @var float
26
   */
27
  public $a;
28
29
  /**
30
   * Modification timestamp.
31
   *
32
   * @var float
33
   */
34
  public $m;
35
36
  /**
37
   * End timestamp.
38
   *
39
   * @var float
40
   */
41
  public $e;
42
43
  /**
44
   * Constructor
45
   *
46
   * S.A.M. default to current time, but E defaults to NULL.
47
   *
48
   * @param float $s
49
   * @param float $a
50
   * @param float $m
51
   * @param float $e
52
   */
53
  public function __construct($s = 0.0, $a = 0.0, $m = 0.0, $e = 0.0) {
54
    $now = microtime(TRUE);
55
    foreach (['s', 'a', 'm'] as $ts) {
56
      $this->$ts = ($$ts) ?: $now;
57
    }
58
    $this->e = $e;
59
  }
60
61
  /**
62
   * Update the access timestamp.
63
   *
64
   * @param float $now
65
   */
66
  public function access($now = 0.0) {
67
    $this->a = $now ?: microtime();
68
  }
69
70
  /**
71
   * Update the modification timestamp.
72
   *
73
   * @param float $now
74
   */
75
  public function modify($now = 0.0) {
76
    if (empty($now)) {
77
      $now = microtime(TRUE);
78
    }
79
    $this->access($now);
80
    $this->m = $now;
81
  }
82
83
  /**
84
   * Update the end timestamp.
85
   *
86
   * @param float $now
87
   */
88
  public function end($now = 0.0) {
89
    if (empty($now)) {
90
      $now = microtime(TRUE);
91
    }
92
    $this->modify($now);
93
    $this->e = $now;
94
  }
95
96
  // Return the age of the instance, in microseconds.
97
  public function age(): float {
98
    if (!empty($this->e)) {
99
      return $this->e - $this->s;
100
    }
101
    // Modifications imply update.
102
    elseif (!empty($this->a)) {
103
      return $this->a - $this->s;
104
    }
105
    return microtime(TRUE) - $this->s;
106
  }
107
108
  // Return the age of the instance in seconds, for use with UNIX timestamps.
109
  public function unixAge(): int {
110
    return intval($this->age() / 1E6);
111
  }
112
113
  public function __toString(): string {
114
    return $this->age();
115
  }
116
}
117