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