SeoModelBehavior::getRouteUrl()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace kovenant\seo;
4
5
use yii\base\Behavior;
6
use yii\db\BaseActiveRecord;
7
use yii\helpers\ArrayHelper;
8
use yii\helpers\Url;
9
10
/**
11
 * Class SeoModelBehavior
12
 * @package kovenant\seo
13
 * @author Anton Berezin <[email protected]>
14
 */
15
class SeoModelBehavior extends Behavior
16
{
17
    /**
18
     * @property array GET parameters used for SEO.
19
     */
20
    public $route = [];
21
22
    /**
23
     * Returns the route array for this model.
24
     * Additional $params will be merged with route from model
25
     * @param array $params additional GET parameters (name=>value)
26
     * @return array
27
     */
28
    public function getRouteUrl(array $params = [])
29
    {
30
        $params = array_merge($this->route, $params);
31
32
        return array_map([$this, 'setPlaceholders'], $params);
33
    }
34
35
    /**
36
     * Returns the URL for this model.
37
     * @param array $params additional GET parameters (name=>value)
38
     * @return string the URL
39
     */
40
    public function getUrl(array $params = [])
41
    {
42
        return Url::toRoute($this->getRouteUrl($params));
43
    }
44
45
    /**
46
     * Returns the absolute URL for this model.
47
     * @param array $params additional GET parameters (name=>value)
48
     * @return string the URL
49
     */
50
    public function getAbsoluteUrl(array $params = [])
51
    {
52
        return Url::base(true) . $this->getUrl($params);
53
    }
54
55
    /**
56
     * Replaces all placeholders in param variable with corresponding values.
57
     * @param string $param
58
     * @return string
59
     * @throws \Exception
60
     */
61
    protected function setPlaceholders($param)
62
    {
63
        /** @var BaseActiveRecord $model */
64
        $model = $this->owner;
65
66
        return preg_replace_callback('/{([^}]+)}/', static function ($matches) use ($model) {
67
            $name = $matches[1];
68
            $attribute = ArrayHelper::getValue($model, $name);
69
70
            if (is_string($attribute) || is_numeric($attribute)) {
71
                return $attribute;
72
            }
73
74
            return $matches[0];
75
76
        }, $param);
77
    }
78
}