Skip to content

Commit

Permalink
ADD allow any value to be saved against a mark (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
digitalSloth authored Aug 21, 2023
1 parent 4f37334 commit be60822
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,28 @@ Reaction::has($post, $user, 'heart'); // returns whether the user has reacted wi
Reaction::count($post, 'person_raising_hand'); // returns the amount of 'person_raising_hand' reactions for the given post
```

You can also use wildcards to allow any value for a specific mark.

Here's an example when working with reactions:

``` php
'allowed_values' => [
'reaction' => '*',
],
```

When set, you can use any value when giving a reaction:

``` php
use App\Models\Post;
use Maize\Markable\Models\Reaction;

$post = Post::firstOrFail();
$user = auth()->user();

Reaction::add($post, $user, 'random_value'); // adds the 'random_value' reaction to the post for the given user
```

### Retrieve the list of marks of an entity with eloquent

``` php
Expand Down
10 changes: 8 additions & 2 deletions src/Mark.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class_basename(static::class)
)->plural()->lower()->__toString();
}

public static function allowedValues(): ?array
public static function allowedValues(): array|string|null
{
$className = Str::lower(static::getMarkClassName());

Expand Down Expand Up @@ -100,7 +100,13 @@ public static function toggle(Model $markable, Model $user, string $value = null

public static function hasAllowedValues(?string $value): bool
{
return in_array($value, static::allowedValues() ?? [null]);
$allowedValues = static::allowedValues() ?? [null];

if ($allowedValues === '*') {
return true;
}

return in_array($value, $allowedValues);
}

public function user(): BelongsTo
Expand Down
19 changes: 19 additions & 0 deletions tests/ReactionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,25 @@ public function cannot_add_an_invalid_reaction_value_fails()
Reaction::add($article, $user, 'not_valid_value');
}

/** @test */
public function can_add_any_value_with_wildcard()
{
config()->set('markable.allowed_values.reaction', '*');

$article = Article::factory()->create();
$user = User::factory()->create();
$table = (new Reaction)->getTable();

Reaction::add($article, $user, 'random_value');
$this->assertDatabaseCount($table, 1);
$this->assertDatabaseHas($table, [
'user_id' => $user->getKey(),
'markable_id' => $article->getKey(),
'markable_type' => $article->getMorphClass(),
'value' => 'random_value',
]);
}

/** @test */
public function can_add_a_reaction()
{
Expand Down

0 comments on commit be60822

Please sign in to comment.