Symfony 5 NelmioDocsBundle 和 JMS Seralizer

问题描述

在理解标题中的工具组合时有点困难。

当我查看我的文档时,模型是空的:

Empty Models

也就是说,我已经尝试了很多方法,包括禁用 jms,但我想使用 JMS。

这是我的配置:

nelmio_api_doc.yaml:

nelmio_api_doc:
  models:
    use_jms: true
  documentation:
    host: cms-api.example.com
    schemes: [ http,https ]
    info:
      title: CMS API
      description: This is an awesome app!
      version: 1.0.0
    securityDefinitions:
      Bearer:
        type: apiKey
        description: 'Value: Bearer {jwt}'
        name: Authorization
        in: header
    security:
      - Bearer: [ ]
  areas:
    default:
      path_patterns: [ ^/api/v1/ ]

用户模型:

<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Nelmio\ApiDocBundle\Annotation\Model;
use Swagger\Annotations as SWG;
use JMS\Serializer\Annotation as Serializer;


/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @Serializer\ExclusionPolicy("all")
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @SWG\Property(description="The unique identifier of the user.")
     * @Serializer\Expose()
     * @Serializer\Type("int")
     * @Serializer\Groups({"default"})
     */
    private $id;

    /**
     * @ORM\Column(type="string",length=180,unique=true)
     * @SWG\Property(type="string",maxLength=255)
     * @Serializer\Expose()
     * @Serializer\Type("string")
     * @var string|null
     */
    private $email;

    /**
     * @ORM\Column(type="json")
     * @SWG\Property(type="array",@SWG\Items(type="string"))
     */
    private $roles = [];

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

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

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

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

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUserIdentifier(): 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 PasswordAuthenticatedUserInterface
     */
    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Returning a salt is only needed,if you are not using a modern
     * hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
     *
     * @see UserInterface
     */
    public function getSalt(): ?string
    {
        return null;
    }

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

用户控制器:

<?php

namespace App\Controller\api\v1;

use App\Entity\User;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Swagger\Annotations as SWG;
use Nelmio\ApiDocBundle\Annotation\Model;
use Nelmio\ApiDocBundle\Annotation\Security;

final class UserController extends AbstractRESTController
{
    /**
     * @Route("/api/v1/user",name="user_get_all_v1",methods={"GET"})
     * @SWG\Response(
     *     response=200,*     description="Returns the rewards of an user",*     @SWG\Schema(
     *         type="array",*         @SWG\Items(ref=@Model(type=User::class,groups={"full"}))
     *     )
     * )
     * @SWG\Tag(name="User")
     * @Security(name="Bearer")
     */
    public function getAllUsers(): JsonResponse
    {
        return $this->respond(['hello' => 'world']);
    }

    /**
     * @Route("/api/v1/user/{id}",name="user_get_one_v1",methods={"GET"})
     * @param User $user
     * @SWG\Response(
     *     response=200,groups={"full"}))
     *     )
     * )
     * @SWG\Tag(name="User")
     * @Security(name="Bearer")
     *
     * @return JsonResponse
     */
    public function getOneUser(User $user): JsonResponse
    {
        return $this->respond([
            'id' => $user->getId(),'email' => $user->getEmail()
        ]);
    }
}

任何帮助或想法都会很棒,我尝试向 id 添加一个组,但仍然无效,我将其留在代码示例中。我错过了什么?

解决方法

一个原因可能是在您的控制器方法注释中您使用了一个名为 full 的组,但我没有看到该组在您的 User 类中应用的位置。

因此,您必须从控制器注释中删除 groups={"full"}(或将其替换为 User 类中使用的 default),或在 User 模型中添加该组,例如像这样 {{ 1}}。

可能有其他原因导致文档无法正常工作,但您绝对应该修复组名。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...