ContainerTest.php 38 KB
Newer Older
1
2
3
4
5
6
7
8
9
<?php

/**
 * @file
 * Contains \Drupal\Tests\Component\DependencyInjection\ContainerTest.
 */

namespace Drupal\Tests\Component\DependencyInjection;

10
use Drupal\Component\Utility\Crypt;
11
use PHPUnit\Framework\TestCase;
12
13
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
14
15
16
17
18
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
19
20
21
22
23
24
use Prophecy\Argument;

/**
 * @coversDefaultClass \Drupal\Component\DependencyInjection\Container
 * @group DependencyInjection
 */
25
class ContainerTest extends TestCase {
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

  /**
   * The tested container.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $container;

  /**
   * The container definition used for the test.
   *
   * @var array
   */
  protected $containerDefinition;

  /**
   * The container class to be tested.
   *
   * @var bool
   */
  protected $containerClass;

  /**
   * Whether the container uses the machine-optimized format or not.
   *
   * @var bool
   */
  protected $machineFormat;

  /**
   * {@inheritdoc}
   */
58
  protected function setUp(): void {
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    $this->machineFormat = TRUE;
    $this->containerClass = '\Drupal\Component\DependencyInjection\Container';
    $this->containerDefinition = $this->getMockContainerDefinition();
    $this->container = new $this->containerClass($this->containerDefinition);
  }

  /**
   * Tests that passing a non-supported format throws an InvalidArgumentException.
   *
   * @covers ::__construct
   */
  public function testConstruct() {
    $container_definition = $this->getMockContainerDefinition();
    $container_definition['machine_format'] = !$this->machineFormat;
73
    $this->expectException(InvalidArgumentException::class);
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    $container = new $this->containerClass($container_definition);
  }

  /**
   * Tests that Container::getParameter() works properly.
   *
   * @covers ::getParameter
   */
  public function testGetParameter() {
    $this->assertEquals($this->containerDefinition['parameters']['some_config'], $this->container->getParameter('some_config'), 'Container parameter matches for %some_config%.');
    $this->assertEquals($this->containerDefinition['parameters']['some_other_config'], $this->container->getParameter('some_other_config'), 'Container parameter matches for %some_other_config%.');
  }

  /**
   * Tests that Container::getParameter() works properly for non-existing
   * parameters.
   *
   * @covers ::getParameter
   * @covers ::getParameterAlternatives
   * @covers ::getAlternatives
   */
  public function testGetParameterIfNotFound() {
96
    $this->expectException(ParameterNotFoundException::class);
97
98
99
100
101
102
103
104
105
    $this->container->getParameter('parameter_that_does_not_exist');
  }

  /**
   * Tests that Container::getParameter() works properly for NULL parameters.
   *
   * @covers ::getParameter
   */
  public function testGetParameterIfNotFoundBecauseNull() {
106
    $this->expectException(ParameterNotFoundException::class);
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    $this->container->getParameter(NULL);
  }

  /**
   * Tests that Container::hasParameter() works properly.
   *
   * @covers ::hasParameter
   */
  public function testHasParameter() {
    $this->assertTrue($this->container->hasParameter('some_config'), 'Container parameters include %some_config%.');
    $this->assertFalse($this->container->hasParameter('some_config_not_exists'), 'Container parameters do not include %some_config_not_exists%.');
  }

  /**
   * Tests that Container::setParameter() in an unfrozen case works properly.
   *
   * @covers ::setParameter
   */
  public function testSetParameterWithUnfrozenContainer() {
    $container_definition = $this->containerDefinition;
    $container_definition['frozen'] = FALSE;
    $this->container = new $this->containerClass($container_definition);
    $this->container->setParameter('some_config', 'new_value');
    $this->assertEquals('new_value', $this->container->getParameter('some_config'), 'Container parameters can be set.');
  }

  /**
   * Tests that Container::setParameter() in a frozen case works properly.
   *
   * @covers ::setParameter
   */
  public function testSetParameterWithFrozenContainer() {
    $this->container = new $this->containerClass($this->containerDefinition);
140
    $this->expectException(LogicException::class);
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    $this->container->setParameter('some_config', 'new_value');
  }

