Completed
Push — master ( 6207c8...1146be )
by Cheren
02:35
created

Macros::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
/**
3
 * CakeCMS Core
4
 *
5
 * This file is part of the of the simple cms based on CakePHP 3.
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 *
9
 * @package   Core
10
 * @license   MIT
11
 * @copyright MIT License http://www.opensource.org/licenses/mit-license.php
12
 * @link      https://github.com/CakeCMS/Core".
13
 * @author    Sergey Kalistratov <[email protected]>
14
 */
15
16
namespace Core\Utility;
17
18
use JBZoo\Utils\Arr;
19
use Cake\ORM\Entity;
20
use Cake\Utility\Hash;
21
use Cake\Routing\Router;
22
23
/**
24
 * Class Macros
25
 *
26
 * @package Core\Utility
27
 */
28
class Macros
29
{
30
31
    /**
32
     * Replacement list.
33
     *
34
     * @var array
35
     */
36
    protected $_list = [];
37
38
    /**
39
     * Macros constructor.
40
     *
41
     * @param array $list
42
     */
43
    public function __construct($list = [])
44
    {
45
        if ($list instanceof Entity) {
46
            /** @var Entity $list */
47
            $list = $list->toArray();
48
        }
49
50
        $this->_list = (array) $list;
51
        $this->set('base_url', Router::fullBaseUrl());
52
    }
53
54
    /**
55
     * Get replacement val or all list.
56
     *
57
     * @param null|string|int $key
58
     * @return array
59
     */
60
    public function get($key = null)
61
    {
62
        if (Arr::key($key, $this->_list)) {
63
            return $this->_list[$key];
64
        }
65
66
        return $this->_list;
67
    }
68
69
    /**
70
     * Add new value in list.
71
     *
72
     * @param string|int $key
73
     * @param string|int $val
74
     * @return $this
75
     */
76
    public function set($key, $val)
77
    {
78
        $this->_list = Hash::merge([$key => $val], $this->_list);
79
        return $this;
80
    }
81
82
    /**
83
     * Get replacement text.
84
     *
85
     * @param string $text
86
     * @return string mixed
87
     */
88
    public function text($text)
89
    {
90
        foreach ($this->_list as $macros => $value) {
91
            $macros = '{' . $macros . '}';
92
            $text   = preg_replace('#' . $macros . '#ius', $value, $text);
93
        }
94
95
        return $text;
96
    }
97
}
98