Add SingletonDecorator

Refactor PurchaseUnitSanitizer service registration to SingletonDecorator
This commit is contained in:
Pedro Silva 2023-08-10 09:46:15 +01:00
parent 2b497182d3
commit ecb884c86c
No known key found for this signature in database
GPG key ID: E2EE20C0669D24B3
3 changed files with 65 additions and 22 deletions

View 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;
}
}