Skip to content

Commit

Permalink
Add callable attributes support (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
talelmishali authored Aug 17, 2022
1 parent b85edbb commit 6316ae6
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 3 deletions.
31 changes: 29 additions & 2 deletions src/OnboardingStep.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ class OnboardingStep implements Arrayable
{
protected array $attributes = [];

/** @var callable|null */
protected $callableAttributes;

/** @var callable|null */
protected $excludeIf;

Expand Down Expand Up @@ -58,6 +61,24 @@ public function setModel(Onboardable $model): self
return $this;
}

public function setCallableAttributes(): void
{
if (is_null($this->callableAttributes)) {
return;
}

$this->attributes(once(fn () => app()->call($this->callableAttributes, ['model' => $this->model])));
}

public function initiate(Onboardable $model): self
{
$this->setModel($model);

$this->setCallableAttributes();

return $this;
}

public function excluded(): bool
{
if ($this->excludeIf && $this->model) {
Expand Down Expand Up @@ -91,9 +112,15 @@ public function attribute(string $key, mixed $default = null): mixed
return Arr::get($this->attributes, $key, $default);
}

public function attributes(array $attributes): self
public function attributes(array|callable $attributes): self
{
$this->attributes = array_merge($this->attributes, $attributes);
if (is_callable($attributes)) {
$this->callableAttributes = $attributes;
}

if (is_array($attributes)) {
$this->attributes = array_merge($this->attributes, $attributes);
}

return $this;
}
Expand Down
2 changes: 1 addition & 1 deletion src/OnboardingSteps.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public function addStep(string $title): OnboardingStep
public function steps(Onboardable $model): Collection
{
return collect($this->steps)
->map(fn (OnboardingStep $step) => $step->setModel($model))
->map(fn (OnboardingStep $step) => $step->initiate($model))
->filter(fn (OnboardingStep $step) => $step->notExcluded());
}
}
23 changes: 23 additions & 0 deletions tests/OnboardTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,26 @@
expect($called)->toBe(1)
->and($onboarding->finished())->toBeFalse();
});

test('step attrbiutes can be callable', function () {
$this->user->name = fake()->name;

$onboardingSteps = new OnboardingSteps();
$onboardingSteps->addStep('Step 1')
->link('/some/url')
->cta('Test This!')
->attributes(function (User $model) {
return [
'user_name' => $model->name,
];
});

$onboarding = new OnboardingManager($this->user, $onboardingSteps);

$step = $onboarding->steps()->first();

expect($step)
->user_name->not->toBeNull()
->user_name->toBe($this->user->name)
->title->tobe('Step 1');
});

0 comments on commit 6316ae6

Please sign in to comment.