  /**
   * Tests that Container::get() works properly.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGet() {
    $container = $this->container->get('service_container');
    $this->assertSame($this->container, $container, 'Container can be retrieved from itself.');

    // Retrieve services of the container.
    $other_service_class = $this->containerDefinition['services']['other.service']['class'];
    $other_service = $this->container->get('other.service');
157
    $this->assertInstanceOf($other_service_class, $other_service);
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

    $some_parameter = $this->containerDefinition['parameters']['some_config'];
    $some_other_parameter = $this->containerDefinition['parameters']['some_other_config'];

    $service = $this->container->get('service.provider');

    $this->assertEquals($other_service, $service->getSomeOtherService(), '@other.service was injected via constructor.');
    $this->assertEquals($some_parameter, $service->getSomeParameter(), '%some_config% was injected via constructor.');
    $this->assertEquals($this->container, $service->getContainer(), 'Container was injected via setter injection.');
    $this->assertEquals($some_other_parameter, $service->getSomeOtherParameter(), '%some_other_config% was injected via setter injection.');
    $this->assertEquals($service->_someProperty, 'foo', 'Service has added properties.');
  }

  /**
   * Tests that Container::get() for non-shared services works properly.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForNonSharedService() {
    $service = $this->container->get('non_shared_service');
    $service2 = $this->container->get('non_shared_service');

    $this->assertNotSame($service, $service2, 'Non shared services are always re-instantiated.');
  }

  /**
   * Tests that Container::get() works properly for class from parameters.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForClassFromParameter() {
    $container_definition = $this->containerDefinition;
    $container_definition['frozen'] = FALSE;
    $container = new $this->containerClass($container_definition);

    $other_service_class = $this->containerDefinition['parameters']['some_parameter_class'];
    $other_service = $container->get('other.service_class_from_parameter');
197
    $this->assertInstanceOf($other_service_class, $other_service);
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
  }

  /**
   * Tests that Container::set() works properly.
   *
   * @covers ::set
   */
  public function testSet() {
    $this->assertNull($this->container->get('new_id', ContainerInterface::NULL_ON_INVALID_REFERENCE));
    $mock_service = new MockService();
    $this->container->set('new_id', $mock_service);

    $this->assertSame($mock_service, $this->container->get('new_id'), 'A manual set service works as expected.');
  }

  /**
   * Tests that Container::has() works properly.
   *
   * @covers ::has
   */
  public function testHas() {
    $this->assertTrue($this->container->has('other.service'));
    $this->assertFalse($this->container->has('another.service'));

    // Set the service manually, ensure that its also respected.
    $mock_service = new MockService();
    $this->container->set('another.service', $mock_service);
    $this->assertTrue($this->container->has('another.service'));
  }

228
229
230
231
232
233
234
235
236
237
238
  /**
   * Tests that Container::has() for aliased services works properly.
   *
   * @covers ::has
   */
  public function testHasForAliasedService() {
    $service = $this->container->has('service.provider');
    $aliased_service = $this->container->has('service.provider_alias');
    $this->assertSame($service, $aliased_service);
  }

239
240
241
242
243
244
  /**
   * Tests that Container::get() for circular dependencies works properly.
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForCircularServices() {
245
    $this->expectException(ServiceCircularReferenceException::class);
246
247
248
249
250
251
252
253
254
255
256
    $this->container->get('circular_dependency');
  }

  /**
   * Tests that Container::get() for non-existent services works properly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::getAlternatives
   * @covers ::getServiceAlternatives
   */
257
  public function testGetForNonExistentService() {
258
    $this->expectException(ServiceNotFoundException::class);
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
    $this->container->get('service_not_exists');
  }

