-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCapitalizeStringDataTransformer.php
More file actions
43 lines (34 loc) · 1.14 KB
/
CapitalizeStringDataTransformer.php
File metadata and controls
43 lines (34 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php declare(strict_types=1);
namespace SBSEDV\Bundle\FormBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
/**
* @implements DataTransformerInterface<string, string>
*/
class CapitalizeStringDataTransformer implements DataTransformerInterface
{
public function __construct(
private readonly ?string $encoding = null,
) {
}
public function transform(mixed $value): ?string
{
return $value;
}
public function reverseTransform(mixed $value): ?string
{
if (null === $value) {
return $value;
}
if (!\is_string($value)) { // @phpstan-ignore function.alreadyNarrowedType
throw new TransformationFailedException('Expected type string.');
}
return $this->mb_ucfirst($value);
}
private function mb_ucfirst(string $string): string
{
$firstChar = \mb_substr($string, 0, 1, $this->encoding);
$lastChars = \mb_substr($string, 1, null, $this->encoding);
return \mb_strtoupper($firstChar, $this->encoding).$lastChars;
}
}