我想创建未映射的实体端点,例如/api/v1/me返回User有关当前经过身份验证的用户的信息(对象)并将其添加到我的文档中。在计划中,我还想添加端点,如/api/v1/account/recover和/api/v1/account/verify-email。
我有一个动作:
namespace AppBundle\Action\Me;
use AppBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class MeView
{
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
/**
* @Security("is_authenticated()")
*
* @Route(
* name="me_view",
* path="/me",
* methods={"GET"}
* )
*
* @return User
*/
public function __invoke()
{
return $this->tokenStorage->getToken()->getUser();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试访问它时,它返回一个异常:
控制器必须返回一个响应(给出的对象(AppBundle\Entity\User))。(500内部服务器错误)
相同的动作,但映射到实体,效果很好:
namespace AppBundle\Action\City;
use AppBundle\Entity\City;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Routing\Annotation\Route;
class CityView
{ …Run Code Online (Sandbox Code Playgroud) 我需要验证用户传递的电子邮件:
private function validate($value): bool
{
$violations = $this->validator->validate($value, [
new Assert\NotBlank(),
new Assert\Email(),
new UniqueEntity([
'entityClass' => User::class,
'fields' => 'email',
])
]);
return count($violations) === 0;
}
Run Code Online (Sandbox Code Playgroud)
但UniqueEntity约束会引发异常:
警告:
get_class()期望参数1为object,给定字符串
看起来像ValidatorInterface::validate()方法的第一个参数等待实体对象与getEmail()方法,但它看起来很难看.
是否有任何优雅的方法来验证字段的唯一性只传递ValidatorInterface::validate()方法的标量值?