Skip to content

Commit 94c8a49

Browse files
committed
Added a new expression to slugify a string
1 parent 137605e commit 94c8a49

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Slugify.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
}

src/StringExpressionLanguageProvider.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ public function getFunctions(): array
3737
new AsFloat('asFloat'),
3838
new AsInteger('asInteger'),
3939
new AsString('asString'),
40+
new Slugify('slugify'),
4041
];
4142
}
4243
}

0 commit comments

Comments
 (0)