functions.php ➔ interpolate()   B
last analyzed

Complexity

Conditions 6
Paths 17

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 17
nop 4
dl 0
loc 22
rs 8.9457
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral;
10
11
/**
12
 * Interpolate string with given parameters, used by many spiral components.
13
 *
14
 * Input: Hello {name}! Good {time}! + ['name' => 'Member', 'time' => 'day']
15
 * Output: Hello Member! Good Day!
16
 *
17
 * @param string $string
18
 * @param array  $values  Arguments (key => value). Will skip unknown names.
19
 * @param string $prefix  Placeholder prefix, "{" by default.
20
 * @param string $postfix Placeholder postfix, "}" by default.
21
 *
22
 * @return mixed
23
 */
24
function interpolate(
25
    string $string,
26
    array $values,
27
    string $prefix = '{',
28
    string $postfix = '}'
29
): string {
30
    $replaces = [];
31
    foreach ($values as $key => $value) {
32
        $value = (is_array($value) || $value instanceof \Closure) ? '' : $value;
33
34
        try {
35
            //Object as string
36
            $value = is_object($value) ? (string)$value : $value;
37
        } catch (\Exception $e) {
38
            $value = '';
39
        }
40
41
        $replaces[$prefix . $key . $postfix] = $value;
42
    }
43
44
    return strtr($string, $replaces);
45
}
46