Replacer   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 27
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A replace() 0 10 2
A getParams() 0 3 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
        return $matches[0];
38
39
    }
40
}
41