forked from FriendsOfSymfony/FOSUserBundle
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUserToUsernameTransformer.php
More file actions
84 lines (73 loc) · 2.24 KB
/
Copy pathUserToUsernameTransformer.php
File metadata and controls
84 lines (73 loc) · 2.24 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/*
* This file is part of the FOSUserBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\UserBundle\Form\DataTransformer;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
/**
* Transforms between a UserInterface instance and a username string.
*
* @author Thibault Duplessis <thibault.duplessis@gmail.com>
*
* @template-implements DataTransformerInterface<UserInterface, string>
*/
final class UserToUsernameTransformer implements DataTransformerInterface
{
/**
* @var UserManagerInterface
*/
private $userManager;
/**
* UserToUsernameTransformer constructor.
*/
public function __construct(UserManagerInterface $userManager)
{
$this->userManager = $userManager;
}
/**
* Transforms a UserInterface instance into a username string.
*
* @param UserInterface|null $value UserInterface instance
*
* @return string|null Username
*
* @throws UnexpectedTypeException if the given value is not a UserInterface instance
*/
public function transform($value): ?string
{
if (null === $value) {
return null;
}
if (!$value instanceof UserInterface) {
throw new UnexpectedTypeException($value, 'FOS\UserBundle\Model\UserInterface');
}
return $value->getUsername();
}
/**
* Transforms a username string into a UserInterface instance.
*
* @param string $value Username
*
* @return UserInterface|null the corresponding UserInterface instance
*
* @throws UnexpectedTypeException if the given value is not a string
*/
public function reverseTransform($value): ?UserInterface
{
if (null === $value || '' === $value) {
return null;
}
if (!is_string($value)) {
throw new UnexpectedTypeException($value, 'string');
}
return $this->userManager->findUserByUsername($value);
}
}