  /**
   * Tests that Container::get() for a serialized definition works properly.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForSerializedServiceDefinition() {
    $container_definition = $this->containerDefinition;
    $container_definition['services']['other.service'] = serialize($container_definition['services']['other.service']);
    $container = new $this->containerClass($container_definition);

    // Retrieve services of the container.
    $other_service_class = $this->containerDefinition['services']['other.service']['class'];
    $other_service = $container->get('other.service');
276
    $this->assertInstanceOf($other_service_class, $other_service);
277
278
279
280
281
282
283
284
285
286
287
288

    $service = $container->get('service.provider');
    $this->assertEquals($other_service, $service->getSomeOtherService(), '@other.service was injected via constructor.');
  }

  /**
   * Tests that Container::get() for non-existent parameters works properly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
289
  public function testGetForNonExistentParameterDependency() {
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
    $service = $this->container->get('service_parameter_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE);
    $this->assertNull($service, 'Service is NULL.');
  }

  /**
   * Tests Container::get() with an exception due to missing parameter on the second call.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testGetForParameterDependencyWithExceptionOnSecondCall() {
    $service = $this->container->get('service_parameter_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE);
    $this->assertNull($service, 'Service is NULL.');

    // Reset the service.
    $this->container->set('service_parameter_not_exists', NULL);
307
    $this->expectException(InvalidArgumentException::class);
308
309
310
311
312
313
314
315
316
317
    $this->container->get('service_parameter_not_exists');
  }

  /**
   * Tests that Container::get() for non-existent parameters works properly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
318
  public function testGetForNonExistentParameterDependencyWithException() {
319
    $this->expectException(InvalidArgumentException::class);
320
321
322
323
324
325
326
327
328
329
    $this->container->get('service_parameter_not_exists');
  }

  /**
   * Tests that Container::get() for non-existent dependencies works properly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
330
  public function testGetForNonExistentServiceDependency() {
331
332
333
334
335
336
337
338
339
340
341
342
    $service = $this->container->get('service_dependency_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE);
    $this->assertNull($service, 'Service is NULL.');
  }

  /**
   * Tests that Container::get() for non-existent dependencies works properly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   * @covers ::getAlternatives
   */
343
  public function testGetForNonExistentServiceDependencyWithException() {
344
    $this->expectException(ServiceNotFoundException::class);
345
346
347
348
349
350
351
352
353
    $this->container->get('service_dependency_not_exists');
  }

