【问题标题】:FosRestBundle PATCH action prevent update entity with null/default valuesFosRestBundle PATCH 操作防止使用空值/默认值更新实体
【发布时间】:2016-03-31 14:03:29
【问题描述】:

我在我的serverController 上创建了一个有效的patchAction 来更新现有服务器中的一个或某些字段。

其实我的patchAction是这样的

/*
 * @ParamConverter("updatedServer", converter="fos_rest.request_body")
 *
 * @return View
 */
public function patchAction(Server $server, Server $updatedServer, ConstraintViolationListInterface $validationErrors)
{
    if ($validationErrors->count() > 0) {
        return $this->handleBodyValidationErrorsView($validationErrors);
    }

    $server->setAlias($updatedServer->getAlias())
        ->setMac($updatedServer->getMac())
        ->setSshUser($updatedServer->getSshUser())
        ->setSshPort($updatedServer->getSshPort())
        ->setIpmiAddress($updatedServer->getIpmiAddress())
        ->setIpmiLogin($updatedServer->getIpmiLogin())
        ->setIpmiPassword($updatedServer->getIpmiPassword())
        ->setMysqlHost($updatedServer->getMysqlHost())
        ->setMysqlRoot($updatedServer->getMysqlRoot())
        ->setWebServer($updatedServer->getWebServer())
        ->setWebServerSslListen($updatedServer->getWebServerSslListen())
        ->setWebServerSslPort($updatedServer->getWebServerSslPort())
        ->setMysqlServer($updatedServer->getMysqlServer())
        ->setSuphp($updatedServer->getSuphp())
        ->setFastcgi($updatedServer->getFastcgi())
        ->setNadminCompliant($updatedServer->getNadminCompliant())
        ->setEmailCompliant($updatedServer->getEmailCompliant())
        ->setAvailable($updatedServer->getAvailable())
        ->setEnvironment($updatedServer->getEnvironment())
        ->setInstalledAt($updatedServer->getInstalledAt());

    if (null !== $updatedServer->getOs()) {
        $os = $this->getDoctrine()->getRepository('AppBundle:Os')->findBy(['id' => $updatedServer->getOs()->getId()]);
        $server->setOs($os[0]);
    }

    if (null !== $updatedServer->getPuppetClasses()) {
        $puppetClass = $this->getDoctrine()->getRepository('AppBundle:PuppetClass')->findBy(['id' => $updatedServer->getPuppetClasses()[0]->getId()]);
        $server->setPuppetClasses($puppetClass);
    }

    if (null !== $updatedServer->getPuppetTemplates()) {
        $puppetTemplate = $this->getDoctrine()->getRepository('AppBundle:PuppetTemplate')->findBy(['id' => $updatedServer->getPuppetTemplates()[0]->getId()]);
        $server->setPuppetTemplates($puppetTemplate);
    }

    if (null !== $updatedServer->getBackupModel()) {
        $backupModel = $this->getDoctrine()->getRepository('AppBundle:BackupModel')->findBy(['id' => $updatedServer->getBackupModel()->getId()]);
        $server->setBackupModel($backupModel[0]);
    }

    $em = $this->getDoctrine()->getManager();

    $em->persist($server);
    $em->flush();

    return $this->view([$updatedServer, $server]);
}

问题在于尝试仅更新一个或几个字段时。我设置了一个 JSON 正文来更改数据。

{
    "mac": "ff:ff:ff:ff:ff:ff"
}

我发送请求后 JSON 正文将如下所示

// This is what $updatedServer get in my controller
{
    "id": null,
    "name": null,
    "alias": null,
    "notes": null,
    "hosted_domain": null,
    "mac": "ff:ff:ff:ff:ff:ff",
    // ...
}

正如您在我的控制器中看到的,我已经设置了每个可更新字段

$server->setAlias($updatedServer->getAlias())
    ->setMac($updatedServer->getMac())
    ->setSshUser($updatedServer->getSshUser())
    // ...

因此,如果主体请求中的值为null,控制器会将其设置为null,它将对实体内部设置的默认值执行相同操作

