Skip to content

Commit 7049893

Browse files
committed
Added the truncateFileName(filename, length) function
1 parent 16b27a8 commit 7049893

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/StringExpressionLanguageProvider.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public function getFunctions(): array
1616
new FileName('fileName'),
1717
new DateTime('dateTime'),
1818
new FormatDate('formatDate'),
19+
new TruncateFileName('truncateFileName'),
1920
];
2021
}
2122
}

src/TruncateFileName.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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 TruncateFileName extends ExpressionFunction
10+
{
11+
public function __construct($name)
12+
{
13+
parent::__construct(
14+
$name,
15+
\Closure::fromCallable([$this, 'compile'])->bindTo($this),
16+
\Closure::fromCallable([$this, 'evaluate'])->bindTo($this)
17+
);
18+
}
19+
20+
private function compile(string $filename, string $length)
21+
{
22+
return <<<PHP
23+
(
24+
!\\is_string({$filename}) ?
25+
null :
26+
(
27+
\\strlen(\$basename = \\pathinfo({$filename}, \\PATHINFO_BASENAME)) > $length ?
28+
\$basename . '.' . \\pathinfo({$filename}, \\PATHINFO_EXTENSION) :
29+
{$filename}
30+
)
31+
)
32+
PHP;
33+
}
34+
35+
private function evaluate(array $context, string $filename, int $length)
36+
{
37+
return !\is_string($filename) ?
38+
null :
39+
(
40+
\strlen($basename = \pathinfo($filename, \PATHINFO_BASENAME)) > $length ?
41+
$basename . '.' . \pathinfo($filename, \PATHINFO_EXTENSION) :
42+
$filename
43+
);
44+
}
45+
}

0 commit comments

Comments
 (0)