mirror of
https://github.com/phpbb/phpbb.git
synced 2025-03-22 16:40:21 +01:00
Merge pull request #4866 from Nicofuma/ticket/15258
[ticket/15258] Adds a method to get a service by class in service_collection
This commit is contained in:
commit
ec9b52f86e
@ -103,4 +103,35 @@ class service_collection extends \ArrayObject
|
||||
{
|
||||
return $this->service_classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the service associated to a class
|
||||
*
|
||||
* @return mixed
|
||||
* @throw \RuntimeException if the
|
||||
*/
|
||||
public function get_by_class($class)
|
||||
{
|
||||
$service_id = null;
|
||||
|
||||
foreach ($this->service_classes as $id => $service_class)
|
||||
{
|
||||
if ($service_class === $class)
|
||||
{
|
||||
if ($service_id !== null)
|
||||
{
|
||||
throw new \RuntimeException('More than one service definitions found for class "'.$class.'" in collection.');
|
||||
}
|
||||
|
||||
$service_id = $id;
|
||||
}
|
||||
}
|
||||
|
||||
if ($service_id === null)
|
||||
{
|
||||
throw new \RuntimeException('No service found for class "'.$class.'" in collection.');
|
||||
}
|
||||
|
||||
return $this->offsetGet($service_id);
|
||||
}
|
||||
}
|
||||
|
@ -23,10 +23,14 @@ class phpbb_service_collection_test extends \phpbb_test_case
|
||||
$container = new phpbb_mock_container_builder();
|
||||
$container->set('foo', new StdClass);
|
||||
$container->set('bar', new StdClass);
|
||||
$container->set('baz', new StdClass);
|
||||
|
||||
$this->service_collection = new \phpbb\di\service_collection($container);
|
||||
$this->service_collection->add('foo');
|
||||
$this->service_collection->add('bar');
|
||||
$this->service_collection->add_service_class('foo', 'foo_class');
|
||||
$this->service_collection->add_service_class('bar', 'bar_class');
|
||||
$this->service_collection->add_service_class('baz', 'bar_class');
|
||||
|
||||
parent::setUp();
|
||||
}
|
||||
@ -44,4 +48,23 @@ class phpbb_service_collection_test extends \phpbb_test_case
|
||||
|
||||
$this->assertSame(array('foo', 'bar'), $service_names);
|
||||
}
|
||||
|
||||
public function test_get_by_class()
|
||||
{
|
||||
$this->assertSame($this->service_collection['foo'], $this->service_collection->get_by_class('foo_class'));
|
||||
}
|
||||
|
||||
public function test_get_by_class_many_services_exception()
|
||||
{
|
||||
$this->setExpectedException('RuntimeException', 'More than one service definitions found for class "bar_class" in collection.');
|
||||
|
||||
$this->service_collection->get_by_class('bar_class');
|
||||
}
|
||||
|
||||
public function test_get_by_class_no_service_exception()
|
||||
{
|
||||
$this->setExpectedException('RuntimeException', 'No service found for class "baz_class" in collection.');
|
||||
|
||||
$this->service_collection->get_by_class('baz_class');
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user