ExtendedContainer::replace now allows registering anonymous classes.

This commit is contained in:
Nestor Soriano 2021-05-04 16:14:34 +02:00
parent 6820b6e519
commit 4d13b0ca07
No known key found for this signature in database
GPG Key ID: 08110F3518C12CAD
2 changed files with 25 additions and 1 deletions

View File

@ -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' );
}
}

View File

@ -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'.
*/