标签: api-platform.com

在 Symfony 5 上使用 DateTime 约束时,为什么会收到“此值应为字符串类型”?

我有以下实体(仅附上相关部分):

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ApiResource(mercure=true)
 * @ORM\Entity(repositoryClass="App\Repository\EventRepository")
 */
class Event {
    /**
     * @ORM\Column(type="datetime")
     * @Assert\DateTime
     * @Assert\NotNull
     */
    private $createdAt;

    public function __construct() {
        $this->createdAt = new \DateTime();
    }

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

    public function setCreatedAt(\DateTimeInterface $createdAt): self {
        $this->createdAt = $createdAt;
        return $this;
    }
}
Run Code Online (Sandbox Code Playgroud)

它的存储库:

class EventRepository extends ServiceEntityRepository {
    public function __construct(ManagerRegistry $registry) {
        parent::__construct($registry, Event::class);
    }
}
Run Code Online (Sandbox Code Playgroud)

向事件端点(通过 Postman 或 Swagger UI)创建 …

php symfony symfony-validator api-platform.com symfony5

13
推荐指数
1
解决办法
4042
查看次数

Symfony4:无法找到路径"/ api/login_check"的控制器.路由配置错误

我想通过JWT设置symfony4 api JSON登录.安装了api平台核心软件包,我按照以下说明操作:https://api-platform.com/docs/core/jwt/

我按照描述创建了自定义用户提供程序.通过打开URL/api/login_check错误消息"无法找到路径控制器"/ api/login_check".路由配置错误." 发生.

通过发送POST请求,我得到了html中的错误页面.

这是我的routes.yaml:

#index:
#    path: /
#    controller: App\Controller\DefaultController::index
api_login_check:
    path: /api/login_check
Run Code Online (Sandbox Code Playgroud)

这是我的security.yaml:

security:
    encoders:
        App\Security\User\WebserviceUser: bcrypt
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        webservice:
          id: App\Security\User\WebserviceUserProvider
        in_memory: { memory: ~ }
        main:
          entity: { class: App\Entity\User, property: email }
    firewalls:
        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            provider: webservice
            json_login:
                check_path: /api/login_check
                username_path: email
                password_path: password
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
        api:
            pattern: ^/api
            provider: webservice
            stateless: true
            guard:
                authenticators:
                    - …
Run Code Online (Sandbox Code Playgroud)

jwt lexikjwtauthbundle api-platform.com symfony4

12
推荐指数
4
解决办法
4064
查看次数

Api 平台处理填充上传

我正在尝试使用 Api Platform 和 Vich Uploader Bundle 上传文件。当我发送带有 multipart/form-data 和实体 ID 的 POST 请求以附加图像文件时,我的实体收到 200 响应。但是上传的文件不会上传到目标目录,并且生成的文件名不会保留。没有错误,没有任何线索,不知道。

这是我的代码:

//vich uploader mappings
vich_uploader:
    db_driver: orm
    mappings:
        logo:
            uri_prefix: /logo
            upload_destination: '%kernel.project_dir%/public/images/logo/'
            namer: App\Infrastructure\Naming\LogoNamer
Run Code Online (Sandbox Code Playgroud)
//Organization Entity
<?php

namespace App\Infrastructure\Dto;

...use