  /**
   * Tests that Container::get() for non-existent services works properly.
   *
   * @covers ::get
   * @covers ::createService
   */
354
  public function testGetForNonExistentServiceWhenUsingNull() {
355
356
357
358
359
360
361
362
    $this->assertNull($this->container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does not throw exception.');
  }

  /**
   * Tests that Container::get() for NULL service works properly.
   * @covers ::get
   * @covers ::createService
   */
363
  public function testGetForNonExistentNULLService() {
364
    $this->expectException(ServiceNotFoundException::class);
365
366
367
368
369
370
371
372
373
    $this->container->get(NULL);
  }

  /**
   * Tests multiple Container::get() calls for non-existing dependencies work.
   *
   * @covers ::get
   * @covers ::createService
   */
374
  public function testGetForNonExistentServiceMultipleTimes() {
375
376
377
378
379
380
381
382
383
384
385
386
387
    $container = new $this->containerClass();

    $this->assertNull($container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does not throw exception.');
    $this->assertNull($container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does not throw exception on second call.');
  }

  /**
   * Tests multiple Container::get() calls with exception on the second time.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::getAlternatives
   */
388
  public function testGetForNonExistentServiceWithExceptionOnSecondCall() {
389
    $this->assertNull($this->container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does nto throw exception.');
390
    $this->expectException(ServiceNotFoundException::class);
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
    $this->container->get('service_not_exists');
  }

  /**
   * Tests that Container::get() for aliased services works properly.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForAliasedService() {
    $service = $this->container->get('service.provider');
    $aliased_service = $this->container->get('service.provider_alias');
    $this->assertSame($service, $aliased_service);
  }

  /**
   * Tests that Container::get() for synthetic services works - if defined.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForSyntheticService() {
    $synthetic_service = new \stdClass();
    $this->container->set('synthetic', $synthetic_service);
    $test_service = $this->container->get('synthetic');
    $this->assertSame($synthetic_service, $test_service);
  }

  /**
   * Tests that Container::get() for synthetic services throws an Exception if not defined.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForSyntheticServiceWithException() {
426
    $this->expectException(RuntimeException::class);
427
428
429
430
431
432
433
434
435
436
    $this->container->get('synthetic');
  }

  /**
   * Tests that Container::get() for services with file includes works.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetWithFileInclude() {
437
    $this->container->get('container_test_file_service_test');
438
439
440
441
442
443
444
445
446
447
448
449
    $this->assertTrue(function_exists('container_test_file_service_test_service_function'));
    $this->assertEquals('Hello Container', container_test_file_service_test_service_function());
  }

  /**
   * Tests that Container::get() for various arguments lengths works.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testGetForInstantiationWithVariousArgumentLengths() {
450
    $args = [];
451
    for ($i = 0; $i < 12; $i++) {
452
      $instantiation_service = $this->container->get('service_test_instantiation_' . $i);
453
454
455
456
457
458
459
460
461
462
463
464
      $this->assertEquals($args, $instantiation_service->getArguments());
      $args[] = 'arg_' . $i;
    }
  }

  /**
   * Tests that Container::get() for wrong factories works correctly.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForWrongFactory() {
465
    $this->expectException(RuntimeException::class);
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    $this->container->get('wrong_factory');
  }

  /**
   * Tests Container::get() for factories via services (Symfony 2.7.0).
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForFactoryService() {
    $factory_service = $this->container->get('factory_service');
    $factory_service_class = $this->container->getParameter('factory_service_class');
    $this->assertInstanceOf($factory_service_class, $factory_service);
  }

  /**
   * Tests that Container::get() for factories via class works (Symfony 2.7.0).
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForFactoryClass() {
    $service = $this->container->get('service.provider');
489
    $factory_service = $this->container->get('factory_class');
490
491
492
493
494
495
496
497
498
499
500
501
502

    $this->assertInstanceOf(get_class($service), $factory_service);
    $this->assertEquals('bar', $factory_service->getSomeParameter(), 'Correct parameter was passed via the factory class instantiation.');
    $this->assertEquals($this->container, $factory_service->getContainer(), 'Container was injected via setter injection.');
  }

  /**
   * Tests that Container::get() for configurable services throws an Exception.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForConfiguratorWithException() {
503
    $this->expectException(InvalidArgumentException::class);
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
    $this->container->get('configurable_service_exception');
  }

  /**
   * Tests that Container::get() for configurable services works.
   *
   * @covers ::get
   * @covers ::createService
   */
  public function testGetForConfigurator() {
    $container = $this->container;

    // Setup a configurator.
    $configurator = $this->prophesize('\Drupal\Tests\Component\DependencyInjection\MockConfiguratorInterface');
    $configurator->configureService(Argument::type('object'))
      ->shouldBeCalled(1)
520
      ->will(function ($args) use ($container) {
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
        $args[0]->setContainer($container);
      });
    $container->set('configurator', $configurator->reveal());

    // Test that the configurator worked.
    $service = $container->get('configurable_service');
    $this->assertSame($container, $service->getContainer(), 'Container was injected via configurator.');
  }

  /**
   * Tests that private services work correctly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testResolveServicesAndParametersForPrivateService() {
    $service = $this->container->get('service_using_private');
    $private_service = $service->getSomeOtherService();
    $this->assertEquals($private_service->getSomeParameter(), 'really_private_lama', 'Private was found successfully.');

    // Test that sharing the same private services works.
    $service = $this->container->get('another_service_using_private');
    $another_private_service = $service->getSomeOtherService();
    $this->assertNotSame($private_service, $another_private_service, 'Private service is not shared.');
    $this->assertEquals($private_service->getSomeParameter(), 'really_private_lama', 'Private was found successfully.');
  }

  /**
   * Tests that private service sharing works correctly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testResolveServicesAndParametersForSharedPrivateService() {
    $service = $this->container->get('service_using_shared_private');
    $private_service = $service->getSomeOtherService();
    $this->assertEquals($private_service->getSomeParameter(), 'really_private_lama', 'Private was found successfully.');

    // Test that sharing the same private services works.
    $service = $this->container->get('another_service_using_shared_private');
    $same_private_service = $service->getSomeOtherService();
    $this->assertSame($private_service, $same_private_service, 'Private service is shared.');
    $this->assertEquals($private_service->getSomeParameter(), 'really_private_lama', 'Private was found successfully.');
  }

  /**
   * Tests that services with an array of arguments work correctly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testResolveServicesAndParametersForArgumentsUsingDeepArray() {
    $service = $this->container->get('service_using_array');
    $other_service = $this->container->get('other.service');
    $this->assertEquals($other_service, $service->getSomeOtherService(), '@other.service was injected via constructor.');
  }

  /**
   * Tests that services that are optional work correctly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testResolveServicesAndParametersForOptionalServiceDependencies() {
    $service = $this->container->get('service_with_optional_dependency');
    $this->assertNull($service->getSomeOtherService(), 'other service was NULL was expected.');
  }

  /**
   * Tests that an invalid argument throw an Exception.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testResolveServicesAndParametersForInvalidArgument() {
601
    $this->expectException(InvalidArgumentException::class);
602
603
604
605
606
607
608
609
610
611
612
613
614
    $this->container->get('invalid_argument_service');
  }

  /**
   * Tests that invalid arguments throw an Exception.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testResolveServicesAndParametersForInvalidArguments() {
    // In case the machine-optimized format is not used, we need to simulate the
    // test failure.
615
    $this->expectException(InvalidArgumentException::class);
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
    if (!$this->machineFormat) {
      throw new InvalidArgumentException('Simulating the test failure.');
    }
    $this->container->get('invalid_arguments_service');
  }

  /**
   * Tests that a parameter that points to a service works correctly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testResolveServicesAndParametersForServiceInstantiatedFromParameter() {
    $service = $this->container->get('service.provider');
    $test_service = $this->container->get('service_with_parameter_service');
    $this->assertSame($service, $test_service->getSomeOtherService(), 'Service was passed via parameter.');
  }

  /**
   * Tests that Container::initialized works correctly.
   *
   * @covers ::initialized
   */
  public function testInitialized() {
    $this->assertFalse($this->container->initialized('late.service'), 'Late service is not initialized.');
    $this->container->get('late.service');
    $this->assertTrue($this->container->initialized('late.service'), 'Late service is initialized after it was retrieved once.');
  }

  /**
   * Tests that Container::initialized works correctly for aliases.
   *
   * @covers ::initialized
   */
  public function testInitializedForAliases() {
    $this->assertFalse($this->container->initialized('late.service_alias'), 'Late service is not initialized.');
    $this->container->get('late.service');
    $this->assertTrue($this->container->initialized('late.service_alias'), 'Late service is initialized after it was retrieved once.');
  }

  /**
   * Tests that Container::getServiceIds() works properly.
   *
   * @covers ::getServiceIds
   */
  public function testGetServiceIds() {
    $service_definition_keys = array_keys($this->containerDefinition['services']);
    $this->assertEquals($service_definition_keys, $this->container->getServiceIds(), 'Retrieved service IDs match definition.');

    $mock_service = new MockService();
    $this->container->set('bar', $mock_service);
    $this->container->set('service.provider', $mock_service);
    $service_definition_keys[] = 'bar';

    $this->assertEquals($service_definition_keys, $this->container->getServiceIds(), 'Retrieved service IDs match definition after setting new services.');
  }

674
675
676
677
678
679
680
681
682
683
684
  /**
   * Tests that raw type services arguments are resolved correctly.
   *
   * @covers ::get
   * @covers ::createService
   * @covers ::resolveServicesAndParameters
   */
  public function testResolveServicesAndParametersForRawArgument() {
    $this->assertEquals(['ccc'], $this->container->get('service_with_raw_argument')->getArguments());
  }

685
686
687
688
689
690
691
692
  /**
   * Gets a mock container definition.
   *
   * @return array
   *   Associated array with parameters and services.
   */
  protected function getMockContainerDefinition() {
    $fake_service = new \stdClass();
693
    $parameters = [];
694
695
696
697
698
699
700
701
    $parameters['some_parameter_class'] = get_class($fake_service);
    $parameters['some_private_config'] = 'really_private_lama';
    $parameters['some_config'] = 'foo';
    $parameters['some_other_config'] = 'lama';
    $parameters['factory_service_class'] = get_class($fake_service);
    // Also test alias resolving.
    $parameters['service_from_parameter'] = $this->getServiceCall('service.provider_alias');

702
703
    $services = [];
    $services['service_container'] = [
704
      'class' => '\Drupal\service_container\DependencyInjection\Container',
705
706
    ];
    $services['other.service'] = [
707
      'class' => get_class($fake_service),
708
    ];
709

710
    $services['non_shared_service'] = [
711
712
      'class' => get_class($fake_service),
      'shared' => FALSE,
713
    ];
714

715
    $services['other.service_class_from_parameter'] = [
716
      'class' => $this->getParameterCall('some_parameter_class'),
717
718
    ];
    $services['late.service'] = [
719
      'class' => get_class($fake_service),
720
721
    ];
    $services['service.provider'] = [
722
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
723
      'arguments' => $this->getCollection([
724
725
        $this->getServiceCall('other.service'),
        $this->getParameterCall('some_config'),
726
727
728
      ]),
      'properties' => $this->getCollection(['_someProperty' => 'foo']),
      'calls' => [
729
730
731
732
733
734
735
736
737
738
739
740
        [
          'setContainer',
          $this->getCollection([
            $this->getServiceCall('service_container'),
          ]),
        ],
        [
          'setOtherConfigParameter',
          $this->getCollection([
            $this->getParameterCall('some_other_config'),
          ]),
        ],
741
      ],
742
      'priority' => 0,
743
    ];
744
745

    // Test private services.
746
    $private_service = [
747
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
748
      'arguments' => $this->getCollection([
749
750
        $this->getServiceCall('other.service'),
        $this->getParameterCall('some_private_config'),
751
      ]),
752
      'public' => FALSE,
753
    ];
754

755
    $services['service_using_private'] = [
756
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
757
      'arguments' => $this->getCollection([
758
759
        $this->getPrivateServiceCall(NULL, $private_service),
        $this->getParameterCall('some_config'),
760
761
762
      ]),
    ];
    $services['another_service_using_private'] = [
763
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
764
      'arguments' => $this->getCollection([
765
766
        $this->getPrivateServiceCall(NULL, $private_service),
        $this->getParameterCall('some_config'),
767
768
      ]),
    ];
769
770
771
772

    // Test shared private services.
    $id = 'private_service_shared_1';

773
    $services['service_using_shared_private'] = [
774
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
775
      'arguments' => $this->getCollection([
776
777
        $this->getPrivateServiceCall($id, $private_service, TRUE),
        $this->getParameterCall('some_config'),
778
779
780
      ]),
    ];
    $services['another_service_using_shared_private'] = [
781
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
782
      'arguments' => $this->getCollection([
783
784
        $this->getPrivateServiceCall($id, $private_service, TRUE),
        $this->getParameterCall('some_config'),
785
786
      ]),
    ];
787
788

    // Tests service with invalid argument.
789
    $services['invalid_argument_service'] = [
790
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
791
      'arguments' => $this->getCollection([
792
793
        // Test passing non-strings, too.
        1,
794
        (object) [
795
          'type' => 'invalid',
796
797
798
        ],
      ]),
    ];
799

800
    $services['invalid_arguments_service'] = [
801
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
802
      'arguments' => (object) [
803
        'type' => 'invalid',
804
805
      ],
    ];
806
807

    // Test service that needs deep-traversal.
808
    $services['service_using_array'] = [
809
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
810
811
      'arguments' => $this->getCollection([
        $this->getCollection([
812
          $this->getServiceCall('other.service'),
813
        ]),
814
        $this->getParameterCall('some_private_config'),
815
816
      ]),
    ];
817

818
    $services['service_with_optional_dependency'] = [
819
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
820
      'arguments' => $this->getCollection([
821
822
        $this->getServiceCall('service.does_not_exist', ContainerInterface::NULL_ON_INVALID_REFERENCE),
        $this->getParameterCall('some_private_config'),
823
      ]),
824

825
    ];
826

827
    $services['factory_service'] = [
828
      'class' => '\Drupal\service_container\ServiceContainer\ControllerInterface',
829
      'factory' => [
830
831
        $this->getServiceCall('service.provider'),
        'getFactoryMethod',
832
833
      ],
      'arguments' => $this->getCollection([
834
        $this->getParameterCall('factory_service_class'),
835
836
837
      ]),
    ];
    $services['factory_class'] = [
838
839
      'class' => '\Drupal\service_container\ServiceContainer\ControllerInterface',
      'factory' => '\Drupal\Tests\Component\DependencyInjection\MockService::getFactoryMethod',
840
      'arguments' => [
841
        '\Drupal\Tests\Component\DependencyInjection\MockService',
842
843
844
        [NULL, 'bar'],
      ],
      'calls' => [
845
846
847
848
849
850
        [
          'setContainer',
          $this->getCollection([
            $this->getServiceCall('service_container'),
          ]),
        ],
851
852
      ],
    ];
853

854
    $services['wrong_factory'] = [
855
      'class' => '\Drupal\service_container\ServiceContainer\ControllerInterface',
856
857
      'factory' => (object) ['I am not a factory, but I pretend to be.'],
    ];
858

859
    $services['circular_dependency'] = [
860
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
861
      'arguments' => $this->getCollection([
862
        $this->getServiceCall('circular_dependency'),
863
864
865
      ]),
    ];
    $services['synthetic'] = [
866
      'synthetic' => TRUE,
867
    ];
868
869
870
    // The file could have been named as a .php file. The reason it is a .data
    // file is that SimpleTest tries to load it. SimpleTest does not like such
    // fixtures and hence we use a neutral name like .data.
871
    $services['container_test_file_service_test'] = [
872
873
      'class' => '\stdClass',
      'file' => __DIR__ . '/Fixture/container_test_file_service_test_service_function.data',
874
    ];
875
876

    // Test multiple arguments.
877
    $args = [];
878
    for ($i = 0; $i < 12; $i++) {
879
      $services['service_test_instantiation_' . $i] = [
880
881
882
        'class' => '\Drupal\Tests\Component\DependencyInjection\MockInstantiationService',
        // Also test a collection that does not need resolving.
        'arguments' => $this->getCollection($args, FALSE),
883
      ];
884
885
886
      $args[] = 'arg_' . $i;
    }

887
    $services['service_parameter_not_exists'] = [
888
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
889
      'arguments' => $this->getCollection([
890
891
        $this->getServiceCall('service.provider'),
        $this->getParameterCall('not_exists'),
892
893
894
      ]),
    ];
    $services['service_dependency_not_exists'] = [
895
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
896
      'arguments' => $this->getCollection([
897
898
        $this->getServiceCall('service_not_exists'),
        $this->getParameterCall('some_config'),
899
900
      ]),
    ];
901

902
    $services['service_with_parameter_service'] = [
903
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
904
      'arguments' => $this->getCollection([
905
906
        $this->getParameterCall('service_from_parameter'),
        // Also test deep collections that don't need resolving.
907
        $this->getCollection([
908
          1,
909
910
911
        ], FALSE),
      ]),
    ];
912
913

    // To ensure getAlternatives() finds something.
914
    $services['service_not_exists_similar'] = [
915
      'synthetic' => TRUE,
916
    ];
917
918

    // Test configurator.
919
    $services['configurator'] = [
920
      'synthetic' => TRUE,
921
922
    ];
    $services['configurable_service'] = [
923
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
924
925
      'arguments' => [],
      'configurator' => [
926
        $this->getServiceCall('configurator'),
927
        'configureService',
928
929
930
      ],
    ];
    $services['configurable_service_exception'] = [
931
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
932
      'arguments' => [],
933
      'configurator' => 'configurator_service_test_does_not_exist',
934
    ];
935

936
937
938
939
940
941
    // Raw argument
    $services['service_with_raw_argument'] = [
      'class' => '\Drupal\Tests\Component\DependencyInjection\MockInstantiationService',
      'arguments' => $this->getCollection([$this->getRaw('ccc')]),
    ];

942
    $aliases = [];
943
944
945
    $aliases['service.provider_alias'] = 'service.provider';
    $aliases['late.service_alias'] = 'late.service';

946
    return [
947
948
949
950
951
      'aliases' => $aliases,
      'parameters' => $parameters,
      'services' => $services,
      'frozen' => TRUE,
      'machine_format' => $this->machineFormat,
952
    ];
953
954
955
956
957
958
  }

  /**
   * Helper function to return a service definition.
   */
  protected function getServiceCall($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
959
    return (object) [
960
961
962
      'type' => 'service',
      'id' => $id,
      'invalidBehavior' => $invalid_behavior,
963
    ];
964
965
966
  }

  /**
967
   * Helper function to return a parameter definition.
968
969
   */
  protected function getParameterCall($name) {
970
    return (object) [
971
972
      'type' => 'parameter',
      'name' => $name,
973
    ];
974
975
976
977
978
979
980
  }

  /**
   * Helper function to return a private service definition.
   */
  protected function getPrivateServiceCall($id, $service_definition, $shared = FALSE) {
    if (!$id) {
981
      $hash = Crypt::hashBase64(serialize($service_definition));
982
983
      $id = 'private__' . $hash;
    }
984
    return (object) [
985
986
987
988
      'type' => 'private_service',
      'id' => $id,
      'value' => $service_definition,
      'shared' => $shared,
989
    ];
990
991
992
993
994
995
  }

  /**
   * Helper function to return a machine-optimized collection.
   */
  protected function getCollection($collection, $resolve = TRUE) {
996
    return (object) [
997
998
999
      'type' => 'collection',
      'value' => $collection,
      'resolve' => $resolve,
1000
    ];
1001
1002
  }

1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
  /**
   * Helper function to return a raw value definition.
   */
  protected function getRaw($value) {
    return (object) [
      'type' => 'raw',
      'value' => $value,
    ];
  }

1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
}

/**
 * Helper interface to test Container::get() with configurator.
 *
 * @group DependencyInjection
 */
interface MockConfiguratorInterface {

  /**
   * Configures a service.
   *
   * @param object $service
   *   The service to configure.
   */
  public function configureService($service);

}


/**
 * Helper class to test Container::get() method for varying number of parameters.
 *
 * @group DependencyInjection
 */
class MockInstantiationService {

  /**
   * @var mixed[]
   */
  protected $arguments;

  /**
   * Construct a mock instantiation service.
   */
  public function __construct() {
    $this->arguments = func_get_args();
  }

  /**
   * Return arguments injected into the service.
   *
   * @return mixed[]
   *   Return the passed arguments.
   */
  public function getArguments() {
    return $this->arguments;
  }

}


/**
 * Helper class to test Container::get() method.
 *
 * @group DependencyInjection
 */
class MockService {

  /**
1073
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
   */
  protected $container;

  /**
   * @var object
   */
  protected $someOtherService;

  /**
   * @var string
   */
  protected $someParameter;

  /**
   * @var string
   */
  protected $someOtherParameter;

  /**
   * Constructs a MockService object.
   *
   * @param object $some_other_service
   *   (optional) Another injected service.
   * @param string $some_parameter
   *   (optional) An injected parameter.
   */
  public function __construct($some_other_service = NULL, $some_parameter = NULL) {
    if (is_array($some_other_service)) {
      $some_other_service = $some_other_service[0];
    }
    $this->someOtherService = $some_other_service;
    $this->someParameter = $some_parameter;
  }

  /**
   * Sets the container object.
   *
1111
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
1112
1113
1114
1115
1116
1117
1118
1119
1120
   *   The container to inject via setter injection.
   */
  public function setContainer(ContainerInterface $container) {
    $this->container = $container;
  }

  /**
   * Gets the container object.
   *
1121
   * @return \Symfony\Component\DependencyInjection\ContainerInterface
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
   *   The internally set container.
   */
  public function getContainer() {
    return $this->container;
  }

  /**
   * Gets the someOtherService object.
   *
   * @return object
   *   The injected service.
   */
  public function getSomeOtherService() {
    return $this->someOtherService;
  }

  /**
   * Gets the someParameter property.
   *
   * @return string
   *   The injected parameter.
   */
  public function getSomeParameter() {
    return $this->someParameter;
  }

  /**
   * Sets the someOtherParameter property.
   *
   * @param string $some_other_parameter
   *   The setter injected parameter.
   */
  public function setOtherConfigParameter($some_other_parameter) {
    $this->someOtherParameter = $some_other_parameter;
  }

  /**
   * Gets the someOtherParameter property.
   *
   * @return string
   *   The injected parameter.
   */
  public function getSomeOtherParameter() {
    return $this->someOtherParameter;
  }

  /**
   * Provides a factory method to get a service.
   *
   * @param string $class
   *   The class name of the class to instantiate
   * @param array $arguments
   *   (optional) Arguments to pass to the new class.
   *
   * @return object
   *   The instantiated service object.
   */
1179
  public static function getFactoryMethod($class, $arguments = []) {
1180
1181
1182
1183
1184
1185
1186
    $r = new \ReflectionClass($class);
    $service = ($r->getConstructor() === NULL) ? $r->newInstance() : $r->newInstanceArgs($arguments);

    return $service;
  }

}