Skip to content

Add methods to make decisions easier when using Accumulator #48

@alexstandiford

Description

@alexstandiford

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 );
	},
] ) );

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions