Skip to content

Commit

Permalink
Update Base_Constant to return the singleton object for same static c…
Browse files Browse the repository at this point in the history
…alls (#7064)
  • Loading branch information
htdat authored Aug 29, 2023
1 parent e9baed0 commit 9d5e3e3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
4 changes: 4 additions & 0 deletions changelog/update-base-constant-return-same-object-static-call
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: dev

Update Base_Constant to return the singleton object for same static calls.
20 changes: 15 additions & 5 deletions includes/constants/class-base-constant.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,19 @@ abstract class Base_Constant implements \JsonSerializable {
protected $value;

/**
* Class constructor.
* Static objects cache.
*
* @param mixed $value Constant from class.
* @var array
*/
protected static $object_cache = [];

/**
* Class constructor. Keep it private to only allow initializing from __callStatic()
*
* @param string $value Constant from class.
* @throws \InvalidArgumentException
*/
public function __construct( $value ) {
private function __construct( string $value ) {
if ( $value instanceof static ) {
$value = $value->get_value();
} else {
Expand Down Expand Up @@ -61,7 +68,7 @@ public function get_value() {
* @return bool
*/
final public function equals( $variable = null ): bool {
return $variable instanceof Base_Constant && $this->get_value() === $variable->get_value() && static::class === \get_class( $variable );
return $this === $variable;
}

/**
Expand Down Expand Up @@ -92,7 +99,10 @@ public static function search( string $value ) {
* @throws \InvalidArgumentException
*/
public static function __callStatic( $name, $arguments ) {
return new static( $name );
if ( ! isset( static::$object_cache[ $name ] ) ) {
static::$object_cache[ $name ] = new static( $name );
}
return static::$object_cache[ $name ];
}

/**
Expand Down
6 changes: 6 additions & 0 deletions tests/unit/test-class-base-constant.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
*/
class Base_Constant_Test extends WCPAY_UnitTestCase {

public function test_base_constant_retun_single_object_for_multiple_same_static_calls() {
$instance_1 = Payment_Method::BASC();
$instance_2 = Payment_Method::BASC();
$this->assertTrue( $instance_1 === $instance_2 );
}
public function test_base_constant_will_create_constant() {
$class = Payment_Method::BASC();
$this->assertInstanceOf( Payment_Method::class, $class );
Expand Down Expand Up @@ -52,4 +57,5 @@ public function test_class_will_throw_exception_if_searched_by_value_that_does_n
$this->expectException( \InvalidArgumentException::class );
Payment_Method::search( 'foo' );
}

}

0 comments on commit 9d5e3e3

Please sign in to comment.