Completed
Push — master ( e32077...7e7359 )
by Tõnis
02:36
created

Replacer::getParams()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
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
        if(is_array($matches)){
38
            return $matches[0];
39
        }
40
41
    }
42
}
43