Skip to content

Commit

Permalink
ContainerBuilder: excluding classes from autowiring [Closes nette/net…
Browse files Browse the repository at this point in the history
  • Loading branch information
matej21 authored and dg committed Jun 24, 2014
1 parent 68aff8e commit 5f5ee0a
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/DI/ContainerBuilder.php
Expand Up @@ -35,6 +35,9 @@ class ContainerBuilder extends Nette\Object
/** @var array for auto-wiring */
private $classes;

/** @var string[] of classes excluded from auto-wiring */
private $excludedClasses = array();

/** @var array of file names */
private $dependencies = array();

Expand Down Expand Up @@ -226,6 +229,12 @@ public function prepareClassList()
}
}

foreach ($this->excludedClasses as $class) {
foreach (class_parents($class) + class_implements($class) + array($class) as $parent) {
unset($this->classes[strtolower($parent)]);
}
}

foreach ($this->classes as $class => $foo) {
$this->addDependency(Reflection\ClassType::from($class)->getFileName());
}
Expand Down Expand Up @@ -343,6 +352,17 @@ private function resolveEntityClass($entity, $recursive = array())
}


/**
* @param string[]
* @return self
*/
public function addExcludedClasses(array $classes)
{
$this->excludedClasses = array_merge($this->excludedClasses, $classes);
return $this;
}


/**
* Adds a file to the list of dependencies.
* @return self
Expand Down
50 changes: 50 additions & 0 deletions tests/DI/ContainerBuilder.autowiring.excluded.phpt
@@ -0,0 +1,50 @@
<?php

/**
* Test: Nette\DI\ContainerBuilder and class blacklist
*/

use Nette\DI,
Tester\Assert;


require __DIR__ . '/../bootstrap.php';


interface IFoo
{
}

interface IBar
{
}

class Foo implements IFoo
{
}

class Bar extends Foo implements IBar
{
}


$builder = new DI\ContainerBuilder;
$builder->addDefinition('xx')
->setClass('Bar');
$builder->addExcludedClasses(array('Foo', 'IBar'));

$container = createContainer($builder);

Assert::type('Bar', $container->getByType('Bar'));

Assert::exception(function() use ($container) {
$container->getByType('IBar');
}, '\Nette\DI\MissingServiceException');

Assert::exception(function() use ($container) {
$container->getByType('Foo');
}, '\Nette\DI\MissingServiceException');

Assert::exception(function() use ($container) {
$container->getByType('IFoo');
}, '\Nette\DI\MissingServiceException');

0 comments on commit 5f5ee0a

Please sign in to comment.