Completed
Push — master ( ce7d35...9aab54 )
by Anton
20:32
created

functions.php ➔ interpolate()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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