Completed
Push — master ( c37ad9...8221f3 )
by Marko
129:14 queued 114:10
created

CKEditorRenderer::__construct()   C

Complexity

Conditions 9
Paths 8

Size

Total Lines 68
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 52
nc 8
nop 6
dl 0
loc 68
ccs 0
cts 67
cp 0
crap 90
rs 6.2813
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 FOS\CKEditorBundle\Renderer;
13
14
use FOS\CKEditorBundle\Builder\JsonBuilder;
15
use Symfony\Component\Asset\Packages;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17
use Symfony\Component\HttpFoundation\RequestStack;
18
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
19
use Symfony\Component\Routing\RouterInterface;
20
use Symfony\Component\Templating\EngineInterface;
21
22
/**
23
 * @author GeLo <[email protected]>
24
 */
25
class CKEditorRenderer implements CKEditorRendererInterface
26
{
27
    /**
28
     * @var JsonBuilder
29
     */
30
    private $jsonBuilder;
31
32
    /**
33
     * @var RouterInterface
34
     */
35
    private $router;
36
37
    /**
38
     * @var Packages
39
     */
40
    private $assetsPackages;
41
42
    private $templating;
43
44
    /**
45
     * @var RequestStack
46
     */
47
    private $requestStack;
48
49
    /**
50
     * @var null|string
51
     */
52
    private $locale;
53
54
    /**
55
     * @param JsonBuilder|ContainerInterface $containerOrJsonBuilder
56
     * @param RouterInterface                $router
57
     * @param Packages                       $packages
58
     * @param RequestStack                   $requestStack
59
     * @param EngineInterface                $templating
60
     * @param null|string                    $locale
61
     */
62
    public function __construct(
63
        $containerOrJsonBuilder,
64
        RouterInterface $router = null,
65
        Packages $packages = null,
66
        RequestStack $requestStack = null,
67
        $templating = null,
68
        $locale = null
69
    ) {
70
        if ($containerOrJsonBuilder instanceof ContainerInterface) {
71
            @trigger_error(sprintf(
72
                'Passing a %s as %s first argument is deprecated since FOSCKEditor 1.0, and will be removed in 2.0.'
73
                .' Use %s instead.',
74
                ContainerInterface::class,
75
                __METHOD__,
76
                JsonBuilder::class
77
            ), E_USER_DEPRECATED);
78
            $jsonBuilder = $containerOrJsonBuilder->get('fos_ck_editor.renderer.json_builder');
79
            $router = $containerOrJsonBuilder->get('router');
80
            $packages = $containerOrJsonBuilder->get('assets.packages');
81
            $requestStack = $containerOrJsonBuilder->get('request_stack');
82
            $templating = $containerOrJsonBuilder->has('twig')
83
                ? $containerOrJsonBuilder->get('twig')
84
                : $containerOrJsonBuilder->get('templating');
85
        } elseif ($containerOrJsonBuilder instanceof JsonBuilder) {
0 ignored issues
show
introduced by
$containerOrJsonBuilder is always a sub-type of FOS\CKEditorBundle\Builder\JsonBuilder.
Loading history...
86
            $jsonBuilder = $containerOrJsonBuilder;
87
            if ($router === null) {
88
                throw new \InvalidArgumentException(sprintf(
89
                    '%s 2nd argument must not be null when using %s as first argument',
90
                    __METHOD__,
91
                    JsonBuilder::class
92
                ));
93
            } elseif ($packages === null) {
94
                throw new \InvalidArgumentException(sprintf(
95
                    '%s 3rd argument must not be null when using %s as first argument',
96
                    __METHOD__,
97
                    JsonBuilder::class
98
                ));
99
            } elseif ($requestStack === null) {
100
                throw new \InvalidArgumentException(sprintf(
101
                    '%s 4th argument must not be null when using %s as first argument',
102
                    __METHOD__,
103
                    JsonBuilder::class
104
                ));
105
            } elseif ($templating === null) {
106
                throw new \InvalidArgumentException(sprintf(
107
                    '%s 5th argument must not be null when using %s as first argument',
108
                    __METHOD__,
109
                    JsonBuilder::class
110
                ));
111
            }
112
        } else {
113
            throw new \InvalidArgumentException(sprintf(
114
                '%s first argument must be an instance of %s or %s (%s given).',
115
                __METHOD__,
116
                ContainerInterface::class,
117
                JsonBuilder::class,
118
                is_object($containerOrJsonBuilder)
119
                    ? get_class($containerOrJsonBuilder)
120
                    : gettype($containerOrJsonBuilder)
121
            ));
122
        }
123
124
        $this->jsonBuilder = $jsonBuilder;
125
        $this->router = $router;
126
        $this->assetsPackages = $packages;
127
        $this->templating = $templating;
128
        $this->requestStack = $requestStack;
129
        $this->locale = $locale;
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135
    public function renderBasePath($basePath)
136
    {
137
        return $this->fixPath($basePath);
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143
    public function renderJsPath($jsPath)
144
    {
145
        return $this->fixPath($jsPath);
146
    }
147
148
    /**
149
     * {@inheritdoc}
150
     */
151
    public function renderWidget($id, array $config, array $options = [])
152
    {
153
        $config = $this->fixConfigLanguage($config);
154
        $config = $this->fixConfigContentsCss($config);
155
        $config = $this->fixConfigFilebrowsers(
156
            $config,
157
            isset($options['filebrowsers']) ? $options['filebrowsers'] : []
158
        );
159
160
        $autoInline = isset($options['auto_inline']) && !$options['auto_inline']
161
            ? 'CKEDITOR.disableAutoInline = true;'."\n"
162
            : null;
163
164
        $builder = $this->jsonBuilder->reset()->setValues($config);
165
        $this->fixConfigEscapedValues($builder, $config);
166
167
        $widget = sprintf(
168
            'CKEDITOR.%s("%s", %s);',
169
            isset($options['inline']) && $options['inline'] ? 'inline' : 'replace',
170
            $id,
171
            $this->fixConfigConstants($builder->build())
172
        );
173
174
        if (isset($options['input_sync']) && $options['input_sync']) {
175
            $variable = 'fos_ckeditor_'.$id;
176
            $widget = 'var '.$variable.' = '.$widget."\n";
177
178
            return $autoInline.$widget.$variable.'.on(\'change\', function() { '.$variable.'.updateElement(); });';
179
        }
180
181
        return $autoInline.$widget;
182
    }
183
184
    /**
185
     * {@inheritdoc}
186
     */
187
    public function renderDestroy($id)
188
    {
189
        return sprintf(
190
            'if (CKEDITOR.instances["%1$s"]) { '.
191
            'CKEDITOR.instances["%1$s"].destroy(true); '.
192
            'delete CKEDITOR.instances["%1$s"]; '.
193
            '}',
194
            $id
195
        );
196
    }
197
198
    /**
199
     * {@inheritdoc}
200
     */
201
    public function renderPlugin($name, array $plugin)
202
    {
203
        return sprintf(
204
            'CKEDITOR.plugins.addExternal("%s", "%s", "%s");',
205
            $name,
206
            $this->fixPath($plugin['path']),
207
            $plugin['filename']
208
        );
209
    }
210
211
    /**
212
     * {@inheritdoc}
213
     */
214
    public function renderStylesSet($name, array $stylesSet)
215
    {
216
        return sprintf(
217
            'if (CKEDITOR.stylesSet.get("%1$s") === null) { '.
218
            'CKEDITOR.stylesSet.add("%1$s", %2$s); '.
219
            '}',
220
            $name,
221
            $this->jsonBuilder->reset()->setValues($stylesSet)->build()
222
        );
223
    }
224
225
    /**
226
     * {@inheritdoc}
227
     */
228
    public function renderTemplate($name, array $template)
229
    {
230
        if (isset($template['imagesPath'])) {
231
            $template['imagesPath'] = $this->fixPath($template['imagesPath']);
232
        }
233
234
        if (isset($template['templates'])) {
235
            foreach ($template['templates'] as &$rawTemplate) {
236
                if (isset($rawTemplate['template'])) {
237
                    $rawTemplate['html'] = $this->templating->render(
238
                        $rawTemplate['template'],
239
                        isset($rawTemplate['template_parameters']) ? $rawTemplate['template_parameters'] : []
240
                    );
241
                }
242
243
                unset($rawTemplate['template']);
244
                unset($rawTemplate['template_parameters']);
245
            }
246
        }
247
248
        return sprintf(
249
            'CKEDITOR.addTemplates("%s", %s);',
250
            $name,
251
            $this->jsonBuilder->reset()->setValues($template)->build()
252
        );
253
    }
254
255
    /**
256
     * @param array $config
257
     *
258
     * @return array
259
     */
260
    private function fixConfigLanguage(array $config)
261
    {
262
        if (!isset($config['language']) && ($language = $this->getLanguage()) !== null) {
263
            $config['language'] = $language;
264
        }
265
266
        if (isset($config['language'])) {
267
            $config['language'] = strtolower(str_replace('_', '-', $config['language']));
268
        }
269
270
        return $config;
271
    }
272
273
    /**
274
     * @param array $config
275
     *
276
     * @return array
277
     */
278
    private function fixConfigContentsCss(array $config)
279
    {
280
        if (isset($config['contentsCss'])) {
281
            $cssContents = (array) $config['contentsCss'];
282
283
            $config['contentsCss'] = [];
284
            foreach ($cssContents as $cssContent) {
285
                $config['contentsCss'][] = $this->fixPath($cssContent);
286
            }
287
        }
288
289
        return $config;
290
    }
291
292
    /**
293
     * @param array $config
294
     * @param array $filebrowsers
295
     *
296
     * @return array
297
     */
298
    private function fixConfigFilebrowsers(array $config, array $filebrowsers)
299
    {
300
        $filebrowsers = array_unique(array_merge([
301
            'Browse',
302
            'FlashBrowse',
303
            'ImageBrowse',
304
            'ImageBrowseLink',
305
            'Upload',
306
            'FlashUpload',
307
            'ImageUpload',
308
        ], $filebrowsers));
309
310
        foreach ($filebrowsers as $filebrowser) {
311
            $fileBrowserKey = 'filebrowser'.$filebrowser;
312
            $handler = $fileBrowserKey.'Handler';
313
            $url = $fileBrowserKey.'Url';
314
            $route = $fileBrowserKey.'Route';
315
            $routeParameters = $fileBrowserKey.'RouteParameters';
316
            $routeType = $fileBrowserKey.'RouteType';
317
318
            if (isset($config[$handler])) {
319
                $config[$url] = $config[$handler]($this->router);
320
            } elseif (isset($config[$route])) {
321
                $config[$url] = $this->router->generate(
322
                    $config[$route],
323
                    isset($config[$routeParameters]) ? $config[$routeParameters] : [],
324
                    isset($config[$routeType]) ? $config[$routeType] : UrlGeneratorInterface::ABSOLUTE_PATH
325
                );
326
            }
327
328
            unset($config[$handler]);
329
            unset($config[$route]);
330
            unset($config[$routeParameters]);
331
            unset($config[$routeType]);
332
        }
333
334
        return $config;
335
    }
336
337
    /**
338
     * @param JsonBuilder $builder
339
     * @param array       $config
340
     */
341
    private function fixConfigEscapedValues(JsonBuilder $builder, array $config)
342
    {
343
        if (isset($config['protectedSource'])) {
344
            foreach ($config['protectedSource'] as $key => $value) {
345
                $builder->setValue(sprintf('[protectedSource][%s]', $key), $value, false);
346
            }
347
        }
348
349
        $escapedValueKeys = [
350
            'stylesheetParser_skipSelectors',
351
            'stylesheetParser_validSelectors',
352
        ];
353
354
        foreach ($escapedValueKeys as $escapedValueKey) {
355
            if (isset($config[$escapedValueKey])) {
356
                $builder->setValue(sprintf('[%s]', $escapedValueKey), $config[$escapedValueKey], false);
357
            }
358
        }
359
    }
360
361
    /**
362
     * @param string $json
363
     *
364
     * @return string
365
     */
366
    private function fixConfigConstants($json)
367
    {
368
        return preg_replace('/"(CKEDITOR\.[A-Z_]+)"/', '$1', $json);
369
    }
370
371
    /**
372
     * @param string $path
373
     *
374
     * @return string
375
     */
376
    private function fixPath($path)
377
    {
378
        if ($this->assetsPackages === null) {
379
            return $path;
380
        }
381
382
        $url = $this->assetsPackages->getUrl($path);
383
384
        if (substr($path, -1) === '/' && ($position = strpos($url, '?')) !== false) {
385
            $url = substr($url, 0, $position);
386
        }
387
388
        return $url;
389
    }
390
391
    /**
392
     * @return null|string
393
     */
394
    private function getLanguage()
395
    {
396
        $request = $this->requestStack->getCurrentRequest();
397
        if ($request !== null) {
398
            return $request->getLocale();
399
        }
400
401
        return $this->locale;
402
    }
403
}
404