Completed
Push — master ( 391247...7316d8 )
by Hong
02:36
created

ReferenceTrait::clearReferenceCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
/**
3
 * Phossa Project
4
 *
5
 * PHP version 5.4
6
 *
7
 * @category  Library
8
 * @package   Phossa2\Shared
9
 * @copyright Copyright (c) 2016 phossa.com
10
 * @license   http://mit-license.org/ MIT License
11
 * @link      http://www.phossa.com/
12
 */
13
/*# declare(strict_types=1); */
14
15
namespace Phossa2\Shared\Reference;
16
17
use Phossa2\Shared\Message\Message;
18
use Phossa2\Shared\Exception\RuntimeException;
19
20
/**
21
 * ReferenceTrait
22
 *
23
 * Provides reference & dereference methods
24
 *
25
 * @package Phossa2\Shared
26
 * @author  Hong Zhang <[email protected]>
27
 * @see     ReferenceInterface
28
 * @version 2.0.4
29
 * @since   2.0.4 added
30
 * @since   2.0.6 added reference cache support
31
 */
32
trait ReferenceTrait
33
{
34
    /**
35
     * refernece start chars
36
     *
37
     * @var    string
38
     * @access protected
39
     */
40
    protected $ref_start = '${';
41
42
    /**
43
     * reference ending chars
44
     *
45
     * @var    string
46
     * @access protected
47
     */
48
    protected $ref_end = '}';
49
50
    /**
51
     * cached pattern to match
52
     *
53
     * @var    string
54
     * @access protected
55
     */
56
    protected $ref_pattern = '~(\$\{((?:(?!\$\{|\}).)+?)\})~';
57
58
    /**
59
     * cached references
60
     *
61
     * @var    array
62
     * @access protected
63
     * @since  2.0.6
64
     */
65
    protected $ref_cache = [];
66
67
    /**
68
     * {@inheritDoc}
69
     */
70
    public function setReference(
71
        /*# string */ $start,
72
        /*# string */ $end
73
    ) {
74
        $this->ref_start = $start;
75
        $this->ref_end = $end;
76
77
        // build pattern
78
        $s = preg_quote($start);
79
        $e = preg_quote($end);
80
        $this->ref_pattern = sprintf(
81
            "~(%s((?:(?!%s|%s).)+?)%s)~", $s, $s, $e, $e
82
        );
83
84
        return $this;
85
    }
86
87
    /**
88
     * {@inheritDoc}
89
     */
90
    public function hasReference(
91
        /*# string */ $subject,
92
        array &$matched
93
    )/*# : bool */ {
94
        if (is_string($subject) &&
95
            false !== strpos($subject, $this->ref_start) &&
96
            preg_match($this->ref_pattern, $subject, $matched)
97
        ) {
98
            return true;
99
        }
100
        return false;
101
    }
102
103
    /**
104
     * {@inheritDoc}
105
     */
106
    public function deReference(/*# string */ $subject)
107
    {
108
        $loop = 0;
109
        $matched = [];
110
111
        while ($this->hasReference($subject, $matched)) {
112
            // resolve the reference, checking loop also
113
            $val = $this->resolveReference($matched[2], $loop++);
114
115
            // resolved to another string
116
            if (is_string($val)) {
117
                $subject = str_replace($matched[1], $val, $subject);
118
119
            // resolved to array, object, null etc.
120
            } else {
121
                return $this->checkValue($val, $subject, $matched[1]);
122
            }
123
        }
124
        return $subject;
125
    }
126
127
    /**
128
     * {@inheritDoc}
129
     */
130
    public function deReferenceArray(&$dataArray)
131
    {
132
        if (is_string($dataArray)) {
133
            $dataArray = $this->deReference($dataArray);
134
        }
135
136
        if (!is_array($dataArray)) {
137
            return;
138
        }
139
140
        foreach ($dataArray as &$data) {
141
            $this->dereferenceArray($data);
142
        }
143
    }
144
145
    /**
146
     * Check dereferenced value
147
     *
148
     * @param  mixed $value
149
     * @param  string $subject
150
     * @param  string $reference
151
     * @return mixed
152
     * @throws RuntimeException if $subject malformed, like mix string & array
153
     * @access protected
154
     */
155
    protected function checkValue(
156
        $value,
157
        /*# string */ $subject,
158
        /*# string */ $reference
159
    ) {
160
        // unknown reference found, leave it alone
161
        if (is_null($value)) {
162
            // exception thrown in resolveUnknown() already if wanted to
163
            return $subject;
164
165
        // malformed partial match
166
        } elseif ($subject != $reference) {
167
            throw new RuntimeException(
168
                Message::get(Message::MSG_REF_MALFORMED, $reference),
169
                Message::MSG_REF_MALFORMED
170
            );
171
172
        // full match, array or object
173
        } else {
174
            return $value;
175
        }
176
    }
177
178
    /**
179
     * Resolve the reference $name
180
     *
181
     * @param  string $name
182
     * @param  int $loop
183
     * @return mixed
184
     * @throws RuntimeException if loop found or reference unknown
185
     * @access protected
186
     * @since  2.0.6 added cache support
187
     */
188
    protected function resolveReference(/*# string */ $name, /*# int */ $loop)
189
    {
190
        try {
191
            // loop found
192
            if ($loop > 20) {
193
                throw new RuntimeException(
194
                    Message::get(Message::MSG_REF_LOOP, $name),
195
                    Message::MSG_REF_LOOP
196
                );
197
            }
198
199
            // try reference cache first
200
            if (isset($this->ref_cache[$name])) {
201
                return $this->ref_cache[$name];
202
            }
203
204
            // get referenced value
205
            $val = $this->getReference($name);
206
207
            // unknown ref found
208
            if (is_null($val)) {
209
                $val = $this->resolveUnknown($name);
210
            }
211
212
            // cache deref result
213
            $this->ref_cache[$name] = $val;
214
215
            return $val;
216
217
        } catch (\Exception $e) {
218
            throw new RuntimeException($e->getMessage(), $e->getCode());
219
        }
220
    }
221
222
    /**
223
     * Clear reference cache
224
     *
225
     * @return $this
226
     * @access protected
227
     * @since  2.0.6 added
228
     */
229
    protected function clearReferenceCache()
230
    {
231
        $this->ref_cache = [];
232
        return $this;
233
    }
234
235
    /**
236
     * For unknown reference $name, normally returns NULL
237
     *
238
     * @param  string $name
239
     * @return mixed
240
     * @throws \Exception if implementor WANTS TO !!
241
     * @access protected
242
     */
243
    abstract protected function resolveUnknown(/*# string */ $name);
244
245
    /**
246
     * The real resolving method. return NULL for unknown reference
247
     *
248
     * @param  string $name
249
     * @return mixed
250
     * @access protected
251
     */
252
    abstract protected function getReference(/*# string */ $name);
253
}
254