/**
 * @ORM\Entity()
 * @ApiResource(
 *     iri="https://schema.org/Organization",
 *     shortName="Place",
 *     collectionOperations={
 *          "post" = {
 *              "denormalization_context" = {
 *                  "groups"={
 *                      "organization:collection:post"
 *                  }
 *              }
 *          },
 *          "get" = {
 *              "normalization_context" = {
 *                  "groups"={
 *                      "organization:collection:get"
 *                  } …
Run Code Online (Sandbox Code Playgroud)

php vichuploaderbundle api-platform.com symfony5

10
推荐指数
2
解决办法
3000
查看次数

唯一约束返回类型不匹配

我有这个用户实体。

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ApiResource(
 *     collectionOperations={
 *          "register"={
 *              "method"="POST",
 *              "path"="/users/register",
 *              "denormalization_context"={"groups"={"register"}},
 *              "normalization_context"={"groups"={"read"}},
 *              "validation_groups"={"register"},
 *              "swagger_context"={
 *                  "summary"="Register a user",
 *                  "description"="For anonymous user to register an account."
 *              }
 *          }
 *     }
 * )
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    const ROLE_USER = 'ROLE_USER';
    const ROLE_WEBADMIN = 'ROLE_WEBADMIN';
    const ROLE_SUPERADMIN = 'ROLE_SUPERADMIN';

    const …
Run Code Online (Sandbox Code Playgroud)

php symfony api-platform.com symfony-4.3

9
推荐指数
1
解决办法
2517
查看次数

API 平台 - 我应该使用哪种方法来创建没有实体的自定义操作

我是 API 平台的新手。我认为这很棒,但我找不到任何示例如何创建不基于任何实体的自定义端点。有很多基于实体的例子,通常都是关于 CRUD 的。但是自定义操作呢?

我需要使用一些与任何实体无关的自定义参数通过数据库创建自定义搜索。例如,我想接收这样的 POST 请求:

{
   "from": "Paris",
   "to": "Berlin"
}
Run Code Online (Sandbox Code Playgroud)

这些数据没有保存到数据库中,我也没有实体。收到这些数据后,应该有很多业务逻辑,包括通过大量数据库表进行数据库查询以及从外部来源获取数据。然后,在业务逻辑完成后,我想返回结果,该结果也是自定义的,与任何实体无关。例如

{
    "flights": [/* a lot of json data*/],
    "airports": [/* a lot of json data*/],
    "cities": [/* a lot of json data*/],
    .......
}
Run Code Online (Sandbox Code Playgroud)

所以,我想我不是唯一一个做类似事情的人。但我真的找不到如何做到这一点的解决方案或最佳实践。在文档中,我找到了至少三种方法,但我无法实现它们中的任何一种。最好的,我想最适合我的是使用自定义操作和控制器。但是文档说不推荐使用这个。此外,我认为我应该将 DTO 用于请求和响应,但对于这种方法,我不确定我是否可以使用它们。

第二个我发现它使用数据传输对象,但这种方法需要一个实体。根据文档,我应该使用 DTO 和 DataTransformers 将 DTO 转换为实体。但我不需要实体,我不需要将它保存到数据库。我只想自己处理收到的 DTO。

第三个我猜它是使用数据提供程序,但我不确定它是否适合我的要求。

因此,主要问题是我应该使用哪种方法或最佳实践来实现与任何实体无关的自定义操作。将 DTO 用于请求和响应将非常有用。

api-platform.com

9
推荐指数
1
解决办法
2660
查看次数

dockerfile 解析错误第 63 行:未知标志:链接

终端

COMPOSE_DOCKER_CLI_BUILD=1 COMPOSE_DOCKER_CLI_LINK=1 DOCKER_BUILDKIT=1 docker-compose up --build
Run Code Online (Sandbox Code Playgroud)

输出

Successfully built fe4aa685d34a0cdeb29c4af824f2cfa7c11a6d036ee85ee19bd7615a518d80a9
Building php
[+] Building 0.8s (4/4) FINISHED                                                                                                                                      
 => [internal] load build definition from Dockerfile                                                                                                             0.0s
 => => transferring dockerfile: 38B                                                                                                                              0.0s
 => [internal] load .dockerignore                                                                                                                                0.1s
 => => transferring context: 35B                                                                                                                                 0.0s
 => resolve image config for docker.io/docker/dockerfile:experimental                                                                                            0.4s
 => CACHED docker-image://docker.io/docker/dockerfile:experimental@sha256:600e5c62eedff338b3f7a0850beb7c05866e0ef27b2d2e8c02aa468e78496ff5                       0.0s
failed to solve with frontend dockerfile.v0: failed to solve with frontend gateway.v0: rpc error: code = Unknown desc = failed to create LLB definition: 

dockerfile parse …
Run Code Online (Sandbox Code Playgroud)

docker-compose api-platform.com

9
推荐指数
3
解决办法
8178
查看次数

