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 shortcut for tag reference #333 #353

Merged
merged 10 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/CompositeContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use Psr\Container\ContainerInterface;
use RuntimeException;
use Throwable;
use Yiisoft\Di\Helpers\TagHelper;
use Yiisoft\Di\Reference\TagReference;

use function is_string;

Expand Down Expand Up @@ -54,11 +54,11 @@
return $stateResetter;
}

if (TagHelper::isTagAlias($id)) {
if (TagReference::isTagAlias($id)) {
$tags = [];
foreach ($this->containers as $container) {
if (!$container instanceof Container) {
continue;

Check warning on line 61 in src/CompositeContainer.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "Continue_": --- Original +++ New @@ @@ $tags = []; foreach ($this->containers as $container) { if (!$container instanceof Container) { - continue; + break; } if ($container->has($id)) { /** @psalm-suppress MixedArgument `Container::get()` always return array for tag */

Check warning on line 61 in src/CompositeContainer.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "Continue_": --- Original +++ New @@ @@ $tags = []; foreach ($this->containers as $container) { if (!$container instanceof Container) { - continue; + break; } if ($container->has($id)) { /** @psalm-suppress MixedArgument `Container::get()` always return array for tag */
}
if ($container->has($id)) {
/** @psalm-suppress MixedArgument `Container::get()` always return array for tag */
Expand All @@ -81,7 +81,7 @@
$exceptions = [];
foreach ($this->containers as $container) {
$hasException = false;
try {

Check warning on line 84 in src/CompositeContainer.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "UnwrapFinally": --- Original +++ New @@ @@ } catch (Throwable $t) { $hasException = true; $exceptions[] = [$t, $container]; - } finally { - if (!$hasException) { - $exceptions[] = [new RuntimeException('Container "has()" returned false, but no exception was thrown from "get()".'), $container]; - } + } + if (!$hasException) { + $exceptions[] = [new RuntimeException('Container "has()" returned false, but no exception was thrown from "get()".'), $container]; } } throw new CompositeNotFoundException($exceptions);

Check warning on line 84 in src/CompositeContainer.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "UnwrapFinally": --- Original +++ New @@ @@ } catch (Throwable $t) { $hasException = true; $exceptions[] = [$t, $container]; - } finally { - if (!$hasException) { - $exceptions[] = [new RuntimeException('Container "has()" returned false, but no exception was thrown from "get()".'), $container]; - } + } + if (!$hasException) { + $exceptions[] = [new RuntimeException('Container "has()" returned false, but no exception was thrown from "get()".'), $container]; } } throw new CompositeNotFoundException($exceptions);
$container->get($id);
} catch (Throwable $t) {
$hasException = true;
Expand Down
10 changes: 5 additions & 5 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use Yiisoft\Definitions\Helpers\DefinitionValidator;
use Yiisoft\Di\Helpers\DefinitionNormalizer;
use Yiisoft\Di\Helpers\DefinitionParser;
use Yiisoft\Di\Helpers\TagHelper;
use Yiisoft\Di\Reference\TagReference;

use function array_key_exists;
use function array_keys;
Expand Down Expand Up @@ -101,8 +101,8 @@
*/
public function has(string $id): bool
{
if (TagHelper::isTagAlias($id)) {
$tag = TagHelper::extractTagFromAlias($id);
if (TagReference::isTagAlias($id)) {
$tag = TagReference::extractTagFromAlias($id);
return isset($this->tags[$tag]);
}

Expand Down Expand Up @@ -276,7 +276,7 @@

$this->delegates->attach($delegate);
}
$this->definitions->setDelegateContainer($this->delegates);

Check warning on line 279 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "MethodCallRemoval": --- Original +++ New @@ @@ } $this->delegates->attach($delegate); } - $this->definitions->setDelegateContainer($this->delegates); + } /** * @param mixed $definition Definition to validate.

Check warning on line 279 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "MethodCallRemoval": --- Original +++ New @@ @@ } $this->delegates->attach($delegate); } - $this->definitions->setDelegateContainer($this->delegates); + } /** * @param mixed $definition Definition to validate.
}

/**
Expand All @@ -303,7 +303,7 @@

$definition = array_merge(
$class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
[ArrayDefinition::CONSTRUCTOR => $constructorArguments],

Check warning on line 306 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "ArrayItemRemoval": --- Original +++ New @@ @@ $methodsAndProperties = $definition['methodsAndProperties']; $definition = array_merge( $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class], - [ArrayDefinition::CONSTRUCTOR => $constructorArguments], + [], // extract only value from parsed definition method array_map(fn(array $data): mixed => $data[2], $methodsAndProperties) );

Check warning on line 306 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "ArrayItemRemoval": --- Original +++ New @@ @@ $methodsAndProperties = $definition['methodsAndProperties']; $definition = array_merge( $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class], - [ArrayDefinition::CONSTRUCTOR => $constructorArguments], + [], // extract only value from parsed definition method array_map(fn(array $data): mixed => $data[2], $methodsAndProperties) );
// extract only value from parsed definition method
array_map(fn (array $data): mixed => $data[2], $methodsAndProperties),
);
Expand Down Expand Up @@ -472,7 +472,7 @@
*/
private function build(string $id)
{
if (TagHelper::isTagAlias($id)) {
if (TagReference::isTagAlias($id)) {
return $this->getTaggedServices($id);
}

Expand All @@ -489,7 +489,7 @@
);
}

$this->building[$id] = 1;

Check warning on line 492 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "IncrementInteger": --- Original +++ New @@ @@ } throw new CircularReferenceException(sprintf('Circular reference to "%s" detected while building: %s.', $id, implode(', ', array_keys($this->building)))); } - $this->building[$id] = 1; + $this->building[$id] = 2; try { /** @var mixed $object */ $object = $this->buildInternal($id);

Check warning on line 492 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "IncrementInteger": --- Original +++ New @@ @@ } throw new CircularReferenceException(sprintf('Circular reference to "%s" detected while building: %s.', $id, implode(', ', array_keys($this->building)))); } - $this->building[$id] = 1; + $this->building[$id] = 2; try { /** @var mixed $object */ $object = $this->buildInternal($id);
try {
/** @var mixed $object */
$object = $this->buildInternal($id);
Expand All @@ -502,7 +502,7 @@

private function getTaggedServices(string $tagAlias): array
{
$tag = TagHelper::extractTagFromAlias($tagAlias);
$tag = TagReference::extractTagFromAlias($tagAlias);
$services = [];
if (isset($this->tags[$tag])) {
foreach ($this->tags[$tag] as $service) {
Expand Down
21 changes: 0 additions & 21 deletions src/Helpers/TagHelper.php

This file was deleted.

38 changes: 38 additions & 0 deletions src/Reference/TagReference.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Di\Reference;

use Yiisoft\Definitions\Reference;

/**
* TagReference is a helper class that is used to specify a reference to a tag.
* For example, `TagReference::to('my-tag')` specifies a reference to all services that are tagged with `tag@my-tag`.
*/
final class TagReference
{
private const PREFIX = 'tag@';

private function __construct()
{
}

public static function to(string $tag): Reference
{
return Reference::to(self::PREFIX . $tag);
}

public static function extractTagFromAlias(string $alias): string
{
if (!str_starts_with($alias, self::PREFIX)) {
throw new \InvalidArgumentException(sprintf('Alias "%s" is not a tag alias.', $alias));
}
return substr($alias, 4);
}

public static function isTagAlias(string $id): bool
{
return str_starts_with($id, self::PREFIX);
}
}
54 changes: 54 additions & 0 deletions tests/Unit/Reference/TagReferenceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Di\Tests\Unit\Reference;

use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Yiisoft\Di\Reference\TagReference;

final class TagReferenceTest extends TestCase
{
public function testAliases(): void
{
$this->assertFalse(TagReference::isTagAlias('test'));
$this->assertFalse(TagReference::isTagAlias('tag#test'));
$this->assertTrue(TagReference::isTagAlias('tag@test'));
}

public function testExtractTag(): void
{
$this->assertEquals('test', TagReference::extractTagFromAlias('tag@test'));
}

public function testExtractWrongTag(): void
xepozz marked this conversation as resolved.
Show resolved Hide resolved
{
$this->expectException(InvalidArgumentException::class);
TagReference::extractTagFromAlias('test');

$this->expectException(InvalidArgumentException::class);
TagReference::extractTagFromAlias('tag#test');
}

public function testReference(): void
{
$reference = TagReference::to('test');
$spyContainer = new class () implements ContainerInterface {
public function get($id)
{
return $id;
}

public function has($id): bool
{
return true;
}
};

$result = $reference->resolve($spyContainer);

$this->assertEquals('tag@test', $result);
}
}
Loading