ExtendedContainer::replace now allows registering anonymous classes.
This commit is contained in:
parent
6820b6e519
commit
4d13b0ca07
|
@ -81,7 +81,7 @@ class ExtendedContainer extends BaseContainer {
|
|||
}
|
||||
|
||||
$concrete_class = $this->get_class_from_concrete( $concrete );
|
||||
if ( isset( $concrete_class ) && ! $this->is_class_allowed( $concrete_class ) ) {
|
||||
if ( isset( $concrete_class ) && ! $this->is_class_allowed( $concrete_class ) && ! $this->is_anonymous_class( $concrete_class ) ) {
|
||||
throw new ContainerException( "You cannot use concrete '$concrete_class', only classes in the {$this->woocommerce_namespace} namespace are allowed." );
|
||||
}
|
||||
|
||||
|
@ -149,4 +149,14 @@ class ExtendedContainer extends BaseContainer {
|
|||
protected function is_class_allowed( string $class_name ): bool {
|
||||
return StringUtil::starts_with( $class_name, $this->woocommerce_namespace, false ) || in_array( $class_name, $this->registration_whitelist, true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a class name corresponds to an anonoymous class.
|
||||
*
|
||||
* @param string $class_name The class name to check.
|
||||
* @return bool True if the name correspondos to an anynymous class.
|
||||
*/
|
||||
protected function is_anonymous_class( string $class_name ): bool {
|
||||
return StringUtil::starts_with( $class_name, 'class@anonymous' );
|
||||
}
|
||||
}
|
||||
|
|
|
@ -103,6 +103,20 @@ class ExtendedContainerTest extends \WC_Unit_Test_Case {
|
|||
$this->assertSame( $instance_2, $this->sut->get( DependencyClass::class ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @testdox 'replace' should allow to replace existing registrations with anonymous classes.
|
||||
*/
|
||||
public function test_replace_allows_replacing_existing_registrations_with_anonymous_classes() {
|
||||
$instance_1 = new DependencyClass();
|
||||
$instance_2 = new class() extends DependencyClass {};
|
||||
|
||||
$this->sut->add( DependencyClass::class, $instance_1, true );
|
||||
$this->assertSame( $instance_1, $this->sut->get( DependencyClass::class ) );
|
||||
|
||||
$this->sut->replace( DependencyClass::class, $instance_2, true );
|
||||
$this->assertSame( $instance_2, $this->sut->get( DependencyClass::class ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @testdox 'reset_all_resolved' should discard cached resolutions for classes registered as 'shared'.
|
||||
*/
|
||||
|
|
Loading…
Reference in New Issue