Symfony 按表单处理 Api 请求

Symfony handle Api request by form

我将 Symfony 4.4 用作 restful API,完全没有视图。我想避免像这样烦人的代码:


        $email = $request->get('email');
        $password = $request->get('password');
        $newUser = new User();
        $newUser->setEmail($email)->setPassword($password));

因为如果一个实体有很多属性,我必须花费大量时间从 request->get('property') 获取每个变量。所以我决定尝试使用 Symfony 表单。

但我总是得到这个错误:

Expected argument of type \"array\", \"null\" given at property path \"roles\"."

我的用户class

<?php

namespace App\Entity;

use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"public"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     * @Assert\Email
     * @Assert\NotBlank
     * @Assert\NotNull
     * @Groups({"public"})
     */
    private $email;

    /**
     * @ORM\Column(type="json")
     * @Groups({"public"})
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     * @Assert\Type("string")
     * @Assert\NotBlank
     * @Assert\NotNull
     */
    private $password;

    /**
     * @ORM\Column(type="datetime")
     * @Groups({"public"})
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     * @Groups({"public"})
     */
    private $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Log", mappedBy="user")
     */
    private $logs;

    /**
     * User constructor.
     */
    public function __construct()
    {
        $this->createdAt = new DateTime();
        $this->updatedAt = new DateTime();
        $this->logs = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = strtolower($email);

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string) $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;
        $this->updatedAt = new DateTime(); // updates the updatedAt field

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    /**
     * Get the value of createdAt
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set the value of createdAt
     *
     * @return  self
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(\DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @return Collection|Log[]
     */
    public function getLogs(): Collection
    {
        return $this->logs;
    }

    public function addLog(Log $log): self
    {
        if (!$this->logs->contains($log)) {
            $this->logs[] = $log;
            $log->setUser($this);
        }

        return $this;
    }

    public function removeLog(Log $log): self
    {
        if ($this->logs->contains($log)) {
            $this->logs->removeElement($log);
            // set the owning side to null (unless already changed)
            if ($log->getUser() === $this) {
                $log->setUser(null);
            }
        }

        return $this;
    }
}

我使用 makerbundle

创建的表格
class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options):void
    {
        $builder
            ->add('email')
            ->add('roles')
            ->add('password')
            ->add('createdAt')
            ->add('updatedAt')
        ;
    }

    public function configureOptions(OptionsResolver $resolver):void
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }

还有我的控制器

    public function postUsersAction(Request $request): View
    {

        $data = json_decode($request->getContent(), true);
        $user = new User();
        $form = $this->createForm(UserType::class);
        $form->handleRequest($request);
        $form->submit($data);

        return $this->view(['message' => $form->isValid()], Response::HTTP_OK); // for testing purposes

我通过邮递员发送的数据是这样的:

email=duuuu@gmail.com&password=1234

您的 setRoles 函数需要一个数组作为参数。但是,当您通过不向 url 传递任何值而将角色字段或值留空时,将提交 "null"。因此,您会收到一个错误消息,指出需要一个数组,但将 null 传递给了角色字段。

要在未提供值时将空数组设置为默认值,您可能需要查看表单字段的 "empty_data" 选项 (https://symfony.com/doc/current/reference/forms/types/form.html#empty-data)

所以在您的表单类型中,您可以这样做:

$builder->add('roles', null, ['empty_data' => []])

只要您提交没有角色值的表单,就会将角色设置为空数组。

如果您只想更新几个值(如在 PATCH 请求中),提交函数接受第二个参数,该参数定义缺失字段是否将被空值覆盖或从表单中删除 (https://symfony.com/doc/current/form/direct_submit.html)

通话中

$form->submit($data, false);

因此,将保持您的对象角色不变,并且仅更新您随请求传递的字段。

我找到了解决方案:

控制器:

        $user = new User();
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);
        $form->submit($request->request->all(), false);

        return $this->view(['message' => $form->isValid()], Response::HTTP_OK); // for testing purposes

而且我还必须通过以下方式禁用 csrf 保护:

 public function configureOptions(OptionsResolver $resolver):void
    {
        $resolver->setDefaults([
            'data_class' => User::class,
            'csrf_protection' => false,
        ]);
    }