mirror of
https://github.com/woocommerce/woocommerce-paypal-payments.git
synced 2025-08-30 05:00:51 +08:00
Add SingletonDecorator
Refactor PurchaseUnitSanitizer service registration to SingletonDecorator
This commit is contained in:
parent
2b497182d3
commit
ecb884c86c
3 changed files with 65 additions and 22 deletions
61
lib/packages/Pattern/SingletonDecorator.php
Normal file
61
lib/packages/Pattern/SingletonDecorator.php
Normal file
|
@ -0,0 +1,61 @@
|
|||
<?php
|
||||
|
||||
namespace WooCommerce\PayPalCommerce\Vendor\Pattern;
|
||||
|
||||
class SingletonDecorator {
|
||||
|
||||
/**
|
||||
* The callable with the executing code
|
||||
*
|
||||
* @var callable
|
||||
*/
|
||||
private $callable;
|
||||
|
||||
/**
|
||||
* The execution result
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
private $result;
|
||||
|
||||
/**
|
||||
* Indicates if the callable is resolved
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $executed = false;
|
||||
|
||||
/**
|
||||
* SingletonDecorator constructor.
|
||||
*
|
||||
* @param callable $callable
|
||||
*/
|
||||
public function __construct( callable $callable ) {
|
||||
$this->callable = $callable;
|
||||
}
|
||||
|
||||
/**
|
||||
* The make constructor.
|
||||
*
|
||||
* @param callable $callable
|
||||
* @return self
|
||||
*/
|
||||
public static function make( callable $callable ): self {
|
||||
return new static( $callable );
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a callable once and returns the same result on subsequent invokes.
|
||||
*
|
||||
* @param mixed ...$args Arguments to be passed to the callable.
|
||||
* @return mixed
|
||||
*/
|
||||
public function __invoke( ...$args ) {
|
||||
if ( ! $this->executed ) {
|
||||
$this->result = call_user_func_array( $this->callable, $args );
|
||||
$this->executed = true;
|
||||
}
|
||||
|
||||
return $this->result;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue