Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add methods to make decisions easier when using Accumulator #48

Open
alexstandiford opened this issue Dec 17, 2021 · 0 comments
Open

Add methods to make decisions easier when using Accumulator #48

alexstandiford opened this issue Dec 17, 2021 · 0 comments

Comments

@alexstandiford
Copy link
Collaborator

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 );
	},
] ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant