22
33namespace Francerz \Http \Tools ;
44
5+ use LogicException ;
56use Psr \Http \Message \UriFactoryInterface ;
67use Psr \Http \Message \UriInterface ;
78
@@ -126,4 +127,34 @@ public static function getCurrent(UriFactoryInterface $uriFactory) : UriInterfac
126127 $ uri .= ':// ' . $ _SERVER ['HTTP_HOST ' ] . $ _SERVER ['REQUEST_URI ' ];
127128 return $ uriFactory ->createUri ($ uri );
128129 }
130+
131+ private static function mapReplaceString (string $ uri , array $ replaces , bool $ encode_values = true ) : string
132+ {
133+ $ match = preg_match_all ('/\{([a-zA-Z0-9\-\_]+)\}/S ' , $ uri , $ matches );
134+ if (!$ match ) {
135+ return $ uri ;
136+ }
137+ $ matches = array_unique ($ matches [1 ]);
138+ foreach ($ matches as $ match ) {
139+ if (!array_key_exists ($ match , $ replaces )) {
140+ continue ;
141+ }
142+ $ val = $ encode_values ? urlencode ($ replaces [$ match ]) : $ replaces [$ match ];
143+ $ uri = str_replace ('{ ' .$ match .'} ' , $ val , $ uri );
144+ }
145+ return $ uri ;
146+ }
147+
148+ public static function mapReplace (UriFactoryInterface $ uriFactory , $ uri , array $ replaces , bool $ encode_values = true ) : UriInterface
149+ {
150+ $ uriStr = $ uri ;
151+ if ($ uri instanceof UriInterface) {
152+ $ uriStr = (string ) $ uri ;
153+ }
154+ if (!is_string ($ uriStr )) {
155+ throw new LogicException (__METHOD__ .' $uri argument must be string or UriInterface object ' );
156+ }
157+ $ uriStr = static ::mapReplaceString ($ uri , $ replaces , $ encode_values );
158+ return $ uriFactory ->createUri ($ uriStr );
159+ }
129160}
0 commit comments