我的想法是为每个可更新字段创建一个 if 条件,但我将在里面有 >20 个条件...

如何防止这种附加到通用和可重复使用的系统?

如果在请求执行之前没有设置这些值可以忽略吗?

也许在我的实体类中创建callback

谢谢

编辑

我的Server $server 是我要更新的当前服务器对象。它伴随着请求而来。例如,当我发送此请求 /api/servers/2 时,我会得到 ID 为 2 的服务器主体。

Server $updatedServer 是包含更新数据的主体。

我尝试了您的第二次编辑,但我收到了 500 error

“无法从请求信息中猜测如何获取Doctrine实例。”

因为我无法同时获得我要修补的服务器和主体(带有ParamConverter)。

【问题讨论】:

  • 我更新了答案。

标签: php symfony fosrestbundle


【解决方案1】:

您可以通过使用PATCH 方法来防止这种情况,就像the specification 解释它(正确的方法)。

顾名思义,PATCH 方法用于发送更新现有资源的补丁。

要正确使用它,您需要发送资源的全新状态。
换句话说,您必须发送资源的所有属性,包括未更改的属性。

因此,如果您发送每个属性及其对应的值,您的补丁将被正确应用。

例子:

{
    "id": 1, # Identifier, never change
    "name": [oldValue],
    "alias": [oldValue],
    "notes": [oldValue],
    "hosted_domain": [oldValue],
    "mac": "ff:ff:ff:ff:ff:ff",
    // ...    
}

像这样,不需要为每个属性写检查。

William Durand 的 Don't PATCH like an idiot 很好地引用了这种常见的错误用法。

编辑

我错了。

您无需完全更新资源即可正确使用 PATCH。 您需要发送一组更改,如给定链接中所述。

我能给你的更好的建议是使用ParamConverter,它通过它的标识符检索你的对象,并根据你给它的字段为你做更新。

EDIT2

我的意思是:

/*
 * @ParamConverter("server", converter="fos_rest.request_body")
 *
 * @return View
 */
public function patchAction(Server $server, ConstraintViolationListInterface $validationErrors)
{
    if ($validationErrors->count() > 0) {
        return $this->handleBodyValidationErrorsView($validationErrors);
    }

    $em = $this->getDoctrine()->getManager();

    $em->persist($server);
    $em->flush();
    
    // ...
}

否则,您需要一个 Assembler 对象用作合并的中间步骤。
请参阅handling PATCH requests through FOSRest 这个很好的例子。

【讨论】:

  • 你能解释一下这个use a ParamConverter that retrieves your object by its identifier吗?我真的不明白这是什么意思。我在ParamConverter doc 上进行了搜索,但这并没有帮助我更多。
  • 我刚刚看到您已经在使用 ParamConverter。你能告诉我你的Server $server是从哪里来的吗?为什么不让 ParamConverter 转换 server 而不是 updatedServer 而不是手动调用 setter?这将在验证后直接从请求正文更新您的资源,顺便说一句,避免了这个问题。
【解决方案2】:

我刚刚找到了那个问题的答案

在您的实体中使用设置参数函数,该函数将更新您将在请求正文中提供的字段

应用\实体\服务器

use Doctrine\Common\Inflector\Inflector;

public class Server {

    public function setParameters($params) {
        foreach ($params as $k => $p) {
            if (!is_null($p)) { // here is the if statement
                $key = Inflector::camelize($k);
                if (property_exists($this, $key)) {
                    $this->{'set' . ucfirst($key)}($p);
                }
            }
        }
        return $this;
    }
}

App\Controller\ServerApiController

public function patchAction(Server $server, Request $request, ConstraintViolationListInterface $validationErrors)
{
    if ($validationErrors->count() > 0) {
        return $this->handleBodyValidationErrorsView($validationErrors);
    }

    $data = json_decode($request->getContent());
    $em->persist($server->setParameters($data););
    $em->flush();

    return $this->view([$server]);
}

它应该返回服务器的内容 + 由您的请求正文更新的字段,这将在 $server->setParameter($data) 中更改

【讨论】:

    猜你喜欢
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多