Code

< 40 %
40-60 %
> 60 %
1
<?php
2
3
namespace WebStream\Container;
4
5
/**
6
 * ValueProxyクラス
7
 * @author Ryuichi TANAKA.
8
 * @since 2013/01/12
9
 * @version 0.4
10
 */
11
class ValueProxy
12
{
13
    /** コールバック関数 */
14
    private $callback;
15
    /** コンテキスト */
16
    private $context;
17
    /** キャッシュするかどうか */
18
    private $cached;
19
    /** コールバックの実行結果 */
20
    private $value;
21
22
    /**
23
     * コンストラクタ
24
     * @param  callable $callback コールバック関数
25
     * @param  array    $context  コンテキスト
26
     * @param  boolean  $cached   キャッシュするかどうか
27
     * @return void
28
     */
29 5
    public function __construct($callback, $context = [], $cached = true)
30
    {
31 5
        $this->callback = $callback;
32 5
        $this->cached   = $cached;
33 5
        $this->context  = $context;
34
    }
35
36
    /**
37
     * 評価する
38
     * @return mixed 実行結果
39
     */
40 5
    public function fetch()
41
    {
42 5
        if ($this->cached && isset($this->value)) {
43
            return $this->value;
44
        }
45 5
        $args = $this->context;
46
        // useで引数を指定した場合、call_user_func_arrayの$argsと
47
        // 引数の数が合わなくなり警告が出るが問題なく実行出来る
48 5
        $result = @call_user_func_array($this->callback, $args);
49 5
        if ($this->cached) {
50 4
            $this->value = $result;
51
        }
52
53 5
        return $result;
54
    }
55
}
56