タグを保存前に正規化する
This commit is contained in:
parent
cb0af4113d
commit
631d2ea298
@ -44,7 +44,7 @@ class CardController
|
||||
]);
|
||||
|
||||
$tagIds = [];
|
||||
foreach ($resolved->tags as $tagName) {
|
||||
foreach ($resolved->normalizedTags() as $tagName) {
|
||||
$tag = Tag::firstOrCreate(['name' => $tagName]);
|
||||
$tagIds[] = $tag->id;
|
||||
}
|
||||
|
@ -56,7 +56,7 @@ class LinkCollector
|
||||
]);
|
||||
|
||||
$tagIds = [];
|
||||
foreach ($resolved->tags as $tagName) {
|
||||
foreach ($resolved->normalizedTags() as $tagName) {
|
||||
$tag = Tag::firstOrCreate(['name' => $tagName]);
|
||||
$tagIds[] = $tag->id;
|
||||
}
|
||||
|
@ -23,4 +23,30 @@ class Metadata
|
||||
* チェックインタグと同様に保存されるため、スペースや改行文字を含めてはいけません。
|
||||
*/
|
||||
public $tags = [];
|
||||
|
||||
/**
|
||||
* 重複を排除し、正規化を行ったタグの集合を返します。
|
||||
* @return string[]
|
||||
*/
|
||||
public function normalizedTags(): array
|
||||
{
|
||||
$tags = [];
|
||||
foreach ($this->tags as $tag) {
|
||||
$tag = $this->sanitize($tag);
|
||||
$tag = $this->trim($tag);
|
||||
$tags[$tag] = true;
|
||||
}
|
||||
|
||||
return array_keys($tags);
|
||||
}
|
||||
|
||||
private function sanitize(string $value): string
|
||||
{
|
||||
return preg_replace('/\r?\n/u', ' ', $value);
|
||||
}
|
||||
|
||||
private function trim(string $value): string
|
||||
{
|
||||
return trim($value);
|
||||
}
|
||||
}
|
||||
|
33
tests/Unit/MetadataResolver/MetadataTest.php
Normal file
33
tests/Unit/MetadataResolver/MetadataTest.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\MetadataResolver;
|
||||
|
||||
use App\MetadataResolver\Metadata;
|
||||
use Tests\TestCase;
|
||||
|
||||
class MetadataTest extends TestCase
|
||||
{
|
||||
public function testNormalizedTagsCanTrim()
|
||||
{
|
||||
$metadata = new Metadata();
|
||||
$metadata->tags = ['foo ', ' bar', ' foo bar '];
|
||||
|
||||
$this->assertEquals(['foo', 'bar', 'foo bar'], $metadata->normalizedTags());
|
||||
}
|
||||
|
||||
public function testNormalizedTagsCanSanitize()
|
||||
{
|
||||
$metadata = new Metadata();
|
||||
$metadata->tags = ["foo \n", " \nbar", " foo\n bar "];
|
||||
|
||||
$this->assertEquals(['foo', 'bar', 'foo bar'], $metadata->normalizedTags());
|
||||
}
|
||||
|
||||
public function testNormalizedTagsCanDeduplication()
|
||||
{
|
||||
$metadata = new Metadata();
|
||||
$metadata->tags = ['foo ', ' foo', ' bar'];
|
||||
|
||||
$this->assertEquals(['foo', 'bar'], $metadata->normalizedTags());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user