比方說,我有以下響應來自API調用來:如何在Symfony 3中使用回調或任何其他方法規範給定屬性?
[
{
"AgreementNumber": 20266,
"StartDate": "2005-07-01T00:00:00",
"EndDate": "2006-06-30T00:00:00",
"AgreementTypeId": 1,
"CfProgramLevelId": 2,
"TamFlag": 0,
"ParentAgreementNumber": null,
"DistributorId": 16,
"CustomerSiteId": 232,
"RowId": 100,
"Source": "Wonderware",
"ActiveFlg": 1
},
...
]
我作圖,結果到Agreement
實體如下:
$propertyNameConverter = new PropertyNameConverter();
$encoders = [new XmlEncoder(), new JsonEncoder()];
$normalizers = [new ObjectNormalizer(null, $propertyNameConverter), new ArrayDenormalizer(),];
$serializer = new Serializer($normalizers, $encoders);
$entities = $serializer->deserialize($data, "QuoteBundle\\Entity\\Agreement[]", 'json');
這是實體的樣子:
class Agreement
{
/**
* @var \DateTime
* @ORM\Column(name="StartDate", type="string", nullable=false)
*/
private $startDate;
/**
* @ORM\OneToOne(targetEntity="QuoteBundle\Entity\AgreementType")
* @ORM\JoinColumn(name="AgreementTypeID", referencedColumnName="AgreementTypeID")
*/
private $agreementType;
/**
* @param \DateTime $startDate
*/
public function setStartDate(\DateTime $startDate)
{
$this->startDate = $startDate;
}
/**
* @param AgreementType $agreementType
*/
public function setAgreementType(AgreementType $agreementType)
{
$this->agreementType = $agreementType;
}
}
每次我嘗試映射數據時,我得到以下錯誤:
Expected argument of type "DateTime", "string" given
這很好,因爲我期待DateTime
作爲startDate
。這裏的解決方案是在將數據映射到實體之前對數據進行標準化。
我已閱讀here但我找不到如何將此回調應用於給定的屬性,因爲該示例是一個簡單的用例,而不是複雜的用例。
我曾嘗試下面的代碼:
$dateTimeNormalizer = new GetSetMethodNormalizer();
$dateTimeCallback = function ($dateTime) {
return $dateTime instanceof \DateTime ? $dateTime->format(\DateTime::ATOM) : '';
};
$dateTimeNormalizer->setCallbacks(['startDate' => $dateTimeCallback, 'endDate' => $dateTimeCallback]);
$normalizers = [
new ObjectNormalizer(null, $propertyNameConverter),
new ArrayDenormalizer(),
$dateTimeNormalizer,
];
$serializer = new Serializer($normalizers, $encoders);
但不工作,因爲我仍然得到同樣的錯誤如上。我知道有一個DateTimeNormalizer,但添加它作爲$normalizers
陣列上的新條目不會使其工作。結果與上面相同的含義具有相同的錯誤。
此外,我還需要一個回調來將屬性AgreementTypeId
標準化爲agreementType
,因爲我確信它也會失敗。 (實際上目前沒有被映射,我認爲問題是因爲名稱不匹配)
任何人都可以幫我弄清楚這一點嗎?