Replacer::getParams()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace andmemasin\helpers;
4
5
/**
6
 * Replacement values helper
7
 *
8
 * @package app\models\helpers
9
 * @author Tonis Ormisson <[email protected]>
10
 */
11
class Replacer {
12
    /**
13
     * Replace the {values} by $params[] values in $text
14
     * @param string $text
15
     * @param array[] $params
16
     * @return string
17
     */
18
    public static function replace($text, $params = []) {
19
        $allParams = $params;
20
        return preg_replace_callback('/{([^}]+)}/', function($m) use ($allParams) {
21
            // skip if is not set
22
            if (isset($allParams[$m[1]])) {
23
                return $allParams[$m[1]];
24
            }
25
            \Yii::error('Failed to replace field: '.$m[1], __METHOD__);
26
            return "{".$m[1]."}";
27
        }, $text);
28
    }
29
30
    /**
31
     * get the items in {} as array
32
     * @param $text
33
     * @return mixed
34
     */
35
    public static function getParams($text) {
36
        preg_match_all('/{(.*?)}/', $text, $matches);
37
        return $matches[0];
38
39
    }
40
}
41