underpin icon indicating copy to clipboard operation
underpin copied to clipboard

Add methods to make decisions easier when using Accumulator

Open alexstandiford opened this issue 2 years ago • 0 comments

It would be nice to add a set method to the accumulator that, unlike update, will only change the value if it is not set.

This could simplify many logical scenarios where something is being extended using apply_filters, but the update only needs to be made if nothing else is currently set.

For example:


// GIVEN
$item = new class{
  use With_Subject;

  public function get_user_photo($id){
	return $this->apply_filters( 'user:photo', new Accumulator( [
		'default'        => null, // Default value is null
		'state'          => [ 'id' => $id ],
		'valid_callback' => fn ( $value ) => is_string( $value ),
	] ) );
  }
}

// NEW
$item->attach( 'user:photo', new Observer( 'key', [
	'update' => function ( $instance, Accumulator $accumulator ) {
                // Only sets if the state hasn't already been set.
		$accumulator->set( Integrations\User::class );
	},
] ) );

// OLD
$item->attach( 'user:photo', new Observer( 'key', [
	'update' => function ( $instance, Accumulator $accumulator ) {
		if($accumulator->get_state() === null) $accumulator->update( Integrations\User::class );
	},
] ) );

alexstandiford avatar Dec 17 '21 14:12 alexstandiford