1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace Icybee\Modules\Editor;
13
14 use ICanBoogie\Exception;
15
16 17 18
19 class WidgetsEditor implements Editor
20 {
21 22 23 24 25
26 public function serialize($content)
27 {
28 return json_encode(array_keys($content));
29 }
30
31 32 33 34 35
36 public function unserialize($serialized_content)
37 {
38 return (array) json_decode($serialized_content);
39 }
40 41 42 43 44
45 public function from(array $attributes)
46 {
47 return new WidgetsEditorElement($attributes);
48 }
49
50 51 52 53 54
55 public function render($content)
56 {
57 global $core;
58
59 if (!$content)
60 {
61 return;
62 }
63
64 $availables = $core->configs->synthesize('widgets', 'merge');
65
66 if (!$availables)
67 {
68 return;
69 }
70
71 $selected = array_flip($content);
72 $undefined = array_diff_key($selected, $availables);
73
74 if ($undefined)
75 {
76 throw new Exception('Undefined widget(s): :list', array(':list' => implode(', ', array_keys($undefined))));
77 }
78
79 $list = array_intersect_key($availables, $selected);
80
81 if (!$list)
82 {
83 return;
84 }
85
86 $html = '';
87 $list = array_merge($selected, $list);
88
89 foreach ($list as $id => $widget)
90 {
91 $html .= '<div id="widget-' . \ICanBoogie\normalize($id) . '" class="widget">' . $this->render_widget($widget, $id) . '</div>';
92 }
93
94 return $html;
95 }
96
97 private function render_widget($widget, $id)
98 {
99 global $core;
100
101 if (isset($widget['file']))
102 {
103 $file = $widget['file'];
104
105 if (substr($file, -4, 4) == '.php')
106 {
107 ob_start();
108
109 require $file;
110
111 return ob_get_clean();
112 }
113 else if (substr($file, -5, 5) == '.html')
114 {
115 $patron = new \Patron\Engine;
116
117 return $patron(file_get_contents($file), null, array('file' => $file));
118 }
119 else
120 {
121 throw new Exception('Unable to process file %file, unsupported type', array('%file' => $file));
122 }
123 }
124 else if (isset($widget['module']) && isset($widget['block']))
125 {
126 return $core->modules[$widget['module']]->getBlock($widget['block']);
127 }
128 else
129 {
130 throw new Exception('Unable to render widget %widget, its description is invalid.', array('%widget' => $id));
131 }
132 }
133 }