Completed
Push — master ( cf5cfd...77d9d3 )
by Łukasz
20:22
created

Configuration::addRichTextSection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * File containing the Configuration class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 */
9
namespace eZ\Bundle\EzPublishCoreBundle\DependencyInjection;
10
11
use eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Configuration\ParserInterface;
12
use eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Configuration\SiteAccessAware\Configuration as SiteAccessConfiguration;
13
use eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Configuration\Suggestion\Collector\SuggestionCollectorInterface;
14
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
15
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
16
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
17
18
class Configuration extends SiteAccessConfiguration
19
{
20
    const CUSTOM_TAG_ATTRIBUTE_TYPES = ['number', 'string', 'boolean', 'choice'];
21
22
    /**
23
     * @var \eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Configuration\ParserInterface
24
     */
25
    private $mainConfigParser;
26
27
    /**
28
     * @var Configuration\Suggestion\Collector\SuggestionCollectorInterface
29
     */
30
    private $suggestionCollector;
31
32
    /**
33
     * @var \eZ\Bundle\EzPublishCoreBundle\SiteAccess\SiteAccessConfigurationFilter[]
34
     */
35
    private $siteAccessConfigurationFilters;
36
37
    public function __construct(ParserInterface $mainConfigParser, SuggestionCollectorInterface $suggestionCollector)
38
    {
39
        $this->suggestionCollector = $suggestionCollector;
40
        $this->mainConfigParser = $mainConfigParser;
41
    }
42
43
    public function setSiteAccessConfigurationFilters(array $filters)
44
    {
45
        $this->siteAccessConfigurationFilters = $filters;
46
    }
47
48
    /**
49
     * Generates the configuration tree builder.
50
     *
51
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
52
     */
53
    public function getConfigTreeBuilder()
54
    {
55
        $treeBuilder = new TreeBuilder();
56
        $rootNode = $treeBuilder->root('ezpublish');
57
58
        $this->addRepositoriesSection($rootNode);
59
        $this->addSiteaccessSection($rootNode);
60
        $this->addImageMagickSection($rootNode);
61
        $this->addHttpCacheSection($rootNode);
62
        $this->addPageSection($rootNode);
63
        $this->addRouterSection($rootNode);
64
        $this->addRichTextSection($rootNode);
65
66
        // Delegate SiteAccess config to configuration parsers
67
        $this->mainConfigParser->addSemanticConfig($this->generateScopeBaseNode($rootNode));
68
69
        return $treeBuilder;
70
    }
71
72
    public function addRepositoriesSection(ArrayNodeDefinition $rootNode)
73
    {
74
        $rootNode
75
            ->children()
76
                ->arrayNode('repositories')
77
                    ->info('Content repositories configuration')
78
                    ->example(
79
                        array(
80
                            'main' => array(
81
                                'storage' => array(
82
                                    'engine' => 'legacy',
83
                                    'connection' => 'my_doctrine_connection_name',
84
                                ),
85
                            ),
86
                        )
87
                    )
88
                    ->useAttributeAsKey('alias')
89
                    ->prototype('array')
90
                        ->beforeNormalization()
91
                            ->always(
92
                                // Handling deprecated structure by mapping it to new one
93
                                function ($v) {
94
                                    if (isset($v['storage'])) {
95
                                        return $v;
96
                                    }
97
98
                                    if (isset($v['engine'])) {
99
                                        $v['storage']['engine'] = $v['engine'];
100
                                        unset($v['engine']);
101
                                    }
102
103
                                    if (isset($v['connection'])) {
104
                                        $v['storage']['connection'] = $v['connection'];
105
                                        unset($v['connection']);
106
                                    }
107
108
                                    if (isset($v['config'])) {
109
                                        $v['storage']['config'] = $v['config'];
110
                                        unset($v['config']);
111
                                    }
112
113
                                    return $v;
114
                                }
115
                            )
116
                        ->end()
117
                        ->beforeNormalization()
118
                            ->always(
119
                                // Setting default values
120
                                function ($v) {
121
                                    if ($v === null) {
122
                                        $v = array();
123
                                    }
124
125
                                    if (!isset($v['storage'])) {
126
                                        $v['storage'] = array();
127
                                    }
128
129
                                    if (!isset($v['search'])) {
130
                                        $v['search'] = array();
131
                                    }
132
133
                                    if (!isset($v['fields_groups']['list'])) {
134
                                        $v['fields_groups']['list'] = [];
135
                                    }
136
137
                                    if (!isset($v['options'])) {
138
                                        $v['options'] = [];
139
                                    }
140
141
                                    return $v;
142
                                }
143
                            )
144
                        ->end()
145
                        ->children()
146
                            ->arrayNode('storage')
147
                                ->children()
148
                                    ->scalarNode('engine')
149
                                        ->defaultValue('%ezpublish.api.storage_engine.default%')
150
                                        ->info('The storage engine to use')
151
                                    ->end()
152
                                    ->scalarNode('connection')
153
                                        ->defaultNull()
154
                                        ->info('The connection name, if applicable (e.g. Doctrine connection name). If not set, the default connection will be used.')
155
                                    ->end()
156
                                    ->arrayNode('config')
157
                                        ->info('Arbitrary configuration options, supported by your storage engine')
158
                                        ->useAttributeAsKey('key')
159
                                        ->prototype('variable')->end()
160
                                    ->end()
161
                                ->end()
162
                            ->end()
163
                            ->arrayNode('search')
164
                                ->children()
165
                                    ->scalarNode('engine')
166
                                        ->defaultValue('%ezpublish.api.search_engine.default%')
167
                                        ->info('The search engine to use')
168
                                    ->end()
169
                                    ->scalarNode('connection')
170
                                        ->defaultNull()
171
                                        ->info('The connection name, if applicable (e.g. Doctrine connection name). If not set, the default connection will be used.')
172
                                    ->end()
173
                                    ->arrayNode('config')
174
                                        ->info('Arbitrary configuration options, supported by your search engine')
175
                                        ->useAttributeAsKey('key')
176
                                        ->prototype('variable')->end()
177
                                    ->end()
178
                                ->end()
179
                            ->end()
180
                            ->arrayNode('fields_groups')
181
                                ->info('Definitions of fields groups.')
182
                                ->children()
183
                                    ->arrayNode('list')->prototype('scalar')->end()->end()
184
                                    ->scalarNode('default')->defaultValue('%ezsettings.default.content.field_groups.default%')->end()
185
                                ->end()
186
                            ->end()
187
                            ->arrayNode('options')
188
                                ->info('Options for repository.')
189
                                ->children()
190
                                    ->scalarNode('default_version_archive_limit')
191
                                        ->defaultValue(5)
192
                                        ->info('Default version archive limit (0-50), only enforced on publish, not on un-publish.')
193
                                    ->end()
194
                                ->end()
195
                            ->end()
196
                        ->end()
197
                    ->end()
198
                ->end()
199
            ->end();
200
    }
201
202
    public function addSiteaccessSection(ArrayNodeDefinition $rootNode)
203
    {
204
        $rootNode
205
            ->children()
206
                ->arrayNode('siteaccess')
207
                    ->info('SiteAccess configuration')
208
                    ->children()
209
                        ->arrayNode('list')
210
                            ->info('Available SiteAccess list')
211
                            ->example(array('ezdemo_site', 'ezdemo_site_admin'))
212
                            ->isRequired()
213
                            ->requiresAtLeastOneElement()
214
                            ->prototype('scalar')->end()
215
                        ->end()
216
                        ->arrayNode('groups')
217
                            ->useAttributeAsKey('key')
218
                            ->info('SiteAccess groups. Useful to share settings between Siteaccess')
219
                            ->example(array('ezdemo_group' => array('ezdemo_site', 'ezdemo_site_admin')))
220
                            ->prototype('array')
221
                                ->requiresAtLeastOneElement()
222
                                ->prototype('scalar')->end()
223
                            ->end()
224
                        ->end()
225
                        ->scalarNode('default_siteaccess')->isRequired()->info('Name of the default siteaccess')->end()
226
                        ->arrayNode('match')
227
                            ->info('Siteaccess match configuration. First key is the matcher class, value is passed to the matcher. Key can be a service identifier (prepended by "@"), or a FQ class name (prepended by "\\")')
228
                            ->example(
229
                                array(
230
                                    'Map\\URI' => array(
231
                                        'foo' => 'ezdemo_site',
232
                                        'ezdemo_site' => 'ezdemo_site',
233
                                        'ezdemo_site_admin' => 'ezdemo_site_admin',
234
                                    ),
235
                                    'Map\\Host' => array(
236
                                        'ezpublish.dev' => 'ezdemo_site',
237
                                        'admin.ezpublish.dev' => 'ezdemo_site_admin',
238
                                    ),
239
                                    '\\My\\Custom\\Matcher' => array(
240
                                        'some' => 'configuration',
241
                                    ),
242
                                    '@my.custom.matcher' => array(
243
                                        'some' => 'other_configuration',
244
                                    ),
245
                                )
246
                            )
247
                            ->isRequired()
248
                            ->useAttributeAsKey('key')
249
                            ->normalizeKeys(false)
250
                            ->prototype('array')
251
                                ->useAttributeAsKey('key')
252
                                ->beforeNormalization()
253
                                    ->always(
254
                                        function ($v) {
255
                                            // Value passed to the matcher should always be an array.
256
                                            // If value is not an array, we transform it to a hash, with 'value' as key.
257
                                            if (!is_array($v)) {
258
                                                return array('value' => $v);
259
                                            }
260
261
                                            // If passed value is a numerically indexed array, we must convert it into a hash.
262
                                            // See https://jira.ez.no/browse/EZP-21876
263
                                            if (array_keys($v) === range(0, count($v) - 1)) {
264
                                                $final = array();
265
                                                foreach ($v as $i => $val) {
266
                                                    $final["i$i"] = $val;
267
                                                }
268
269
                                                return $final;
270
                                            }
271
272
                                            return $v;
273
                                        }
274
                                    )
275
                                ->end()
276
                                ->normalizeKeys(false)
277
                                ->prototype('variable')->end()
278
                            ->end()
279
                        ->end()
280
                    ->end()
281
                    ->beforeNormalization()
282
                        ->always()->then(function ($v) {
283
                            if (isset($this->siteAccessConfigurationFilters)) {
284
                                foreach ($this->siteAccessConfigurationFilters as $filter) {
285
                                    $v = $filter->filter($v);
286
                                }
287
                            }
288
289
                            return $v;
290
                        })
291
                    ->end()
292
                ->end()
293
                ->arrayNode('locale_conversion')
294
                    ->info('Locale conversion map between eZ Publish format (i.e. fre-FR) to POSIX (i.e. fr_FR). The key is the eZ Publish locale. Check locale.yml in EzPublishCoreBundle to see natively supported locales.')
295
                    ->example(array('fre-FR' => 'fr_FR'))
296
                    ->useAttributeAsKey('key')
297
                    ->normalizeKeys(false)
298
                    ->prototype('scalar')->end()
299
                ->end()
300
            ->end();
301
    }
302
303
    private function addImageMagickSection(ArrayNodeDefinition $rootNode)
304
    {
305
        $filtersInfo =
306
<<<EOT
307
DEPRECATED.
308
This is only used for legacy injection.
309
You may use imagick/gmagick liip_imagine bundle drivers.
310
311
Hash of filters to be used for your image variations config.
312
#   Key is the filter name, value is an argument passed to "convert" binary.
313
#   You can use numbered placeholders (aka input variables) that will be replaced by defined parameters in your image variations config
314
EOT;
315
316
        $rootNode
317
            ->children()
318
                ->arrayNode('imagemagick')
319
                    ->info('ImageMagick configuration')
320
                    ->children()
321
                        ->booleanNode('enabled')->defaultTrue()->end()
322
                        ->scalarNode('path')
323
                            ->info('Absolute path of ImageMagick / GraphicsMagick "convert" binary.')
324
                            ->beforeNormalization()
325
                                ->ifTrue(
326
                                    function ($v) {
327
                                        $basename = basename($v);
328
                                        // If there is a space in the basename, just drop it and everything after it.
329
                                        if (($wsPos = strpos($basename, ' ')) !== false) {
330
                                            $basename = substr($basename, 0, $wsPos);
331
                                        }
332
333
                                        return !is_executable(dirname($v) . DIRECTORY_SEPARATOR . $basename);
334
                                    }
335
                                )
336
                                ->thenInvalid('Please provide full path to ImageMagick / GraphicsMagick  "convert" binary. Please also check that it is executable.')
337
                            ->end()
338
                        ->end()
339
                        ->arrayNode('filters')
340
                            ->info($filtersInfo)
341
                            ->example(array('geometry/scaledownonly' => '"-geometry {1}x{2}>"'))
342
                            ->prototype('scalar')->end()
343
                        ->end()
344
                    ->end()
345
                ->end()
346
            ->end();
347
    }
348
349
    private function addHttpCacheSection(ArrayNodeDefinition $rootNode)
350
    {
351
        $purgeTypeInfo = <<<EOT
352
Http cache purge type.
353
354
Cache purge for content/locations is triggered when needed (e.g. on publish) and will result in one or several Http PURGE requests.
355
Can be "local", "http" or a valid symfony service id:
356
- If "local" is used, an Http PURGE request will be emulated when needed (e.g. when using Symfony internal reverse proxy).
357
- If "http" is used, a full HTTP PURGE/BAN is done to a real reverse proxy (Varnish, ..) depending on your config
358
- If custom symfony service id is used, then check documentation on that service for how it behaves and how you need to configure your system for it.
359
360
If ezplatform-http-cache package is enabled (default as of 1.12 and up), then go to documentation on this package for further
361
info on how it supports multiple response tagging, purges and allow plugins for custom purge types.
362
363
If that is not enabled, then the (deprecated as of 1.8) default BAN based system will be used instead.
364
Where ressponses can be tagged by a single  X-Location-Id header, and for purges a single Http BAN request will be sent,
365
where X-Location-Id header consists of a Regexp containing locationIds to ban.
366
  BAN Examples:
367
   - (123|456|789) => Purge locations #123, #456, #789.
368
   - .* => Purge all locations.
369
EOT;
370
371
        $rootNode
372
            ->children()
373
                ->arrayNode('http_cache')
374
                    ->children()
375
                        ->scalarNode('purge_type')
376
                            ->info($purgeTypeInfo)
377
                            ->defaultValue('local')
378
                            ->beforeNormalization()
379
                                ->ifTrue(
380
                                    function ($v) {
381
                                        $http = array('multiple_http' => true, 'single_http' => true);
382
383
                                        return isset($http[$v]);
384
                                    }
385
                                )
386
                                ->then(
387
                                    function () {
388
                                        return 'http';
389
                                    }
390
                                )
391
                            ->end()
392
                        ->end()
393
                        ->scalarNode('timeout')->info('DEPRECATED')->end()
394
                    ->end()
395
                ->end()
396
            ->end();
397
    }
398
399
    private function addPageSection(ArrayNodeDefinition $rootNode)
400
    {
401
        $pageInfo = <<<EOT
402
List of globally registered layouts and blocks used by the Page fieldtype
403
EOT;
404
405
        $rootNode
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Config...\Builder\NodeDefinition as the method children() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
406
            ->children()
407
                ->arrayNode('ezpage')
408
                    ->info($pageInfo)
409
                    ->children()
410
                        ->arrayNode('layouts')
411
                            ->info('List of registered layouts, the key is the identifier of the layout')
412
                            ->useAttributeAsKey('key')
413
                            ->normalizeKeys(false)
414
                            ->prototype('array')
415
                                ->children()
416
                                    ->scalarNode('name')->isRequired()->info('Name of the layout')->end()
417
                                    ->scalarNode('template')->isRequired()->info('Template to use to render this layout')->end()
418
                                ->end()
419
                            ->end()
420
                        ->end()
421
                        ->arrayNode('blocks')
422
                            ->info('List of registered blocks, the key is the identifier of the block')
423
                            ->useAttributeAsKey('key')
424
                            ->normalizeKeys(false)
425
                            ->prototype('array')
426
                                ->children()
427
                                    ->scalarNode('name')->isRequired()->info('Name of the block')->end()
428
                                ->end()
429
                            ->end()
430
                        ->end()
431
                        ->arrayNode('enabledBlocks')
432
                            ->prototype('scalar')
433
                            ->end()
434
                            ->info('List of enabled blocks by default')
435
                        ->end()
436
                        ->arrayNode('enabledLayouts')
437
                            ->prototype('scalar')
438
                            ->end()
439
                            ->info('List of enabled layouts by default')
440
                        ->end()
441
                    ->end()
442
                ->end()
443
            ->end();
444
    }
445
446
    private function addRouterSection(ArrayNodeDefinition $rootNode)
447
    {
448
        $nonSAAwareInfo = <<<EOT
449
Route names that are not supposed to be SiteAccess aware, i.e. Routes pointing to asset generation (like assetic).
450
Note that you can just specify a prefix to match a selection of routes.
451
e.g. "_assetic_" will match "_assetic_*"
452
Defaults to ['_assetic_', '_wdt', '_profiler', '_configurator_']
453
EOT;
454
        $rootNode
455
            ->children()
456
                ->arrayNode('router')
457
                    ->children()
458
                        ->arrayNode('default_router')
459
                            ->children()
460
                                ->arrayNode('non_siteaccess_aware_routes')
461
                                    ->prototype('scalar')->end()
462
                                    ->info($nonSAAwareInfo)
463
                                    ->example(array('my_route_name', 'some_prefix_'))
464
                                ->end()
465
                            ->end()
466
                        ->end()
467
                    ->end()
468
                    ->info('Router related settings')
469
                ->end()
470
            ->end();
471
    }
472
473
    /**
474
     * Define global Semantic Configuration for RichText.
475
     *
476
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $rootNode
477
     */
478
    private function addRichTextSection(ArrayNodeDefinition $rootNode)
479
    {
480
        $this->addCustomTagsSection(
481
            $rootNode->children()->arrayNode('ezrichtext')->children()
482
        )->end()->end()->end();
483
    }
484
485
    /**
486
     * Define RichText Custom Tags Semantic Configuration.
487
     *
488
     * The configuration is available at:
489
     * <code>
490
     * ezpublish:
491
     *     ezrichtext:
492
     *         custom_tags:
493
     * </code>
494
     *
495
     * @param \Symfony\Component\Config\Definition\Builder\NodeBuilder $ezRichTextNode
496
     *
497
     * @return \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
498
     */
499
    private function addCustomTagsSection(NodeBuilder $ezRichTextNode)
500
    {
501
        return $ezRichTextNode
502
                ->arrayNode('custom_tags')
503
                // workaround: take into account Custom Tag names when merging configs
504
                ->useAttributeAsKey('tag')
505
                ->arrayPrototype()
506
                    ->children()
507
                        ->scalarNode('template')
508
                            ->isRequired()
509
                        ->end()
510
                        ->scalarNode('icon')
511
                            ->defaultNull()
512
                        ->end()
513
                        ->arrayNode('attributes')
514
                            ->useAttributeAsKey('attribute')
515
                            ->isRequired()
516
                            ->arrayPrototype()
517
                                ->beforeNormalization()
518
                                    ->always(
519
                                        function ($v) {
520
                                            // Workaround: set empty value to be able to unset it later on (see validation for "choices")
521
                                            if (!isset($v['choices'])) {
522
                                                $v['choices'] = [];
523
                                            }
524
525
                                            return $v;
526
                                        }
527
                                    )
528
                                ->end()
529
                                ->validate()
530
                                    ->ifTrue(
531
                                        function ($v) {
532
                                            return $v['type'] === 'choice' && !empty($v['required']) && empty($v['choices']);
533
                                        }
534
                                    )
535
                                    ->thenInvalid('List of choices for required choice type attribute has to be non-empty')
536
                                ->end()
537
                                ->validate()
538
                                    ->ifTrue(
539
                                        function ($v) {
540
                                            return !empty($v['choices']) && $v['type'] !== 'choice';
541
                                        }
542
                                    )
543
                                    ->thenInvalid('List of choices is supported by choices type only.')
544
                                ->end()
545
                                ->children()
546
                                    ->enumNode('type')
547
                                        ->isRequired()
548
                                        ->values(static::CUSTOM_TAG_ATTRIBUTE_TYPES)
549
                                    ->end()
550
                                    ->booleanNode('required')
551
                                        ->defaultFalse()
552
                                    ->end()
553
                                    ->scalarNode('default_value')
554
                                        ->defaultNull()
555
                                    ->end()
556
                                    ->arrayNode('choices')
557
                                        ->scalarPrototype()->end()
558
                                        ->performNoDeepMerging()
559
                                        ->validate()
560
                                            ->ifEmpty()->thenUnset()
561
                                        ->end()
562
                                    ->end()
563
                                ->end()
564
                            ->end()
565
                        ->end()
566
                    ->end()
567
                ->end()
568
            ->end()
569
        ;
570
    }
571
}
572