Completed
Push — 6.13 ( 7e7b66...6c34c5 )
by André
53:02 queued 27:51
created

Configuration::addStashCacheSection()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 1
nop 1
dl 0
loc 28
rs 9.472
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\TreeBuilder;
15
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
16
17
class Configuration extends SiteAccessConfiguration
18
{
19
    /**
20
     * @var \eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Configuration\ParserInterface
21
     */
22
    private $mainConfigParser;
23
24
    /**
25
     * @var Configuration\Suggestion\Collector\SuggestionCollectorInterface
26
     */
27
    private $suggestionCollector;
28
    /**
29
     * @var \eZ\Bundle\EzPublishCoreBundle\SiteAccess\SiteAccessConfigurationFilter[]
30
     */
31
    private $siteAccessConfigurationFilters;
32
33
    public function __construct(ParserInterface $mainConfigParser, SuggestionCollectorInterface $suggestionCollector)
34
    {
35
        $this->suggestionCollector = $suggestionCollector;
36
        $this->mainConfigParser = $mainConfigParser;
37
    }
38
39
    public function setSiteAccessConfigurationFilters(array $filters)
40
    {
41
        $this->siteAccessConfigurationFilters = $filters;
42
    }
43
44
    /**
45
     * Generates the configuration tree builder.
46
     *
47
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
48
     */
49
    public function getConfigTreeBuilder()
50
    {
51
        $treeBuilder = new TreeBuilder();
52
        $rootNode = $treeBuilder->root('ezpublish');
53
54
        $this->addRepositoriesSection($rootNode);
55
        $this->addSiteaccessSection($rootNode);
56
        $this->addImageMagickSection($rootNode);
57
        $this->addHttpCacheSection($rootNode);
58
        $this->addPageSection($rootNode);
59
        $this->addRouterSection($rootNode);
60
        $this->addStashCacheSection($rootNode);
61
62
        // Delegate SiteAccess config to configuration parsers
63
        $this->mainConfigParser->addSemanticConfig($this->generateScopeBaseNode($rootNode));
64
65
        return $treeBuilder;
66
    }
67
68
    public function addRepositoriesSection(ArrayNodeDefinition $rootNode)
69
    {
70
        $rootNode
71
            ->children()
72
                ->arrayNode('repositories')
73
                    ->info('Content repositories configuration')
74
                    ->example(
75
                        array(
76
                            'main' => array(
77
                                'storage' => array(
78
                                    'engine' => 'legacy',
79
                                    'connection' => 'my_doctrine_connection_name',
80
                                ),
81
                            ),
82
                        )
83
                    )
84
                    ->useAttributeAsKey('alias')
85
                    ->prototype('array')
86
                        ->beforeNormalization()
87
                            ->always(
88
                                // Handling deprecated structure by mapping it to new one
89
                                function ($v) {
90
                                    if (isset($v['storage'])) {
91
                                        return $v;
92
                                    }
93
94
                                    if (isset($v['engine'])) {
95
                                        $v['storage']['engine'] = $v['engine'];
96
                                        unset($v['engine']);
97
                                    }
98
99
                                    if (isset($v['connection'])) {
100
                                        $v['storage']['connection'] = $v['connection'];
101
                                        unset($v['connection']);
102
                                    }
103
104
                                    if (isset($v['config'])) {
105
                                        $v['storage']['config'] = $v['config'];
106
                                        unset($v['config']);
107
                                    }
108
109
                                    return $v;
110
                                }
111
                            )
112
                        ->end()
113
                        ->beforeNormalization()
114
                            ->always(
115
                                // Setting default values
116
                                function ($v) {
117
                                    if ($v === null) {
118
                                        $v = array();
119
                                    }
120
121
                                    if (!isset($v['storage'])) {
122
                                        $v['storage'] = array();
123
                                    }
124
125
                                    if (!isset($v['search'])) {
126
                                        $v['search'] = array();
127
                                    }
128
129
                                    if (!isset($v['fields_groups']['list'])) {
130
                                        $v['fields_groups']['list'] = [];
131
                                    }
132
133
                                    if (!isset($v['options'])) {
134
                                        $v['options'] = [];
135
                                    }
136
137
                                    return $v;
138
                                }
139
                            )
140
                        ->end()
141
                        ->children()
142
                            ->arrayNode('storage')
143
                                ->children()
144
                                    ->scalarNode('engine')
145
                                        ->defaultValue('%ezpublish.api.storage_engine.default%')
146
                                        ->info('The storage engine to use')
147
                                    ->end()
148
                                    ->scalarNode('connection')
149
                                        ->defaultNull()
150
                                        ->info('The connection name, if applicable (e.g. Doctrine connection name). If not set, the default connection will be used.')
151
                                    ->end()
152
                                    ->arrayNode('config')
153
                                        ->info('Arbitrary configuration options, supported by your storage engine')
154
                                        ->useAttributeAsKey('key')
155
                                        ->prototype('variable')->end()
156
                                    ->end()
157
                                ->end()
158
                            ->end()
159
                            ->arrayNode('search')
160
                                ->children()
161
                                    ->scalarNode('engine')
162
                                        ->defaultValue('%ezpublish.api.search_engine.default%')
163
                                        ->info('The search engine to use')
164
                                    ->end()
165
                                    ->scalarNode('connection')
166
                                        ->defaultNull()
167
                                        ->info('The connection name, if applicable (e.g. Doctrine connection name). If not set, the default connection will be used.')
168
                                    ->end()
169
                                    ->arrayNode('config')
170
                                        ->info('Arbitrary configuration options, supported by your search engine')
171
                                        ->useAttributeAsKey('key')
172
                                        ->prototype('variable')->end()
173
                                    ->end()
174
                                ->end()
175
                            ->end()
176
                            ->arrayNode('fields_groups')
177
                                ->info('Definitions of fields groups.')
178
                                ->children()
179
                                    ->arrayNode('list')->prototype('scalar')->end()->end()
180
                                    ->scalarNode('default')->defaultValue('%ezsettings.default.content.field_groups.default%')->end()
181
                                ->end()
182
                            ->end()
183
                            ->arrayNode('options')
184
                                ->info('Options for repository.')
185
                                ->children()
186
                                    ->scalarNode('default_version_archive_limit')
187
                                        ->defaultValue(5)
188
                                        ->info('Default version archive limit (0-50), only enforced on publish, not on un-publish.')
189
                                    ->end()
190
                                ->end()
191
                            ->end()
192
                        ->end()
193
                    ->end()
194
                ->end()
195
            ->end();
196
    }
197
198
    public function addSiteaccessSection(ArrayNodeDefinition $rootNode)
199
    {
200
        $rootNode
201
            ->children()
202
                ->arrayNode('siteaccess')
203
                    ->info('SiteAccess configuration')
204
                    ->children()
205
                        ->arrayNode('list')
206
                            ->info('Available SiteAccess list')
207
                            ->example(array('ezdemo_site', 'ezdemo_site_admin'))
208
                            ->isRequired()
209
                            ->requiresAtLeastOneElement()
210
                            ->prototype('scalar')->end()
211
                        ->end()
212
                        ->arrayNode('groups')
213
                            ->useAttributeAsKey('key')
214
                            ->info('SiteAccess groups. Useful to share settings between Siteaccess')
215
                            ->example(array('ezdemo_group' => array('ezdemo_site', 'ezdemo_site_admin')))
216
                            ->prototype('array')
217
                                ->requiresAtLeastOneElement()
218
                                ->prototype('scalar')->end()
219
                            ->end()
220
                        ->end()
221
                        ->scalarNode('default_siteaccess')->isRequired()->info('Name of the default siteaccess')->end()
222
                        ->arrayNode('match')
223
                            ->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 "\\")')
224
                            ->example(
225
                                array(
226
                                    'Map\\URI' => array(
227
                                        'foo' => 'ezdemo_site',
228
                                        'ezdemo_site' => 'ezdemo_site',
229
                                        'ezdemo_site_admin' => 'ezdemo_site_admin',
230
                                    ),
231
                                    'Map\\Host' => array(
232
                                        'ezpublish.dev' => 'ezdemo_site',
233
                                        'admin.ezpublish.dev' => 'ezdemo_site_admin',
234
                                    ),
235
                                    '\\My\\Custom\\Matcher' => array(
236
                                        'some' => 'configuration',
237
                                    ),
238
                                    '@my.custom.matcher' => array(
239
                                        'some' => 'other_configuration',
240
                                    ),
241
                                )
242
                            )
243
                            ->isRequired()
244
                            ->useAttributeAsKey('key')
245
                            ->normalizeKeys(false)
246
                            ->prototype('array')
247
                                ->useAttributeAsKey('key')
248
                                ->beforeNormalization()
249
                                    ->always(
250
                                        function ($v) {
251
                                            // Value passed to the matcher should always be an array.
252
                                            // If value is not an array, we transform it to a hash, with 'value' as key.
253
                                            if (!is_array($v)) {
254
                                                return array('value' => $v);
255
                                            }
256
257
                                            // If passed value is a numerically indexed array, we must convert it into a hash.
258
                                            // See https://jira.ez.no/browse/EZP-21876
259
                                            if (array_keys($v) === range(0, count($v) - 1)) {
260
                                                $final = array();
261
                                                foreach ($v as $i => $val) {
262
                                                    $final["i$i"] = $val;
263
                                                }
264
265
                                                return $final;
266
                                            }
267
268
                                            return $v;
269
                                        }
270
                                    )
271
                                ->end()
272
                                ->normalizeKeys(false)
273
                                ->prototype('variable')->end()
274
                            ->end()
275
                        ->end()
276
                    ->end()
277
                    ->beforeNormalization()
278
                        ->always()->then(function ($v) {
279
                            if (isset($this->siteAccessConfigurationFilters)) {
280
                                foreach ($this->siteAccessConfigurationFilters as $filter) {
281
                                    $v = $filter->filter($v);
282
                                }
283
                            }
284
285
                            return $v;
286
                        })
287
                    ->end()
288
                ->end()
289
                ->arrayNode('locale_conversion')
290
                    ->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.')
291
                    ->example(array('fre-FR' => 'fr_FR'))
292
                    ->useAttributeAsKey('key')
293
                    ->normalizeKeys(false)
294
                    ->prototype('scalar')->end()
295
                ->end()
296
            ->end();
297
    }
