|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Kiboko\Component\StringExpressionLanguage; |
| 6 | + |
| 7 | +use Symfony\Component\ExpressionLanguage\ExpressionFunction; |
| 8 | + |
| 9 | +final class Slugify extends ExpressionFunction |
| 10 | +{ |
| 11 | + public function __construct($name) |
| 12 | + { |
| 13 | + parent::__construct( |
| 14 | + $name, |
| 15 | + $this->compile(...)->bindTo($this), |
| 16 | + $this->evaluate(...)->bindTo($this) |
| 17 | + ); |
| 18 | + } |
| 19 | + |
| 20 | + private function compile(string $value, string $divider = '-'): string |
| 21 | + { |
| 22 | + return <<<PHP |
| 23 | + (function () use (\$input) : string { |
| 24 | + \$text = preg_replace('~[^\\pL\\d]+~u', {$divider}, {$value}); |
| 25 | + \$text = iconv('utf-8', 'us-ascii//TRANSLIT', \$text); |
| 26 | + \$text = preg_replace('~[^-\\w]+~', '', \$text); |
| 27 | + \$text = trim(\$text, {$divider}); |
| 28 | + \$text = preg_replace('~-+~', {$divider}, \$text); |
| 29 | + \$text = strtolower(\$text); |
| 30 | +
|
| 31 | + if (strlen(\$text) <= 0) { |
| 32 | + return ''; |
| 33 | + } |
| 34 | +
|
| 35 | + return \$text; |
| 36 | + })() |
| 37 | + PHP; |
| 38 | + } |
| 39 | + |
| 40 | + private function evaluate(array $context, string $value, string $divider = '-'): string |
| 41 | + { |
| 42 | + $text = preg_replace('~[^\pL\d]+~u', $divider, $value); |
| 43 | + $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); |
| 44 | + $text = preg_replace('~[^-\w]+~', '', $text); |
| 45 | + $text = trim($text, $divider); |
| 46 | + $text = preg_replace('~-+~', $divider, $text); |
| 47 | + $text = strtolower($text); |
| 48 | + |
| 49 | + if (\strlen($text) <= 0) { |
| 50 | + return 'n-a'; |
| 51 | + } |
| 52 | + |
| 53 | + return $text; |
| 54 | + } |
| 55 | +} |
0 commit comments