Centralized logic to normalize tag names and removed references to deprecated setTags method in unit tests

This commit is contained in:
Alejandro Celaya 2021-01-31 11:09:00 +01:00
parent 09f25d78b7
commit 1cd6fdeede
2 changed files with 9 additions and 12 deletions

View File

@ -7,11 +7,9 @@ namespace Shlinkio\Shlink\Core\Util;
use Doctrine\Common\Collections; use Doctrine\Common\Collections;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Shlinkio\Shlink\Core\Entity\Tag; use Shlinkio\Shlink\Core\Entity\Tag;
use Shlinkio\Shlink\Core\Validation\ShortUrlInputFilter;
use function Functional\map; use function Functional\map;
use function str_replace;
use function strtolower;
use function trim;
/** @deprecated */ /** @deprecated */
trait TagManagerTrait trait TagManagerTrait
@ -23,8 +21,11 @@ trait TagManagerTrait
*/ */
private function tagNamesToEntities(EntityManagerInterface $em, array $tags): Collections\Collection private function tagNamesToEntities(EntityManagerInterface $em, array $tags): Collections\Collection
{ {
$entities = map($tags, function (string $tagName) use ($em) { $normalizedTags = ShortUrlInputFilter::withNonRequiredLongUrl([
$tagName = $this->normalizeTagName($tagName); ShortUrlInputFilter::TAGS => $tags,
])->getValue(ShortUrlInputFilter::TAGS);
$entities = map($normalizedTags, function (string $tagName) use ($em) {
$tag = $em->getRepository(Tag::class)->findOneBy(['name' => $tagName]) ?? new Tag($tagName); $tag = $em->getRepository(Tag::class)->findOneBy(['name' => $tagName]) ?? new Tag($tagName);
$em->persist($tag); $em->persist($tag);
@ -33,9 +34,4 @@ trait TagManagerTrait
return new Collections\ArrayCollection($entities); return new Collections\ArrayCollection($entities);
} }
private function normalizeTagName(string $tagName): string
{
return str_replace(' ', '-', strtolower(trim($tagName)));
}
} }

View File

@ -119,7 +119,7 @@ class UrlShortenerTest extends TestCase
), ShortUrl::withLongUrl($url)]; ), ShortUrl::withLongUrl($url)];
yield [ yield [
ShortUrlMeta::fromRawData(['findIfExists' => true, 'longUrl' => $url, 'tags' => ['foo', 'bar']]), ShortUrlMeta::fromRawData(['findIfExists' => true, 'longUrl' => $url, 'tags' => ['foo', 'bar']]),
ShortUrl::withLongUrl($url)->setTags(new ArrayCollection([new Tag('bar'), new Tag('foo')])), ShortUrl::fromMeta(ShortUrlMeta::fromRawData(['longUrl' => $url, 'tags' => ['foo', 'bar']])),
]; ];
yield [ yield [
ShortUrlMeta::fromRawData(['findIfExists' => true, 'maxVisits' => 3, 'longUrl' => $url]), ShortUrlMeta::fromRawData(['findIfExists' => true, 'maxVisits' => 3, 'longUrl' => $url]),
@ -157,7 +157,8 @@ class UrlShortenerTest extends TestCase
'validUntil' => Chronos::parse('2017-01-01'), 'validUntil' => Chronos::parse('2017-01-01'),
'maxVisits' => 4, 'maxVisits' => 4,
'longUrl' => $url, 'longUrl' => $url,
]))->setTags(new ArrayCollection([new Tag('foo'), new Tag('bar'), new Tag('baz')])), 'tags' => ['foo', 'bar', 'baz'],
])),
]; ];
} }
} }