Completed
Pull Request — master (#211)
by Eric
05:30 queued 02:42
created

CKEditorRenderer::fixConfigFilebrowsers()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 38
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 38
rs 8.439
cc 6
eloc 28
nc 4
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Ivory CKEditor package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ivory\CKEditorBundle\Renderer;
13
14
use Ivory\JsonBuilder\JsonBuilder;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16
17
/**
18
 * @author GeLo <[email protected]>
19
 */
20
class CKEditorRenderer implements CKEditorRendererInterface
21
{
22
    /** @var \Ivory\JsonBuilder\JsonBuilder */
23
    private $jsonBuilder;
24
25
    /** @var \Symfony\Component\DependencyInjection\ContainerInterface */
26
    private $container;
27
28
    /**
29
     * Creates a CKEditor renderer.
30
     *
31
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container The container.
32
     */
33
    public function __construct(ContainerInterface $container)
34
    {
35
        $this->jsonBuilder = new JsonBuilder();
36
        $this->container = $container;
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function renderBasePath($basePath)
43
    {
44
        return $this->fixPath($this->fixUrl($basePath));
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function renderJsPath($jsPath)
51
    {
52
        return $this->fixUrl($jsPath);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function renderWidget($id, array $config, array $options = array())
59
    {
60
        $config = $this->fixConfigLanguage($config);
61
        $config = $this->fixConfigContentsCss($config);
62
        $config = $this->fixConfigFilebrowsers($config);
63
64
        $this->jsonBuilder
65
            ->reset()
66
            ->setValues($config);
67
68
        $this->fixConfigEscapedValues($config);
69
70
        $autoInline = isset($options['auto_inline']) && !$options['auto_inline']
71
            ? 'CKEDITOR.disableAutoInline = true;'.PHP_EOL
72
            : null;
73
74
        $widget = sprintf(
75
            'CKEDITOR.%s("%s", %s);',
76
            isset($options['inline']) && $options['inline'] ? 'inline' : 'replace',
77
            $id,
78
            $this->fixConfigConstants($this->jsonBuilder->build())
79
        );
80
81
        if (isset($options['input_sync']) && $options['input_sync']) {
82
            $variable = 'ivory_ckeditor_'.$id;
83
            $widget = 'var '.$variable.' = '.$widget.PHP_EOL;
84
85
            return $autoInline.$widget.$variable.'.on(\'change\', function() { '.$variable.'.updateElement(); });';
86
        }
87
88
        return $autoInline.$widget;
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94
    public function renderDestroy($id)
95
    {
96
        return sprintf('if (CKEDITOR.instances["%s"]) { delete CKEDITOR.instances["%s"]; }', $id, $id);
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function renderPlugin($name, array $plugin)
103
    {
104
        return sprintf(
105
            'CKEDITOR.plugins.addExternal("%s", "%s", "%s");',
106
            $name,
107
            $this->fixPath($this->fixUrl($plugin['path'])),
108
            $plugin['filename']
109
        );
110
    }
111
112
    /**
113
     * {@inheritdoc}
114
     */
115
    public function renderStylesSet($name, array $stylesSet)
116
    {
117
        $this->jsonBuilder
118
            ->reset()
119
            ->setValues($stylesSet);
120
121
        return sprintf(
122
            'if (CKEDITOR.stylesSet.get("%s") === null) { CKEDITOR.stylesSet.add("%s", %s); }',
123
            $name,
124
            $name,
125
            $this->jsonBuilder->build()
126
        );
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function renderTemplate($name, array $template)
133
    {
134
        if (isset($template['imagesPath'])) {
135
            $template['imagesPath'] = $this->fixPath($this->fixUrl($template['imagesPath']));
136
        }
137
138
        $this->jsonBuilder
139
            ->reset()
140
            ->setValues($template);
141
142
        return sprintf('CKEDITOR.addTemplates("%s", %s);', $name, $this->jsonBuilder->build());
143
    }
144
145
    /**
146
     * Fixes the config language.
147
     *
148
     * @param array $config The config.
149
     *
150
     * @return array The fixed config.
151
     */
152
    private function fixConfigLanguage(array $config)
153
    {
154
        if (isset($config['language'])) {
155
            $config['language'] = strtolower(str_replace('_', '-', $config['language']));
156
        }
157
158
        return $config;
159
    }
160
161
    /**
162
     * Fixes the config contents css.
163
     *
164
     * @param array $config The config.
165
     *
166
     * @return array The fixed config.
167
     */
168
    private function fixConfigContentsCss(array $config)
169
    {
170
        if (isset($config['contentsCss'])) {
171
            $cssContents = (array) $config['contentsCss'];
172
173
            $config['contentsCss'] = array();
174
            foreach ($cssContents as $cssContent) {
175
                $config['contentsCss'][] = $this->fixPath($this->fixUrl($cssContent));
176
            }
177
        }
178
179
        return $config;
180
    }
181
182
    /**
183
     * Fixes the config filebrowsers.
184
     *
185
     * @param array $config The config.
186
     *
187
     * @return array The fixed config.
188
     */
189
    private function fixConfigFilebrowsers(array $config)
190
    {
191
        $keys = array(
192
            'Browse',
193
            'FlashBrowse',
194
            'ImageBrowse',
195
            'ImageBrowseLink',
196
            'Upload',
197
            'FlashUpload',
198
            'ImageUpload',
199
        );
200
201
        foreach ($keys as $key) {
202
            $fileBrowserKey = 'filebrowser'.$key;
203
            $handler = $fileBrowserKey.'Handler';
204
            $url = $fileBrowserKey.'Url';
205
            $route = $fileBrowserKey.'Route';
206
            $routeParameters = $fileBrowserKey.'RouteParameters';
207
            $routeAbsolute = $fileBrowserKey.'RouteAbsolute';
208
209
            if (isset($config[$handler])) {
210
                $config[$url] = $config[$handler]($this->getRouter());
211
            } elseif (isset($config[$route])) {
212
                $config[$url] = $this->getRouter()->generate(
213
                    $config[$route],
214
                    isset($config[$routeParameters]) ? $config[$routeParameters] : array(),
215
                    isset($config[$routeAbsolute]) ? $config[$routeAbsolute] : false
216
                );
217
            }
218
219
            unset($config[$handler]);
220
            unset($config[$route]);
221
            unset($config[$routeParameters]);
222
            unset($config[$routeAbsolute]);
223
        }
224
225
        return $config;
226
    }
227
228
    /**
229
     * Fixes the config escaped values and sets them on the json builder.
230
     *
231
     * @param array $config The config.
232
     */
233
    private function fixConfigEscapedValues(array $config)
234
    {
235
        if (isset($config['protectedSource'])) {
236
            foreach ($config['protectedSource'] as $key => $value) {
237
                $this->jsonBuilder->setValue(sprintf('[protectedSource][%s]', $key), $value, false);
238
            }
239
        }
240
241
        $escapedValueKeys = array(
242
            'stylesheetParser_skipSelectors',
243
            'stylesheetParser_validSelectors',
244
        );
245
246
        foreach ($escapedValueKeys as $escapedValueKey) {
247
            if (isset($config[$escapedValueKey])) {
248
                $this->jsonBuilder->setValue(sprintf('[%s]', $escapedValueKey), $config[$escapedValueKey], false);
249
            }
250
        }
251
    }
252
253
    /**
254
     * Fixes the config constants.
255
     *
256
     * @param string $json The json config.
257
     *
258
     * @return string The fixed config.
259
     */
260
    private function fixConfigConstants($json)
261
    {
262
        return preg_replace('/"(CKEDITOR\.[A-Z_]+)"/', '$1', $json);
263
    }
264
265
    /**
266
     * Fixes a path.
267
     *
268
     * @param string $path The path.
269
     *
270
     * @return string The fixed path.
271
     */
272
    private function fixPath($path)
273
    {
274
        if (($position = strpos($path, '?')) !== false) {
275
            return substr($path, 0, $position);
276
        }
277
278
        return $path;
279
    }
280
281
    /**
282
     * Fixes an url.
283
     *
284
     * @param string $url The url.
285
     *
286
     * @return string The fixed url.
287
     */
288
    private function fixUrl($url)
289
    {
290
        $assetsHelper = $this->getAssetsHelper();
291
292
        if ($assetsHelper !== null) {
293
            $url = $assetsHelper->getUrl($url);
294
        }
295
296
        return $url;
297
    }
298
299
    /**
300
     * Gets the assets helper.
301
     *
302
     * @return \Symfony\Component\Asset\Packages|\Symfony\Component\Templating\Helper\CoreAssetsHelper|null The assets helper.
303
     */
304
    private function getAssetsHelper()
305
    {
306
        return $this->container->get('assets.packages', ContainerInterface::NULL_ON_INVALID_REFERENCE);
307
    }
308
309
    /**
310
     * Gets the router.
311
     *
312
     * @return \Symfony\Component\Routing\RouterInterface The router.
313
     */
314
    private function getRouter()
315
    {
316
        return $this->container->get('router');
317
    }
318
}
319