Merge pull request #8142 from open-sausages/pulls/4.0/fix-injector-empty

BUG Safely handle empty injector factory responses
This commit is contained in:
Robbie Averill 2018-06-11 15:20:24 +12:00 committed by GitHub
commit 27e24a4728
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 0 deletions

View File

@ -584,6 +584,11 @@ class Injector implements ContainerInterface
$factory = isset($spec['factory']) ? $this->get($spec['factory']) : $this->getObjectCreator(); $factory = isset($spec['factory']) ? $this->get($spec['factory']) : $this->getObjectCreator();
$object = $factory->create($class, $constructorParams); $object = $factory->create($class, $constructorParams);
// Handle empty factory responses
if (!$object) {
return null;
}
// figure out if we have a specific id set or not. In some cases, we might be instantiating objects // figure out if we have a specific id set or not. In some cases, we might be instantiating objects
// that we don't manage directly; we don't want to store these in the service cache below // that we don't manage directly; we don't want to store these in the service cache below
if (!$id) { if (!$id) {

View File

@ -14,6 +14,7 @@ use SilverStripe\Core\Tests\Injector\InjectorTest\CircularOne;
use SilverStripe\Core\Tests\Injector\InjectorTest\CircularTwo; use SilverStripe\Core\Tests\Injector\InjectorTest\CircularTwo;
use SilverStripe\Core\Tests\Injector\InjectorTest\ConstructableObject; use SilverStripe\Core\Tests\Injector\InjectorTest\ConstructableObject;
use SilverStripe\Core\Tests\Injector\InjectorTest\DummyRequirements; use SilverStripe\Core\Tests\Injector\InjectorTest\DummyRequirements;
use SilverStripe\Core\Tests\Injector\InjectorTest\EmptyFactory;
use SilverStripe\Core\Tests\Injector\InjectorTest\MyChildClass; use SilverStripe\Core\Tests\Injector\InjectorTest\MyChildClass;
use SilverStripe\Core\Tests\Injector\InjectorTest\MyParentClass; use SilverStripe\Core\Tests\Injector\InjectorTest\MyParentClass;
use SilverStripe\Core\Tests\Injector\InjectorTest\NeedsBothCirculars; use SilverStripe\Core\Tests\Injector\InjectorTest\NeedsBothCirculars;
@ -102,6 +103,21 @@ class InjectorTest extends SapphireTest
); );
} }
public function testEmptyFactory()
{
$this->expectException(InjectorNotFoundException::class);
$injector = new Injector();
$services = array(
'SomeClass' => array(
'class' => AnotherService::class,
'factory' => EmptyFactory::class,
)
);
$injector->load($services);
$injector->create('SomeClass');
}
public function testConfiguredInjector() public function testConfiguredInjector()
{ {
$injector = new Injector(); $injector = new Injector();

View File

@ -0,0 +1,13 @@
<?php
namespace SilverStripe\Core\Tests\Injector\InjectorTest;
use SilverStripe\Core\Injector\Factory;
class EmptyFactory implements Factory
{
public function create($service, array $params = array())
{
return null;
}
}