Completed
Push — symfony4 ( c6a911...b0a2f3 )
by
unknown
37:19
created

BaseIntegrationTest   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 654
Duplicated Lines 12.84 %

Coupling/Cohesion

Components 3
Dependencies 29

Importance

Changes 0
Metric Value
dl 84
loc 654
rs 8.586
c 0
b 0
f 0
wmc 47
lcom 3
cbo 29

34 Methods

Rating   Name   Duplication   Size   Complexity  
getTypeName() 0 1 ?
getCustomHandler() 0 1 ?
getTypeConstraints() 0 1 ?
getFieldDefinitionData() 0 1 ?
getInitialValue() 0 1 ?
getUpdatedValue() 0 1 ?
A getInstallationDir() 10 10 2
A getTransformationProcessor() 0 12 2
A assertLoadedFieldDataCorrect() 0 7 1
A assertUpdatedFieldDataCorrect() 0 7 1
A postCreationHook() 0 4 1
A assertDeletedFieldDataCorrect() 0 4 1
A setUp() 0 13 2
A testCreateContentType() 0 9 1
A createContentType() 0 47 1
A testContentTypeField() 0 7 1
A testLoadContentTypeField() 0 7 1
A testLoadContentTypeFieldType() 0 9 1
A testLoadContentTypeFieldData() 0 7 1
A testCreateContent() 0 13 1
A createContent() 0 54 1
A testCreatedFieldType() 0 9 1
A testLoadField() 0 8 1
A testLoadFieldType() 0 9 1
A testLoadExternalData() 0 4 1
A testUpdateField() 0 6 1
A updateContent() 0 20 1
A testUpdateFieldType() 0 9 1
A testUpdateExternalData() 0 4 1
A testDeleteField() 0 14 1
A deleteContent() 0 9 1
A getContainer() 40 40 1
A getHandler() 0 22 1
C setAllServicesPublic() 34 34 17

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like BaseIntegrationTest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BaseIntegrationTest, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * File contains: eZ\Publish\SPI\Tests\FieldType\BaseIntegrationTest 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\Publish\SPI\Tests\FieldType;
10
11
use eZ\Publish\Core\Persistence;
12
use eZ\Publish\Core\Persistence\TransformationProcessor\DefinitionBased;
13
use eZ\Publish\Core\Persistence\Legacy\Tests\TestCase;
14
use eZ\Publish\Core\Persistence\Legacy;
15
use eZ\Publish\SPI\Persistence\Content;
16
use eZ\Publish\SPI\Persistence\Content\Field;
17
use eZ\Publish\SPI\Persistence\Content\Type;
18
use eZ\Publish\SPI\Persistence\Content\UpdateStruct;
19
use Symfony\Component\DependencyInjection\ContainerBuilder;
20
use Symfony\Component\Config\FileLocator;
21
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
22
23
/**
24
 * Integration test for the legacy storage.
25
 *
26
 * @group integration
27
 */
