提供的值无效(IRI无效?)测试api-platform端点时出错

问题描述 投票:6回答:2

我有一个Product实体,与另一个具有关系manyToOne的User实体相关

class Product implements AuthoredEntityInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;

/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="products")
* @ORM\JoinColumn(nullable=false)
*/
private $user;

/**
* @ORM\Column(type="string", length=255)
*/
private $name;

/**
* @ORM\Column(type="double")
*/
private $price;

//various getters and setters

}

AuthoredEntityInterface有助于将用户设置为当前登录用户。当我对/ api / products(我使用postman)发出api调用时,传递一个像这样的json:

{
    "name": "my product",
    "price": 10
}

这有效,并创建了一条新记录。问题在于单元测试。我这样打电话:

$headers = [
        'HTTP_AUTHORIZATION' => 'Bearer ' . $token,
        'CONTENT_TYPE' => 'application/ld+json',
        'HTTP_ACCEPT' => 'application/ld+json'
    ];
$postData = [
    'name' => 'my product',
    'price' => 10
];
$client = $this->makeClient();
    $client->request('POST', '/api/products', [], [], $headers, json_encode($postData));

我收到此错误:提供的值无效(IRI无效?)

现在唯一的IRI指的是用户,如上所述是在类中自动生成的。

任何的想法?

更新:

填充用户字段

产品中的方法

public function setUser(UserInterface $user): AuthoredEntityInterface
{
    $this->user = $user;
    return $this;
}

然后我使用事件订阅者:

class AuthoredEntitySubscriber implements EventSubscriberInterface
{
/** @var TokenStorageInterface */
private $tokenStorage;

public function __construct(TokenStorageInterface $tokenStorage)
{
    $this->tokenStorage = $tokenStorage;
}

public static function getSubscribedEvents()
{
    return [
        KernelEvents::VIEW => ['getAuthenticatedUser', EventPriorities::PRE_WRITE]
    ];
}

public function getAuthenticatedUser(GetResponseForControllerResultEvent $event)
{
    $entity = $event->getControllerResult();
    $method = $event->getRequest()->getMethod();

    /** @var UserInterface $user */
    $user = $this->tokenStorage->getToken()->getUser();

    if((!$entity instanceof AuthoredEntityInterface) || Request::METHOD_POST != $method) {
        return;
    }

    $entity->setUser($user);
}
}
php symfony api-platform.com
2个回答
0
投票

您必须将$postData编码为您想要的内容类型,例如。 JSON和编码数据必须传递到$client->request()


0
投票

我很确定你遇到了我曾经遇到过的同样的错误,身份验证凭据不应该在请求头中传递,它应该通过客户端传递。

样品:

$credentials = array(
    'HTTP_AUTHORIZATION' => 'Bearer ' . $token,
);

$client = $this->makeClient($credentials);

还要确保HTTP_AUTHORIZATION是您需要使用的正确名称。很多时候它只是授权。

回顾那里的请求标头和客户端标头。确保您在客户端标头中设置auth。

© www.soinside.com 2019 - 2024. All rights reserved.