View source
<?php
namespace Drupal\Tests\Component\DependencyInjection;
use Drupal\Component\Utility\Crypt;
use Drupal\Tests\PhpUnitCompatibilityTrait;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
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;
use Prophecy\Argument;
class ContainerTest extends TestCase {
use PhpUnitCompatibilityTrait;
protected $container;
protected $containerDefinition;
protected $containerClass;
protected $machineFormat;
protected function setUp() : void {
$this->machineFormat = TRUE;
$this->containerClass = '\\Drupal\\Component\\DependencyInjection\\Container';
$this->containerDefinition = $this
->getMockContainerDefinition();
$this->container = new $this->containerClass($this->containerDefinition);
}
public function testConstruct() {
$container_definition = $this
->getMockContainerDefinition();
$container_definition['machine_format'] = !$this->machineFormat;
$this
->expectException(InvalidArgumentException::class);
$container = new $this->containerClass($container_definition);
}
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%.');
}
public function testGetParameterIfNotFound() {
$this
->expectException(ParameterNotFoundException::class);
$this->container
->getParameter('parameter_that_does_not_exist');
}
public function testGetParameterIfNotFoundBecauseNull() {
$this
->expectException(ParameterNotFoundException::class);
$this->container
->getParameter(NULL);
}
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%.');
}
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.');
}
public function testSetParameterWithFrozenContainer() {
$this->container = new $this->containerClass($this->containerDefinition);
$this
->expectException(LogicException::class);
$this->container
->setParameter('some_config', 'new_value');
}
public function testGet() {
$container = $this->container
->get('service_container');
$this
->assertSame($this->container, $container, 'Container can be retrieved from itself.');
$other_service_class = $this->containerDefinition['services']['other.service']['class'];
$other_service = $this->container
->get('other.service');
$this
->assertInstanceOf($other_service_class, $other_service);
$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('foo', $service->_someProperty, 'Service has added properties.');
}
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.');
}
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');
$this
->assertInstanceOf($other_service_class, $other_service);
}
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.');
}
public function testHas() {
$this
->assertTrue($this->container
->has('other.service'));
$this
->assertFalse($this->container
->has('another.service'));
$mock_service = new MockService();
$this->container
->set('another.service', $mock_service);
$this
->assertTrue($this->container
->has('another.service'));
}
public function testHasForAliasedService() {
$service = $this->container
->has('service.provider');
$aliased_service = $this->container
->has('service.provider_alias');
$this
->assertSame($service, $aliased_service);
}
public function testGetForCircularServices() {
$this
->expectException(ServiceCircularReferenceException::class);
$this->container
->get('circular_dependency');
}
public function testGetForNonExistentService() {
$this
->expectException(ServiceNotFoundException::class);
$this->container
->get('service_not_exists');
}
public function testGetForSerializedServiceDefinition() {
$container_definition = $this->containerDefinition;
$container_definition['services']['other.service'] = serialize($container_definition['services']['other.service']);
$container = new $this->containerClass($container_definition);
$other_service_class = $this->containerDefinition['services']['other.service']['class'];
$other_service = $container
->get('other.service');
$this
->assertInstanceOf($other_service_class, $other_service);
$service = $container
->get('service.provider');
$this
->assertEquals($other_service, $service
->getSomeOtherService(), '@other.service was injected via constructor.');
}
public function testGetForNonExistentParameterDependency() {
$service = $this->container
->get('service_parameter_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE);
$this
->assertNull($service, 'Service is NULL.');
}
public function testGetForParameterDependencyWithExceptionOnSecondCall() {
$service = $this->container
->get('service_parameter_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE);
$this
->assertNull($service, 'Service is NULL.');
$this->container
->set('service_parameter_not_exists', NULL);
$this
->expectException(InvalidArgumentException::class);
$this->container
->get('service_parameter_not_exists');
}
public function testGetForNonExistentParameterDependencyWithException() {
$this
->expectException(InvalidArgumentException::class);
$this->container
->get('service_parameter_not_exists');
}
public function testGetForNonExistentServiceDependency() {
$service = $this->container
->get('service_dependency_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE);
$this
->assertNull($service, 'Service is NULL.');
}
public function testGetForNonExistentServiceDependencyWithException() {
$this
->expectException(ServiceNotFoundException::class);
$this->container
->get('service_dependency_not_exists');
}
public function testGetForNonExistentServiceWhenUsingNull() {
$this
->assertNull($this->container
->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does not throw exception.');
}
public function testGetForNonExistentNULLService() {
$this
->expectException(ServiceNotFoundException::class);
$this->container
->get(NULL);
}
public function testGetForNonExistentServiceMultipleTimes() {
$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.');
}
public function testGetForNonExistentServiceWithExceptionOnSecondCall() {
$this
->assertNull($this->container
->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does nto throw exception.');
$this
->expectException(ServiceNotFoundException::class);
$this->container
->get('service_not_exists');
}
public function testGetForAliasedService() {
$service = $this->container
->get('service.provider');
$aliased_service = $this->container
->get('service.provider_alias');
$this
->assertSame($service, $aliased_service);
}
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);
}
public function testGetForSyntheticServiceWithException() {
$this
->expectException(RuntimeException::class);
$this->container
->get('synthetic');
}
public function testGetWithFileInclude() {
$this->container
->get('container_test_file_service_test');
$this
->assertTrue(function_exists('container_test_file_service_test_service_function'));
$this
->assertEquals('Hello Container', container_test_file_service_test_service_function());
}
public function testGetForInstantiationWithVariousArgumentLengths() {
$args = [];
for ($i = 0; $i < 12; $i++) {
$instantiation_service = $this->container
->get('service_test_instantiation_' . $i);
$this
->assertEquals($args, $instantiation_service
->getArguments());
$args[] = 'arg_' . $i;
}
}
public function testGetForWrongFactory() {
$this
->expectException(RuntimeException::class);
$this->container
->get('wrong_factory');
}
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);
}
public function testGetForFactoryClass() {
$service = $this->container
->get('service.provider');
$factory_service = $this->container
->get('factory_class');
$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.');
}
public function testGetForConfiguratorWithException() {
$this
->expectException(InvalidArgumentException::class);
$this->container
->get('configurable_service_exception');
}
public function testGetForConfigurator() {
$container = $this->container;
$configurator = $this
->prophesize('\\Drupal\\Tests\\Component\\DependencyInjection\\MockConfiguratorInterface');
$configurator
->configureService(Argument::type('object'))
->shouldBeCalled(1)
->will(function ($args) use ($container) {
$args[0]
->setContainer($container);
});
$container
->set('configurator', $configurator
->reveal());
$service = $container
->get('configurable_service');
$this
->assertSame($container, $service
->getContainer(), 'Container was injected via configurator.');
}
public function testResolveServicesAndParametersForPrivateService() {
$service = $this->container
->get('service_using_private');
$private_service = $service
->getSomeOtherService();
$this
->assertEquals('really_private_lama', $private_service
->getSomeParameter(), 'Private was found successfully.');
$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('really_private_lama', $private_service
->getSomeParameter(), 'Private was found successfully.');
}
public function testResolveServicesAndParametersForSharedPrivateService() {
$service = $this->container
->get('service_using_shared_private');
$private_service = $service
->getSomeOtherService();
$this
->assertEquals('really_private_lama', $private_service
->getSomeParameter(), 'Private was found successfully.');
$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('really_private_lama', $private_service
->getSomeParameter(), 'Private was found successfully.');
}
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.');
}
public function testResolveServicesAndParametersForOptionalServiceDependencies() {
$service = $this->container
->get('service_with_optional_dependency');
$this
->assertNull($service
->getSomeOtherService(), 'other service was NULL was expected.');
}
public function testResolveServicesAndParametersForInvalidArgument() {
$this
->expectException(InvalidArgumentException::class);
$this->container
->get('invalid_argument_service');
}
public function testResolveServicesAndParametersForInvalidArguments() {
$this
->expectException(InvalidArgumentException::class);
if (!$this->machineFormat) {
throw new InvalidArgumentException('Simulating the test failure.');
}
$this->container
->get('invalid_arguments_service');
}
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.');
}
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.');
}
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.');
}
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.');
}
public function testResolveServicesAndParametersForRawArgument() {
$this
->assertEquals([
'ccc',
], $this->container
->get('service_with_raw_argument')
->getArguments());
}
protected function getMockContainerDefinition() {
$fake_service = new \stdClass();
$parameters = [];
$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);
$parameters['service_from_parameter'] = $this
->getServiceCall('service.provider_alias');
$services = [];
$services['service_container'] = [
'class' => '\\Drupal\\service_container\\DependencyInjection\\Container',
];
$services['other.service'] = [
'class' => get_class($fake_service),
];
$services['non_shared_service'] = [
'class' => get_class($fake_service),
'shared' => FALSE,
];
$services['other.service_class_from_parameter'] = [
'class' => $this
->getParameterCall('some_parameter_class'),
];
$services['late.service'] = [
'class' => get_class($fake_service),
];
$services['service.provider'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getServiceCall('other.service'),
$this
->getParameterCall('some_config'),
]),
'properties' => $this
->getCollection([
'_someProperty' => 'foo',
]),
'calls' => [
[
'setContainer',
$this
->getCollection([
$this
->getServiceCall('service_container'),
]),
],
[
'setOtherConfigParameter',
$this
->getCollection([
$this
->getParameterCall('some_other_config'),
]),
],
],
'priority' => 0,
];
$private_service = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getServiceCall('other.service'),
$this
->getParameterCall('some_private_config'),
]),
'public' => FALSE,
];
$services['service_using_private'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getPrivateServiceCall(NULL, $private_service),
$this
->getParameterCall('some_config'),
]),
];
$services['another_service_using_private'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getPrivateServiceCall(NULL, $private_service),
$this
->getParameterCall('some_config'),
]),
];
$id = 'private_service_shared_1';
$services['service_using_shared_private'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getPrivateServiceCall($id, $private_service, TRUE),
$this
->getParameterCall('some_config'),
]),
];
$services['another_service_using_shared_private'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getPrivateServiceCall($id, $private_service, TRUE),
$this
->getParameterCall('some_config'),
]),
];
$services['invalid_argument_service'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
1,
(object) [
'type' => 'invalid',
],
]),
];
$services['invalid_arguments_service'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => (object) [
'type' => 'invalid',
],
];
$services['service_using_array'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getCollection([
$this
->getServiceCall('other.service'),
]),
$this
->getParameterCall('some_private_config'),
]),
];
$services['service_with_optional_dependency'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getServiceCall('service.does_not_exist', ContainerInterface::NULL_ON_INVALID_REFERENCE),
$this
->getParameterCall('some_private_config'),
]),
];
$services['factory_service'] = [
'class' => '\\Drupal\\service_container\\ServiceContainer\\ControllerInterface',
'factory' => [
$this
->getServiceCall('service.provider'),
'getFactoryMethod',
],
'arguments' => $this
->getCollection([
$this
->getParameterCall('factory_service_class'),
]),
];
$services['factory_class'] = [
'class' => '\\Drupal\\service_container\\ServiceContainer\\ControllerInterface',
'factory' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService::getFactoryMethod',
'arguments' => [
'\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
[
NULL,
'bar',
],
],
'calls' => [
[
'setContainer',
$this
->getCollection([
$this
->getServiceCall('service_container'),
]),
],
],
];
$services['wrong_factory'] = [
'class' => '\\Drupal\\service_container\\ServiceContainer\\ControllerInterface',
'factory' => (object) [
'I am not a factory, but I pretend to be.',
],
];
$services['circular_dependency'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getServiceCall('circular_dependency'),
]),
];
$services['synthetic'] = [
'synthetic' => TRUE,
];
$services['container_test_file_service_test'] = [
'class' => '\\stdClass',
'file' => __DIR__ . '/Fixture/container_test_file_service_test_service_function.php',
];
$args = [];
for ($i = 0; $i < 12; $i++) {
$services['service_test_instantiation_' . $i] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockInstantiationService',
'arguments' => $this
->getCollection($args, FALSE),
];
$args[] = 'arg_' . $i;
}
$services['service_parameter_not_exists'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getServiceCall('service.provider'),
$this
->getParameterCall('not_exists'),
]),
];
$services['service_dependency_not_exists'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getServiceCall('service_not_exists'),
$this
->getParameterCall('some_config'),
]),
];
$services['service_with_parameter_service'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => $this
->getCollection([
$this
->getParameterCall('service_from_parameter'),
$this
->getCollection([
1,
], FALSE),
]),
];
$services['service_not_exists_similar'] = [
'synthetic' => TRUE,
];
$services['configurator'] = [
'synthetic' => TRUE,
];
$services['configurable_service'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => [],
'configurator' => [
$this
->getServiceCall('configurator'),
'configureService',
],
];
$services['configurable_service_exception'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockService',
'arguments' => [],
'configurator' => 'configurator_service_test_does_not_exist',
];
$services['service_with_raw_argument'] = [
'class' => '\\Drupal\\Tests\\Component\\DependencyInjection\\MockInstantiationService',
'arguments' => $this
->getCollection([
$this
->getRaw('ccc'),
]),
];
$aliases = [];
$aliases['service.provider_alias'] = 'service.provider';
$aliases['late.service_alias'] = 'late.service';
return [
'aliases' => $aliases,
'parameters' => $parameters,
'services' => $services,
'frozen' => TRUE,
'machine_format' => $this->machineFormat,
];
}
protected function getServiceCall($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
return (object) [
'type' => 'service',
'id' => $id,
'invalidBehavior' => $invalid_behavior,
];
}
protected function getParameterCall($name) {
return (object) [
'type' => 'parameter',
'name' => $name,
];
}
protected function getPrivateServiceCall($id, $service_definition, $shared = FALSE) {
if (!$id) {
$hash = Crypt::hashBase64(serialize($service_definition));
$id = 'private__' . $hash;
}
return (object) [
'type' => 'private_service',
'id' => $id,
'value' => $service_definition,
'shared' => $shared,
];
}
protected function getCollection($collection, $resolve = TRUE) {
return (object) [
'type' => 'collection',
'value' => $collection,
'resolve' => $resolve,
];
}
protected function getRaw($value) {
return (object) [
'type' => 'raw',
'value' => $value,
];
}
}
interface MockConfiguratorInterface {
public function configureService($service);
}
class MockInstantiationService {
protected $arguments;
public function __construct() {
$this->arguments = func_get_args();
}
public function getArguments() {
return $this->arguments;
}
}
class MockService {
protected $container;
protected $someOtherService;
protected $someParameter;
protected $someOtherParameter;
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;
}
public function setContainer(ContainerInterface $container) {
$this->container = $container;
}
public function getContainer() {
return $this->container;
}
public function getSomeOtherService() {
return $this->someOtherService;
}
public function getSomeParameter() {
return $this->someParameter;
}
public function setOtherConfigParameter($some_other_parameter) {
$this->someOtherParameter = $some_other_parameter;
}
public function getSomeOtherParameter() {
return $this->someOtherParameter;
}
public static function getFactoryMethod($class, $arguments = []) {
$r = new \ReflectionClass($class);
$service = $r
->getConstructor() === NULL ? $r
->newInstance() : $r
->newInstanceArgs($arguments);
return $service;
}
}