TitlePlaceholdersTrait   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 53
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getTitlePlaceholderReplaces() 0 4 1
A updateTitle() 0 6 1
A replacePlaceholders() 0 17 3
1
<?php
2
3
namespace CosmicRadioTV\Podcast\Classes;
4
5
6
/**
7
 * Class TitlePlaceholdersTrait
8
 *
9
 * @property \Cms\Classes\PageCode $page Current page
10
 */
11
trait TitlePlaceholdersTrait
12
{
13
14
    /**
15
     * Returns things to replace placeholders with.
16
     * Must be an object so models can be easily walked to.
17
     * For ease you can do return (object) [...];
18
     *
19
     * @return object
20
     */
21
    protected function getTitlePlaceholderReplaces()
22
    {
23
        return new \stdClass();
24
    }
25
26
    /**
27
     * Update page's title using placeholders
28
     */
29
    protected function updateTitle()
30
    {
31
        $raw = $this->page->title;
32
33
        $this->page->title = $this->replacePlaceholders($raw, $this->getTitlePlaceholderReplaces());
34
    }
35
36
    /**
37
     * Replaces placeholders in title
38
     * Matches all {{rule}} placeholders, escaped @{{ blocks (w/ optional }})
39
     * Technically also matches "{{something"
40
     *
41
     * @param $title        string Title with placeholders
42
     * @param $replacedWith object Things to replace with
43
     *
44
     * @return mixed
45
     */
46
    protected function replacePlaceholders($title, $replacedWith)
47
    {
48
        return preg_replace_callback('/(\@)?\{\{([\w\d\.]+)(?:\}\})/', function ($matches) use ($replacedWith) {
49
            if ($matches[1] == '@') {
50
                // Escape
51
                return substr($matches[0], 1);
52
            }
53
            // Find the requested thing
54
            $value = object_get($replacedWith, $matches[2]);
55
            if ($value) {
56
                return $value;
57
            }
58
59
            // No idea
60
            return $matches[0];
61
        }, $title);
62
    }
63
}