28
abstract class BaseIntegrationTest extends TestCase
29
{
30
    /**
31
     * Property indicating whether the DB already has been set up.
32
     *
33
     * @var bool
34
     */
35
    protected static $setUp = false;
36
37
    /**
38
     * Id of test content type.
39
     *
40
     * @var string
41
     */
42
    protected static $contentTypeId;
43
44
    /**
45
     * Id of test content.
46
     *
47
     * @var string
48
     */
49
    protected static $contentId;
50
51
    /**
52
     * Current version of test content.
53
     *
54
     * @var string
55
     */
56
    protected static $contentVersion;
57
58
    /**
59
     * @var \Symfony\Component\DependencyInjection\ContainerBuilder
60
     */
61
    protected static $container;
62
63
    /**
64
     * @return string
65
     */
66 View Code Duplication
    protected static function getInstallationDir()
67
    {
68
        static $installDir = null;
69
        if ($installDir === null) {
70
            $config = require __DIR__ . '/../../../../../config.php';
71
            $installDir = $config['install_dir'];
72
        }
73
74
        return $installDir;
75
    }
76
77
    /**
78
     * @var \eZ\Publish\Core\Persistence\TransformationProcessor
79
     */
80
    protected $transformationProcessor;
81
82
    /**
83
     * @return \eZ\Publish\Core\Persistence\TransformationProcessor
84
     */
85
    public function getTransformationProcessor()
86
    {
87
        if (!isset($this->transformationProcessor)) {
88
            $this->transformationProcessor = new DefinitionBased(
89
                new Persistence\TransformationProcessor\DefinitionBased\Parser(self::getInstallationDir()),
90
                new Persistence\TransformationProcessor\PcreCompiler(new Persistence\Utf8Converter()),
91
                glob(__DIR__ . '/../../../Core/Persistence/Tests/TransformationProcessor/_fixtures/transformations/*.tr')
92
            );
93
        }
94
95
        return $this->transformationProcessor;
96
    }
97
98
    /**
99
     * Returns the identifier of the FieldType under test.
100
     *
101
     * @return string
102
     */
103
    abstract public function getTypeName();
104
105
    /**
106
     * Returns the Handler with all necessary objects registered.
107
     *
108
     * Returns an instance of the Persistence Handler where the
109
     * FieldType\Storage has been registered.
110
     *
111
     * @return \eZ\Publish\SPI\Persistence\Handler
112
     */
113
    abstract public function getCustomHandler();
114
115
    /**
116
     * Returns the FieldTypeConstraints to be used to create a field definition
117
     * of the FieldType under test.
118
     *
119
     * @return \eZ\Publish\SPI\Persistence\Content\FieldTypeConstraints
120
     */
121
    abstract public function getTypeConstraints();
122
123
    /**
124
     * Returns the field definition data expected after loading the newly
125
     * created field definition with the FieldType under test.
126
     *
127
     * This is a PHPUnit data provider
128
     *
129
     * @return array
130
     */
131
    abstract public function getFieldDefinitionData();
132
133
    /**
134
     * Get initial field value.
135
     *
136
     * @return \eZ\Publish\SPI\Persistence\Content\FieldValue
137
     */
138
    abstract public function getInitialValue();
139
140
    /**
141
     * Asserts that the loaded field data is correct.
142
     *
143
     * Performs assertions on the loaded field, mainly checking that the
144
     * $field->value->externalData is loaded correctly. If the loading of
145
     * external data manipulates other aspects of $field, their correctness
146
     * also needs to be asserted. Make sure you implement this method agnostic
147
     * to the used SPI\Persistence implementation!
148
     */
149
    public function assertLoadedFieldDataCorrect(Field $field)
150
    {
151
        $this->assertEquals(
152
            $this->getInitialValue(),
153
            $field->value
154
        );
155
    }
156
157
    /**
158
     * Get update field value.
159
     *
160
     * Use to update the field
161
     *
162
     * @return \eZ\Publish\SPI\Persistence\Content\FieldValue
163
     */
164
    abstract public function getUpdatedValue();
165
166
    /**
167
     * Asserts that the updated field data is loaded correct.
168
     *
169
     * Performs assertions on the loaded field after it has been updated,
170
     * mainly checking that the $field->value->externalData is loaded
171
     * correctly. If the loading of external data manipulates other aspects of
172
     * $field, their correctness also needs to be asserted. Make sure you
173
     * implement this method agnostic to the used SPI\Persistence
174
     * implementation!
175
     */
176
    public function assertUpdatedFieldDataCorrect(Field $field)
177
    {
178
        $this->assertEquals(
179
            $this->getUpdatedValue(),
180
            $field->value
181
        );
182
    }
183
184
    /**
185
     * Method called after content creation.
186
     *
187
     * Useful, if additional stuff should be executed (like creating the actual
188
     * user).
189
     *
190
     * @param Legacy\Handler $handler
191
     * @param Content $content
192
     */
193
    public function postCreationHook(Legacy\Handler $handler, Content $content)
194
    {
195
        // Do nothing by default
196
    }
197
198
    /**
199
     * Can be overwritten to assert that additional data has been deleted.
200
     *
201
     * @param Content $content
202
     */
203
    public function assertDeletedFieldDataCorrect(Content $content)
0 ignored issues
show
Unused Code introduced by
The parameter $content is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
204
    {
205
        // Do nothing by default
206
    }
207
208
    /**
209
     * Only set up once for these read only tests on a large fixture.
210
     *
211
     * Skipping the reset-up, since setting up for these tests takes quite some
212
     * time, which is not required to spent, since we are only reading from the
213
     * database anyways.
214
     */
215
    public function setUp()
216
    {
217
        if (!self::$setUp) {
218
            self::$container = $this->getContainer();
219
            $this->handler = self::$container->get('ezpublish.api.storage_engine.legacy.dbhandler');
220
            $this->db = $this->handler->getName();
221
            parent::setUp();
222
            $this->insertDatabaseFixture(__DIR__ . '/../../../Core/Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
223
            self::$setUp = $this->handler;
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->handler of type object is incompatible with the declared type boolean of property $setUp.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
224
        } else {
225
            $this->handler = self::$setUp;
0 ignored issues
show
Documentation Bug introduced by
It seems like self::$setUp of type boolean is incompatible with the declared type object<eZ\Publish\Core\P...tabase\DatabaseHandler> of property $handler.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
226
        }
227
    }
228
229
    public function testCreateContentType()
230
    {
231
        $contentType = $this->createContentType();
232
233
        $this->assertNotNull($contentType->id);
234
        self::$contentTypeId = $contentType->id;
235
236
        return $contentType;
237
    }
238
239
    /**
240
     * Performs the creation of the content type with a field of the field type
241
     * under test.
242
     *
243
     * @return \eZ\Publish\SPI\Persistence\Content\Type
244
     */
245
    protected function createContentType()
246
    {
247
        $createStruct = new Content\Type\CreateStruct(
248
            array(
249
                'name' => array('eng-GB' => 'Test'),
250
                'identifier' => 'test-' . $this->getTypeName(),
251
                'status' => 0,
252
                'creatorId' => 14,
253
                'created' => time(),
254
                'modifierId' => 14,
255
                'modified' => time(),
256
                'initialLanguageId' => 2,
257
                'remoteId' => 'abcdef',
258
            )
259
        );
260
261
        $createStruct->fieldDefinitions = array(
262
            new Content\Type\FieldDefinition(
263
                array(
264
                    'name' => array('eng-GB' => 'Name'),
265
                    'identifier' => 'name',
266
                    'fieldGroup' => 'main',
267
                    'position' => 1,
268
                    'fieldType' => 'ezstring',
269
                    'isTranslatable' => false,
270
                    'isRequired' => true,
271
                )
272
            ),
273
            new Content\Type\FieldDefinition(
274
                array(
275
                    'name' => array('eng-GB' => 'Data'),
276
                    'identifier' => 'data',
277
                    'fieldGroup' => 'main',
278
                    'position' => 2,
279
                    'fieldType' => $this->getTypeName(),
280
                    'isTranslatable' => false,
281
                    'isRequired' => true,
282
                    'fieldTypeConstraints' => $this->getTypeConstraints(),
283
                )
284
            ),
285
        );
286
287
        $handler = $this->getCustomHandler();
288
        $contentTypeHandler = $handler->contentTypeHandler();
289
290
        return $contentTypeHandler->create($createStruct);
291
    }
292
293
    /**
294
     * @depends testCreateContentType
295
     */
296
    public function testContentTypeField($contentType)
297
    {
298
        $this->assertSame(
299
            $this->getTypeName(),
300
            $contentType->fieldDefinitions[1]->fieldType
301
        );
302
    }
303
304
    /**
305
     * @depends testCreateContentType
306
     */
307
    public function testLoadContentTypeField()
308
    {
309
        $handler = $this->getCustomHandler();
310
        $contentTypeHandler = $handler->contentTypeHandler();
311
312
        return $contentTypeHandler->load(self::$contentTypeId);
313
    }
314
315
    /**
316
     * @depends testLoadContentTypeField
317
     */
318
    public function testLoadContentTypeFieldType($contentType)
319
    {
320
        $this->assertSame(
321
            $this->getTypeName(),
322
            $contentType->fieldDefinitions[1]->fieldType
323
        );
324
325
        return $contentType->fieldDefinitions[1];
326
    }
327
328
    /**
329
     * @depends testLoadContentTypeFieldType
330
     * @dataProvider getFieldDefinitionData
331
     */
332
    public function testLoadContentTypeFieldData($name, $value, $field)
333
    {
334
        $this->assertEquals(
335
            $value,
336
            $field->$name
337
        );
338
    }
339
340
    /**
341
     * @depends testLoadContentTypeField
342
     */
343
    public function testCreateContent($contentType)
344
    {
345
        $handler = $this->getCustomHandler();
346
347
        $content = $this->createContent($contentType, $this->getInitialValue());
348
349
        self::$contentId = $content->versionInfo->contentInfo->id;
350
        self::$contentVersion = $content->versionInfo->contentInfo->currentVersionNo;
0 ignored issues
show
Documentation Bug introduced by
The property $contentVersion was declared of type string, but $content->versionInfo->c...tInfo->currentVersionNo is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
351
352
        $this->postCreationHook($handler, $content);
0 ignored issues
show
Compatibility introduced by
$handler of type object<eZ\Publish\SPI\Persistence\Handler> is not a sub-type of object<eZ\Publish\Core\P...istence\Legacy\Handler>. It seems like you assume a concrete implementation of the interface eZ\Publish\SPI\Persistence\Handler to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
353
354
        return $content;
355
    }
356
357
    /**
358
     * Creates content of the given $contentType with $fieldValue in
359
     * $languageCode.
360
     *
361
     * @param Type $contentType
362
     * @param mixed $fieldValue
363
     * @param string $languageCode
364
     *
365
     * @return Content
366
     */
367
    protected function createContent(Type $contentType, $fieldValue, $languageCode = 'eng-GB')
368
    {
369
        $createStruct = new Content\CreateStruct(
370
            array(
371
                'name' => array($languageCode => 'Test object'),
372
                'typeId' => $contentType->id,
373
                'sectionId' => 1,
374
                'ownerId' => 14,
375
                'locations' => array(
376
                    new Content\Location\CreateStruct(
377
                        array(
378
                            'parentId' => 2,
379
                            'remoteId' => 'sindelfingen',
380
                        )
381
                    ),
382
                ),
383
                // Language with id=2 is eng-US
384
                // This is probably a mistake, as the fields are given with eng-GB, but it has a nice
385
                // side effect of testing creation with empty value.
386
                // TODO: change to eng-GB (8) and/or find a more obvious way to test creation with empty value
387
                'initialLanguageId' => 2,
388
                'remoteId' => microtime(),
389
                'modified' => time(),
390
                'fields' => array(
391
                    new Content\Field(
392
                        array(
393
                            'type' => 'ezstring',
394
                            'languageCode' => $languageCode,
395
                            'fieldDefinitionId' => $contentType->fieldDefinitions[0]->id,
396
                            'value' => new Content\FieldValue(
397
                                array(
398
                                    'data' => 'This is just a test object',
399
                                    'sortKey' => 'this is just a test object',
400
                                )
401
                            ),
402
                        )
403
                    ),
404
                    new Content\Field(
405
                        array(
406
                            'type' => $this->getTypeName(),
407
                            'languageCode' => $languageCode,
408
                            'fieldDefinitionId' => $contentType->fieldDefinitions[1]->id,
409
                            'value' => $fieldValue,
410
                        )
411
                    ),
412
                ),
413
            )
414
        );
415
416
        $handler = $this->getCustomHandler();
417
        $contentHandler = $handler->contentHandler();
418
419
        return $contentHandler->create($createStruct);
420
    }
421
422
    /**
423
     * @depends testCreateContent
424
     */
425
    public function testCreatedFieldType($content)
426
    {
427
        $this->assertSame(
428
            $this->getTypeName(),
429
            $content->fields[1]->type
430
        );
431
432
        return $content->fields[1];
433
    }
434
435
    /**
436
     * @depends testCreateContent
437
     */
438
    public function testLoadField()
439
    {
440
        $handler = $this->getCustomHandler();
441
442
        $contentHandler = $handler->contentHandler();
443
444
        return $contentHandler->load(self::$contentId, self::$contentVersion);
445
    }
446
447
    /**
448
     * @depends testLoadField
449
     */
450
    public function testLoadFieldType($content)
451
    {
452
        $this->assertSame(
453
            $this->getTypeName(),
454
            $content->fields[1]->type
455
        );
456
457
        return $content->fields[1];
458
    }
459
460
    /**
461
     * @depends testLoadFieldType
462
     */
463
    public function testLoadExternalData($field)
464
    {
465
        $this->assertLoadedFieldDataCorrect($field);
466
    }
467
468
    /**
469
     * @depends testLoadFieldType
470
     */
471
    public function testUpdateField($field)
472
    {
473
        $field->value = $this->getUpdatedValue();
474
475
        return $this->updateContent(self::$contentId, self::$contentVersion, $field);
476
    }
477
478
    /**
479
     * Performs an update on $contentId in $contentVersion setting $field.
480
     *
481
     * @param mixed $contentId
482
     * @param mixed $contentVersion
483
     * @param Field $field
484
     *
485
     * @return Content
486
     */
487
    protected function updateContent($contentId, $contentVersion, Field $field)
488
    {
489
        $handler = $this->getCustomHandler();
490
491
        $field->value = $this->getUpdatedValue();
492
        $updateStruct = new UpdateStruct(
493
            array(
494
                'creatorId' => 14,
495
                'modificationDate' => time(),
496
                'initialLanguageId' => 2,
497
                'fields' => array(
498
                    $field,
499
                ),
500
            )
501
        );
502
503
        $contentHandler = $handler->contentHandler();
504
505
        return $contentHandler->updateContent($contentId, $contentVersion, $updateStruct);
506
    }
507
508
    /**
509
     * @depends testUpdateField
510
     */
511
    public function testUpdateFieldType($content)
512
    {
513
        $this->assertSame(
514
            $this->getTypeName(),
515
            $content->fields[1]->type
516
        );
517
518
        return $content->fields[1];
519
    }
520
521
    /**
522
     * @depends testUpdateFieldType
523
     */
524
    public function testUpdateExternalData($field)
525
    {
526
        $this->assertUpdatedFieldDataCorrect($field);
527
    }
528
529
    /**
530
     * @depends testUpdateField
531
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
532
     */
533
    public function testDeleteField($content)
534
    {
535
        $handler = $this->getCustomHandler();
536
        $contentHandler = $handler->contentHandler();
537
538
        $this->deleteContent($content);
539
540
        $this->assertDeletedFieldDataCorrect($content);
541
542
        $contentHandler->load(
543
            $content->versionInfo->contentInfo->id,
544
            $content->versionInfo->versionNo
545
        );
546
    }
547
548
    /**
549
     * Deletes the given $content.
550
     *
551
     * @param Content $content
552
     */
553
    protected function deleteContent(Content $content)
554
    {
555
        $handler = $this->getCustomHandler();
556
        $contentHandler = $handler->contentHandler();
557
558
        $contentHandler->removeRawContent(
559
            $content->versionInfo->contentInfo->id
560
        );
561
    }
562
563 View Code Duplication
    protected function getContainer()
564
    {
565
        $config = include __DIR__ . '/../../../../../config.php';
566
        $installDir = $config['install_dir'];
567
568
        $containerBuilder = new ContainerBuilder();
569
        $settingsPath = $installDir . '/eZ/Publish/Core/settings/';
570
        $loader = new YamlFileLoader($containerBuilder, new FileLocator($settingsPath));
571
572
        $loader->load('fieldtypes.yml');
573
        $loader->load('io.yml');
574
        $loader->load('repository.yml');
575
        $loader->load('repository/inner.yml');
576
        $loader->load('repository/signalslot.yml');
577
        $loader->load('repository/siteaccessaware.yml');
578
        $loader->load('fieldtype_external_storages.yml');
579
        $loader->load('storage_engines/common.yml');
580
        $loader->load('storage_engines/shortcuts.yml');
581
        $loader->load('storage_engines/legacy.yml');
582
        $loader->load('search_engines/legacy.yml');
583
        $loader->load('storage_engines/cache.yml');
584
        $loader->load('settings.yml');
585
        $loader->load('fieldtype_services.yml');
586
        $loader->load('utils.yml');
587
        $loader->load('tests/common.yml');
588
        $loader->load('policies.yml');
589
590
        $containerBuilder->setParameter('ezpublish.kernel.root_dir', $installDir);
591
592
        $containerBuilder->setParameter(
593
            'legacy_dsn',
594
            $this->getDsn()
595
        );
596
597
        $this->setAllServicesPublic($containerBuilder);
598
599
        $containerBuilder->compile();
600
601
        return $containerBuilder;
602
    }
603
604
    /**
605
     * Returns the Handler.
606
     *
607
     * @param string $identifier
608
     * @param \eZ\Publish\SPI\FieldType\FieldType $fieldType
609
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\FieldValue\Converter $fieldValueConverter
610
     * @param \eZ\Publish\SPI\FieldType\FieldStorage $externalStorage
611
     *
612
     * @return \eZ\Publish\SPI\Persistence\Handler
613
     */
614
    protected function getHandler($identifier, $fieldType, $fieldValueConverter, $externalStorage)
615
    {
616
        /** @var \eZ\Publish\Core\Persistence\FieldTypeRegistry $fieldTypeRegistry */
617
        $fieldTypeRegistry = self::$container->get('ezpublish.persistence.field_type_registry');
618
        /** @var \eZ\Publish\Core\Persistence\Legacy\Content\FieldValue\ConverterRegistry $converterRegistry */
619
        $converterRegistry = self::$container->get('ezpublish.persistence.legacy.field_value_converter.registry');
620
        /** @var \eZ\Publish\Core\Persistence\Legacy\Content\StorageRegistry $storageRegistry */
621
        $storageRegistry = self::$container->get('ezpublish.persistence.external_storage_registry');
622
623
        $textLineFieldType = new \eZ\Publish\Core\FieldType\TextLine\Type();
624
        $textLineFieldType->setTransformationProcessor($this->getTransformationProcessor());
625
        $textLineFieldValueConverter = new Legacy\Content\FieldValue\Converter\TextLineConverter();
626
627
        $fieldTypeRegistry->register('ezstring', $textLineFieldType);
628
        $converterRegistry->register('ezstring', $textLineFieldValueConverter);
629
630
        $fieldTypeRegistry->register($identifier, $fieldType);
631
        $converterRegistry->register($identifier, $fieldValueConverter);
632
        $storageRegistry->register($identifier, $externalStorage);
633
634
        return self::$container->get('ezpublish.spi.persistence.legacy');
635
    }
636
637
    /**
638
     * Overrides all services to be public.
639
     *
640
     * It is a workaround to the change in Symfony 4 which makes all services private by default.
641
     * Our integration tests are not prepared for this as they get services directly from the Container.
642
     *
643
     * Inspired by {@link \Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TestServiceContainerWeakRefPass}
644
     *
645
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $containerBuilder
646
     */
647 View Code Duplication
    private function setAllServicesPublic(ContainerBuilder $containerBuilder): void
648
    {
649
        $definitions = $containerBuilder->getDefinitions();
650
651
        foreach ($definitions as $id => $definition) {
652
            if (
653
                $id && '.' !== $id[0]
654
                && (!$definition->isPublic() || $definition->isPrivate())
655
                && !$definition->getErrors()
656
                && !$definition->isAbstract()
657
            ) {
658
                $definition->setPrivate(false);
659
                $definition->setPublic(true);
660
            }
661
        }
662
663
        $aliases = $containerBuilder->getAliases();
664
        foreach ($aliases as $id => $alias) {
665
            if ($id && '.' !== $id[0] && (!$alias->isPublic() || $alias->isPrivate())) {
666
                while (isset($aliases[$target = (string) $alias])) {
667
                    $alias = $aliases[$target];
668
                }
669
                if (
670
                    isset($definitions[$target])
671
                    && !$definitions[$target]->getErrors()
672
                    && !$definitions[$target]->isAbstract()
673
                ) {
674
675
                    $definition->setPrivate(false);
0 ignored issues
show
Bug introduced by
The variable $definition seems to be defined by a foreach iteration on line 651. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
676
                    $definition->setPublic(true);
677
                }
678
            }
679
        }
680
    }
681
}
682