Completed
Push — master ( 7cb054...584ba8 )
by Tim
44:11 queued 26:38
created

ExpiringMemoizingSupplier   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 24
rs 10
wmc 4
lcom 1
cbo 1
1
<?php
2
/*
3
 * Copyright (c) Ouzo contributors, http://ouzoframework.org
4
 * This file is made available under the MIT License (view the LICENSE file for more information).
5
 */
6
namespace Ouzo\Utilities\Supplier;
7
8
use Ouzo\Utilities\Clock;
9
10
class ExpiringMemoizingSupplier
11
{
12
    private $cachedResult;
13
    private $lastCallTime;
14
    private $function;
15
    private $expireTime;
16
17
    public function __construct($function, $expireTime = 3600)
18
    {
19
        $this->function = $function;
20
        $this->expireTime = $expireTime;
21
    }
22
23
    public function get()
24
    {
25
        $function = $this->function;
26
        $now = Clock::now()->getTimestamp();
27
        if ($this->cachedResult === null || $now - $this->lastCallTime > $this->expireTime) {
28
            $this->cachedResult = $function();
29
            $this->lastCallTime = $now;
30
        }
31
        return $this->cachedResult;
32
    }
33
}