298
299
    private function addImageMagickSection(ArrayNodeDefinition $rootNode)
300
    {
301
        $filtersInfo =
302
<<<EOT
303
DEPRECATED.
304
This is only used for legacy injection.
305
You may use imagick/gmagick liip_imagine bundle drivers.
306
307
Hash of filters to be used for your image variations config.
308
#   Key is the filter name, value is an argument passed to "convert" binary.
309
#   You can use numbered placeholders (aka input variables) that will be replaced by defined parameters in your image variations config
310
EOT;
311
312
        $rootNode
313
            ->children()
314
                ->arrayNode('imagemagick')
315
                    ->info('ImageMagick configuration')
316
                    ->children()
317
                        ->booleanNode('enabled')->defaultTrue()->end()
318
                        ->scalarNode('path')
319
                            ->info('Absolute path of ImageMagick / GraphicsMagick "convert" binary.')
320
                            ->beforeNormalization()
321
                                ->ifTrue(
322
                                    function ($v) {
323
                                        $basename = basename($v);
324
                                        // If there is a space in the basename, just drop it and everything after it.
325
                                        if (($wsPos = strpos($basename, ' ')) !== false) {
326
                                            $basename = substr($basename, 0, $wsPos);
327
                                        }
328
329
                                        return !is_executable(dirname($v) . DIRECTORY_SEPARATOR . $basename);
330
                                    }
331
                                )
332
                                ->thenInvalid('Please provide full path to ImageMagick / GraphicsMagick  "convert" binary. Please also check that it is executable.')
333
                            ->end()
334
                        ->end()
335
                        ->arrayNode('filters')
336
                            ->info($filtersInfo)
337
                            ->example(array('geometry/scaledownonly' => '"-geometry {1}x{2}>"'))
338
                            ->prototype('scalar')->end()
339
                        ->end()
340
                    ->end()
341
                ->end()
342
            ->end();
343
    }
