Completed
Branch develop (2a5993)
by Evan
02:52
created

Shortcode   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 94
rs 10
wmc 7
lcom 1
cbo 1

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A register() 0 4 1
A controller() 0 4 1
A render() 0 10 2
A handler() 0 4 1
A attributes() 0 4 1
1
<?php
2
3
namespace Silk\Support;
4
5
use Illuminate\Support\Collection;
6
7
abstract class Shortcode
8
{
9
    /**
10
     * The attributes passed to the shortcode
11
     * @var array
12
     */
13
    protected $attributes;
14
15
    /**
16
     * The enclosed content within the shortcode
17
     * @var string
18
     */
19
    protected $content;
20
    
21
    /**
22
     * The shortcode tag that was called
23
     * @var string
24
     */
25
    protected $tag;
26
27
    /**
28
     * Shortcode Constructor.
29
     *
30
     * @param array $atts      Shortcode attributes
31
     * @param string $content  The inner (enclosed) content
32
     * @param string $tag      The called shortcode tag
33
     */
34
    public function __construct($atts, $content, $tag)
35
    {
36
        $this->attributes = $atts;
37
        $this->content = $content;
38
        $this->tag = $tag;
39
    }
40
41
    /**
42
     * Register a tag for this shortcode.
43
     *
44
     * @param mixed $tag  The tag to register with this shortcode class
45
     */
46
    public static function register($tag)
47
    {
48
        add_shortcode((string) $tag, [static::class, 'controller']);
49
    }
50
51
    /**
52
     * WordPress Shortcode Callback
53
     *
54
     * @param  mixed $atts      Shortcode attributes
55
     * @param  string $content  The inner (enclosed) content
56
     * @param  string $tag      The called shortcode tag
57
     *
58
     * @return static
59
     */
60
    public static function controller($atts, $content, $tag)
61
    {
62
        return (new static((array) $atts, $content, $tag))->render();
63
    }
64
65
    /**
66
     * Call the shortcode's handler and return the output.
67
     *
68
     * @return mixed  Rendered shortcode output
69
     */
70
    public function render()
71
    {
72
        $dedicated_method = "{$this->tag}_handler";
73
74
        if (method_exists($this, $dedicated_method)) {
75
            return $this->$dedicated_method();
76
        }
77
78
        return $this->handler();
79
    }
80
81
    /**
82
     * Catch-all render method.
83
     *
84
     * @return string
85
     */
86
    protected function handler()
87
    {
88
        return '';  // Override this in a sub-class
89
    }
90
91
    /**
92
     * Get all attributes as a collection.
93
     *
94
     * @return Collection
95
     */
96
    public function attributes()
97
    {
98
        return Collection::make($this->attributes);
99
    }
100
}
101