1
+ <?php
2
+
3
+ namespace Hyperwallet \Util ;
4
+
5
+ /**
6
+ * A simple implementation of https://www.rfc-editor.org/rfc/rfc6570 for expanding Hyperwallet
7
+ * Uniform Resource Identifier (URI) Template.
8
+ *
9
+ * This class was created to allow the Hyperwallet SDK to support by PHP 5.6 and latest version
10
+ * @package Hyperwallet\Util
11
+ */
12
+ final class HyperwalletUriTemplate
13
+ {
14
+
15
+ /**
16
+ * Regex pattern to find variable identifier defined by pair of braces ('{', '}').
17
+ * e.g. {var}
18
+ */
19
+ const PATTERN = '/\{([^\}]+)\}/ ' ;
20
+
21
+ /**
22
+ * Processes URI Template
23
+ *
24
+ * This implementation will replace simple key defined in pair of braces ('{', '}') and replaced for the associate
25
+ * variable value.
26
+ *
27
+ * E.g. $uriTemplate = `test/{var-a}/{var-b}`, $variables = array('var-a' => 'testA', 'var-b' => 'testB') will return
28
+ * test/testA/testB
29
+ *
30
+ * @param string $uriTemplate the URI Template is a string that
31
+ * contains zero or more embedded variable expressions delimited by pair of braces ('{', '}').
32
+ * @param array $variables the variable identifiers for associating values within a template
33
+ * processor
34
+ * @return string
35
+ */
36
+ public function expand ($ uriTemplate , array $ variables )
37
+ {
38
+ if (!$ variables || strpos ($ uriTemplate , '{ ' ) === false ) {
39
+ // skip processing
40
+ return $ uriTemplate ;
41
+ }
42
+
43
+ return \preg_replace_callback (
44
+ self ::PATTERN ,
45
+ self ::buildProcessMatchResult ($ variables ),
46
+ $ uriTemplate
47
+ );
48
+ }
49
+
50
+ /**
51
+ * Evaluates the match result and find the associated value from the defined variables
52
+ * @param array $matches the match results
53
+ * @param array $variables the variable identifiers for associating values within a template
54
+ * processor
55
+ * @return mixed
56
+ */
57
+ private static function processMatchResult (array $ matches , array $ variables )
58
+ {
59
+ if (!isset ($ variables [$ matches [1 ]])) {
60
+ // missing variable definition, return the match key
61
+ return $ matches [0 ];
62
+ }
63
+
64
+ return $ variables [$ matches [1 ]];
65
+ }
66
+
67
+ /**
68
+ * Builds an anonymous functions to process the match result
69
+ * @param array $variables
70
+ * @return \Closure
71
+ */
72
+ private static function buildProcessMatchResult (array $ variables )
73
+ {
74
+ return static function (array $ matches ) use ($ variables ) {
75
+ return self ::processMatchResult ($ matches , $ variables );
76
+ };
77
+ }
78
+ }
0 commit comments