344
345
    private function addHttpCacheSection(ArrayNodeDefinition $rootNode)
346
    {
347
        $purgeTypeInfo = <<<EOT
348
Http cache purge type.
349
350
Cache purge for content/locations is triggered when needed (e.g. on publish) and will result in one or several Http PURGE requests.
351
Can be "local", "http" or a valid symfony service id:
352
- If "local" is used, an Http PURGE request will be emulated when needed (e.g. when using Symfony internal reverse proxy).
353
- If "http" is used, a full HTTP PURGE/BAN is done to a real reverse proxy (Varnish, ..) depending on your config
354
- 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.
355
356
If ezplatform-http-cache package is enabled (default as of 1.12 and up), then go to documentation on this package for further
357
info on how it supports multiple response tagging, purges and allow plugins for custom purge types.
358
359
If that is not enabled, then the (deprecated as of 1.8) default BAN based system will be used instead.
360
Where ressponses can be tagged by a single  X-Location-Id header, and for purges a single Http BAN request will be sent,
361
where X-Location-Id header consists of a Regexp containing locationIds to ban.
362
  BAN Examples:
363
   - (123|456|789) => Purge locations #123, #456, #789.
364
   - .* => Purge all locations.
365
EOT;
366
367
        $rootNode
368
            ->children()
369
                ->arrayNode('http_cache')
370
                    ->children()
371
                        ->scalarNode('purge_type')
372
                            ->info($purgeTypeInfo)
373
                            ->defaultValue('local')
374
                            ->beforeNormalization()
375
                                ->ifTrue(
376
                                    function ($v) {
377
                                        $http = array('multiple_http' => true, 'single_http' => true);
378
379
                                        return isset($http[$v]);
380
                                    }
381
                                )
382
                                ->then(
383
                                    function () {
384
                                        return 'http';
385
                                    }
386
                                )
387
                            ->end()
388
                        ->end()
389
                        ->scalarNode('timeout')->info('DEPRECATED')->end()
390
                    ->end()
391
                ->end()
392
            ->end();
393
    }
