diff --git a/composer.json b/composer.json index e5f74ff..7468339 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,8 @@ "psr/container": "^1.0" }, "suggest": { - "ext-libxml": "TagAndAttributeRemover needs this extention" + "ext-libxml": "TagAndAttributeRemover needs this extention", + "ext-intl": "Slugify needs this extension" }, "require-dev": { "codeception/codeception": "^4.1", @@ -38,7 +39,6 @@ } }, "scripts": { - "cs-check": "vendor/bin/phpcs --standard=Doctrine", "cs-fix": "vendor/bin/phpcbf --standard=Doctrine" diff --git a/src/Slugifier.php b/src/Slugifier.php new file mode 100644 index 0000000..ac54ab8 --- /dev/null +++ b/src/Slugifier.php @@ -0,0 +1,69 @@ +subject = $subject; + $this->transliterator = Transliterator::create('Any-Latin; Latin-ASCII'); + } + /** + * @param mixed $subject + * @return string|iterable + */ + public static function slugify($subject) + { + return (new self($subject)) + ->getSlugifiedResult(); + } + /** + * @return string|iterable + */ + private function getSlugifiedResult() + { + if (is_iterable($this->subject)) { + return $this->getSlugifiedIterable($this->subject); + } + return $this->getSlugifiedString($this->subject); + } + + private function getSlugifiedString($subject) : string + { + + if (!is_string($subject)) { + throw new InvalidArgumentException( + sprintf('Only string or array of strings accepted but %s given', gettype($subject)) + ); + } + $stringWithRemovedDiacritics = $this->transliterator->transliterate($subject); + $stringWithRemovedWhite = preg_replace(['/\-/','/[\W]+/'], [' ','-'], $stringWithRemovedDiacritics); + return strtolower($stringWithRemovedWhite); + } + + /** + * @param iterable $subject + * @return iterable + */ + private function getSlugifiedIterable(iterable $subject) : iterable + { + foreach ($subject as $item) { + yield $this->getSlugifiedString($item); + } + } +} \ No newline at end of file diff --git a/tests/unit/SlugifierTest.php b/tests/unit/SlugifierTest.php new file mode 100644 index 0000000..72f92e1 --- /dev/null +++ b/tests/unit/SlugifierTest.php @@ -0,0 +1,65 @@ +assertEquals($expected[$index], $item, 'Returning expected slugs failed'); + $index++; + } + } + /** + * @test + */ + public function shouldThrowExceptionForInvalidInput(): void + { + $this->expectException(InvalidArgumentException::class); + Slugifier::slugify(1234); + } + + public function dataProvider() : array + { + return [ + [ + [ + 'Meinung: Impfstoff-Mangel für die Ärmsten - eine moralische Bankrotterklärung', + 'Türkiye\'nin İstanbul Sözleşmesi serüveni', + 'Во Франции прошли протесты против ужесточения мер', + '1234' + ], + [ + 'meinung-impfstoff-mangel-fur-die-armsten-eine-moralische-bankrotterklarung', + 'turkiye-nin-istanbul-sozlesmesi-seruveni', + 'vo-francii-prosli-protesty-protiv-uzestocenia-mer', + '1234' + ], + ] + ]; + } + +}