2017-02-06 23:00:41 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
/*
|
|
|
|
* This file is part of the Symfony package.
|
|
|
|
*
|
|
|
|
* (c) Fabien Potencier <fabien@symfony.com>
|
|
|
|
*
|
|
|
|
* For the full copyright and license information, please view the LICENSE
|
|
|
|
* file that was distributed with this source code.
|
|
|
|
*/
|
|
|
|
|
|
|
|
namespace Symfony\Component\DependencyInjection\Tests;
|
|
|
|
|
2017-02-20 13:56:45 +00:00
|
|
|
use PHPUnit\Framework\TestCase;
|
2017-02-06 23:00:41 +00:00
|
|
|
use Symfony\Component\DependencyInjection\ServiceLocator;
|
|
|
|
|
2017-02-20 13:56:45 +00:00
|
|
|
class ServiceLocatorTest extends TestCase
|
2017-02-06 23:00:41 +00:00
|
|
|
{
|
|
|
|
public function testHas()
|
|
|
|
{
|
|
|
|
$locator = new ServiceLocator(array(
|
|
|
|
'foo' => function () { return 'bar'; },
|
|
|
|
'bar' => function () { return 'baz'; },
|
|
|
|
function () { return 'dummy'; },
|
|
|
|
));
|
|
|
|
|
|
|
|
$this->assertTrue($locator->has('foo'));
|
|
|
|
$this->assertTrue($locator->has('bar'));
|
|
|
|
$this->assertFalse($locator->has('dummy'));
|
|
|
|
}
|
|
|
|
|
|
|
|
public function testGet()
|
|
|
|
{
|
|
|
|
$locator = new ServiceLocator(array(
|
|
|
|
'foo' => function () { return 'bar'; },
|
|
|
|
'bar' => function () { return 'baz'; },
|
|
|
|
));
|
|
|
|
|
|
|
|
$this->assertSame('bar', $locator->get('foo'));
|
|
|
|
$this->assertSame('baz', $locator->get('bar'));
|
|
|
|
}
|
|
|
|
|
2017-03-16 18:01:53 +00:00
|
|
|
public function testGetDoesNotMemoize()
|
2017-02-06 23:00:41 +00:00
|
|
|
{
|
|
|
|
$i = 0;
|
2017-03-16 18:01:53 +00:00
|
|
|
$locator = new ServiceLocator(array(
|
|
|
|
'foo' => function () use (&$i) {
|
|
|
|
++$i;
|
|
|
|
|
|
|
|
return 'bar';
|
|
|
|
},
|
|
|
|
));
|
2017-02-06 23:00:41 +00:00
|
|
|
|
|
|
|
$this->assertSame('bar', $locator->get('foo'));
|
|
|
|
$this->assertSame('bar', $locator->get('foo'));
|
2017-03-16 18:01:53 +00:00
|
|
|
$this->assertSame(2, $i);
|
2017-02-06 23:00:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @expectedException \Psr\Container\NotFoundExceptionInterface
|
|
|
|
* @expectedExceptionMessage You have requested a non-existent service "dummy"
|
|
|
|
*/
|
|
|
|
public function testGetThrowsOnUndefinedService()
|
|
|
|
{
|
|
|
|
$locator = new ServiceLocator(array(
|
|
|
|
'foo' => function () { return 'bar'; },
|
|
|
|
'bar' => function () { return 'baz'; },
|
|
|
|
));
|
|
|
|
|
|
|
|
$locator->get('dummy');
|
|
|
|
}
|
|
|
|
|
|
|
|
public function testInvoke()
|
|
|
|
{
|
|
|
|
$locator = new ServiceLocator(array(
|
|
|
|
'foo' => function () { return 'bar'; },
|
|
|
|
'bar' => function () { return 'baz'; },
|
|
|
|
));
|
|
|
|
|
|
|
|
$this->assertSame('bar', $locator('foo'));
|
|
|
|
$this->assertSame('baz', $locator('bar'));
|
|
|
|
$this->assertNull($locator('dummy'), '->__invoke() should return null on invalid service');
|
|
|
|
}
|
|
|
|
}
|