UML/API:如何为RESTful API建模

我需要为使用API​​ Platform和Symfony 3.2(后端)和Ionic 2(前端)开发的RESTFul API创建UML类图和用例图.但我不知道如何通过类图描述我的后端API的结构.

如果有人有任何想法或可能有任何帮助,我真的很感激.谢谢!

api rest uml symfony api-platform.com

8
推荐指数
2
解决办法
1万
查看次数

Symfony - API 平台 - 文件上传

我正在尝试按照文档使用API PLatform实现文件上传使用 Vich使用。但它不起作用,准确地说,MediaObject 没有被我根据我的请求发送的文件水合。

我完全遵循 API Platform 提供的说明书,但我的表单似乎没有很好地处理请求,因为它没有通过约束验证,我从 API 得到了这个答案:

{
    "type": "https:\/\/tools.ietf.org\/html\/rfc2616#section-10",
    "title": "An error occurred",
    "detail": "file: This value should not be null.",
    "violations": [
        {
        "propertyPath": "file",
        "message": "This value should not be null."
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我的要求是基本的:标头是 multipart/form-data,我发送一个小文件 (78Ko):"file" => image.jpg

当我转储 $request 对象时,文件在其中,但 $form->getData() 没有被水合。知道为什么吗?

这是我的 MediaObject :

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Traits\updatedAt;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Entity\File;
use Vich\UploaderBundle\Mapping\Annotation …
Run Code Online (Sandbox Code Playgroud)

file-upload symfony vichuploaderbundle api-platform.com

8
推荐指数
1
解决办法
4644
查看次数

如何让 API 平台加载相关(例如 Many2One)资源/实体?

根据文档,api-platform默认会立即加载相关资源。

但在默认配置上,我对具有关系的资源(主要是典型Many2One关系)的所有查询都会使用对象 IRI 而不是序列化对象来填充这些属性。

例如,对于这个实体:

/**
 * @ORM\Entity(repositoryClass="App\Repository\BoostLeadContactActionRepository")
 * @ORM\Table(name="BoostLeadContactActions")
 */
class BoostLeadContactAction {

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\BoostLead", inversedBy="contacts")
     * @ORM\JoinColumn(nullable=false)
     */
    private $boostLead;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\ContactChannel", fetch="EAGER")
     * @ORM\JoinColumn(nullable=false, referencedColumnName="Id")
     */
    private $channel;

    // getters/setters/extra properties removed for brevity
}
Run Code Online (Sandbox Code Playgroud)

那么我们就有了对应的ContactChannel

/**
 * ContactChannel
 *
 * @ORM\Table(name="ContactChannels")
 * @ORM\Entity
 */
class ContactChannel {

    /**
     * @var int
     *
     * @ORM\Column(name="Id", type="smallint", nullable=false, options={"unsigned"=true})
     * …
Run Code Online (Sandbox Code Playgroud)

php doctrine symfony api-platform.com

8
推荐指数
1
解决办法
5345
查看次数

如何将依赖于API-Platform的序列化组的属性公开给react-admin?

我在我的应用程序中动态更改序列化上下文admin:write在用户是管理员时应用该组.这样管理员的用户就可以更新此属性.

上下文构建器具有以下配置:

<?php

namespace App\Serializer;

use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class AdminContextBuilder implements SerializerContextBuilderInterface
{
    private $decorated;
    private $authorizationChecker;

    public function __construct(SerializerContextBuilderInterface $decorated, AuthorizationCheckerInterface $authorizationChecker)
    {
        $this->decorated = $decorated;
        $this->authorizationChecker = $authorizationChecker;
    }

    public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
    {
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);

        if (isset($context['groups']) && $this->authorizationChecker->isGranted('ROLE_ADMIN') && false === $normalization) {
            $context['groups'][] = 'admin:write';
        }
        if (isset($context['groups']) && $this->authorizationChecker->isGranted('ROLE_ADMIN') && true === $normalization) { …
Run Code Online (Sandbox Code Playgroud)

php symfony api-platform.com symfony4 react-admin

7
推荐指数
1
解决办法
405
查看次数