394
395
    private function addPageSection(ArrayNodeDefinition $rootNode)
396
    {
397
        $pageInfo = <<<EOT
398
List of globally registered layouts and blocks used by the Page fieldtype
399
EOT;
400
401
        $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...
402
            ->children()
403
                ->arrayNode('ezpage')
404
                    ->info($pageInfo)
405
                    ->children()
406
                        ->arrayNode('layouts')
407
                            ->info('List of registered layouts, the key is the identifier of the layout')
408
                            ->useAttributeAsKey('key')
409
                            ->normalizeKeys(false)
410
                            ->prototype('array')
411
                                ->children()
412
                                    ->scalarNode('name')->isRequired()->info('Name of the layout')->end()
413
                                    ->scalarNode('template')->isRequired()->info('Template to use to render this layout')->end()
414
                                ->end()
415
                            ->end()
416
                        ->end()
417
                        ->arrayNode('blocks')
418
                            ->info('List of registered blocks, the key is the identifier of the block')
419
                            ->useAttributeAsKey('key')
420
                            ->normalizeKeys(false)
421
                            ->prototype('array')
422
                                ->children()
423
                                    ->scalarNode('name')->isRequired()->info('Name of the block')->end()
424
                                ->end()
425
                            ->end()
426
                        ->end()
427
                        ->arrayNode('enabledBlocks')
428
                            ->prototype('scalar')
429
                            ->end()
430
                            ->info('List of enabled blocks by default')
431
                        ->end()
432
                        ->arrayNode('enabledLayouts')
433
                            ->prototype('scalar')
434
                            ->end()
435
                            ->info('List of enabled layouts by default')
436
                        ->end()
437
                    ->end()
438
                ->end()
439
            ->end();
440
    }
441
442
    private function addRouterSection(ArrayNodeDefinition $rootNode)
443
    {
444
        $nonSAAwareInfo = <<<EOT
445
Route names that are not supposed to be SiteAccess aware, i.e. Routes pointing to asset generation (like assetic).
446
Note that you can just specify a prefix to match a selection of routes.
447
e.g. "_assetic_" will match "_assetic_*"
448
Defaults to ['_assetic_', '_wdt', '_profiler', '_configurator_']
449
EOT;
450
        $rootNode
451
            ->children()
452
                ->arrayNode('router')
453
                    ->children()
454
                        ->arrayNode('default_router')
455
                            ->children()
456
                                ->arrayNode('non_siteaccess_aware_routes')
457
                                    ->prototype('scalar')->end()
458
                                    ->info($nonSAAwareInfo)
459
                                    ->example(array('my_route_name', 'some_prefix_'))
460
                                ->end()
461
                            ->end()
462
                        ->end()
463
                    ->end()
464
                    ->info('Router related settings')
465
                ->end()
466
            ->end();
467
    }
468
469
    private function addStashCacheSection(ArrayNodeDefinition $rootNode)
470
    {
471
        $rootNode
472
            ->children()
473
                ->arrayNode('stash_cache')
474
                    ->children()
475
                        ->booleanNode('igbinary')
476
                            ->defaultFalse()
477
                            ->validate()
478
                                ->ifTrue(function ($igbinary) {
479
                                    return $igbinary && !extension_loaded('igbinary');
480
                                })
481
                                ->thenInvalid('PHP extension "igbinary" is not installed!')
482
                            ->end()
483
                        ->end()
484
                        ->booleanNode('lzf')
485
                            ->defaultFalse()
486
                            ->validate()
487
                                ->ifTrue(function ($lzf) {
488
                                    return $lzf && !extension_loaded('lzf');
489
                                })
490
                                ->thenInvalid('PHP extension "lzf" is not installed!')
491
                            ->end()
492
                        ->end()
493
                    ->end()
494
                ->end()
495
            ->end();
496
    }
497
}
498