Skip to content

Commit

Permalink
Add tag attribute (#52743)
Browse files Browse the repository at this point in the history
  • Loading branch information
TijmenWierenga authored Sep 11, 2024
1 parent aaa46ac commit 77739f6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/Illuminate/Container/Attributes/Tag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace Illuminate\Container\Attributes;

use Attribute;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Container\ContextualAttribute;

#[Attribute(Attribute::TARGET_PARAMETER)]
final class Tag implements ContextualAttribute
{
public function __construct(
public string $tag,
) {
}

/**
* Resolve the tag.
*
* @param self $attribute
* @param \Illuminate\Contracts\Container\Container $container
* @return mixed
*/
public static function resolve(self $attribute, Container $container)
{
return $container->tagged($attribute->tag);
}
}
16 changes: 16 additions & 0 deletions tests/Container/ContextualAttributeBindingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
use Illuminate\Container\Attributes\Database;
use Illuminate\Container\Attributes\Log;
use Illuminate\Container\Attributes\Storage;
use Illuminate\Container\Attributes\Tag;
use Illuminate\Container\Container;
use Illuminate\Container\RewindableGenerator;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Guard as GuardContract;
use Illuminate\Contracts\Container\ContextualAttribute;
Expand Down Expand Up @@ -235,6 +237,20 @@ public function testAttributeOnAppCall()

$this->assertEquals('Europe/Paris', $value);
}

public function testTagAttribute()
{
$container = new Container;
$container->bind('one', fn (): int => 1);
$container->bind('two', fn (): int => 2);
$container->tag(['one', 'two'], 'numbers');

$value = $container->call(function (#[Tag('numbers')] RewindableGenerator $integers) {
return $integers;
});

$this->assertEquals([1, 2], iterator_to_array($value));
}
}

#[Attribute(Attribute::TARGET_PARAMETER)]
Expand Down

0 comments on commit 77739f6

Please sign in to comment.