I have a stdClass object $patient
that is the result of a webservice call. I also have an array of changes $changes
that I want to make to that object. But I can't get a reference to the nested properties the way I want. The stdClass looks something like this:
"Patient": {
"PatientID": 649,
"PatientClinicalInfo": {
"Gender": "Male",
},
"PatientGeneralInfo": {
"BillingAddress": {
"AddressLine1": "123 MAIN ST",
"AddressLine2": "APT B",
"City": "SPRINGFIELD",
"PostalCode": "49024",
"State": "MI"
},
"BillingContactInfo": {
"EmailAddress": "user@domain.com",
"PhoneNumber": "3185189415"
},
"DeliveryAddress": {
"AddressLine1": "123 MAIN ST",
"AddressLine2": "APT B",
"City": "SPRINGFIELD",
"PostalCode": "49024",
"State": "Michigan"
},
"DeliveryPhone": "3185189415",
"Name": {
"First": "Gonna",
"Last": "Sick",
"Middle": "B"
}
}
}
The array of changes looks something like this:
['delivery_address2' => 'APT 2B', 'primary_phone' => '2695551212']
This is what I was hoping to do (but this code does not work):
private function applyChangesToPatient(array $changes, stdClass $patient): stdClass
{
$newPatient = $patient;
$fieldMap = [
'delivery_address1' => 'PatientGeneralInfo->DeliveryAddress->AddressLine1',
'delivery_address2' => 'PatientGeneralInfo->DeliveryAddress->AddressLine2',
'primary_phone' => 'PatientGeneralInfo->BillingContactInfo->PhoneNumber',
];
foreach ($changes as $key => $value) {
if (isset($fieldMap[$key])){
$path = $fieldMap[$key];
$newPatient->$path = $value; // This doesn't work!
}
}
return $newPatient;
}
What I've tried
There are lots of tips on stackoverflow for iterating through the object and get the values, that's not what I want.
I've tried lots of different combinations of $$path
and ${$path}
, but I just can't seem to convert the string 'PatientGeneralInfo->DeliveryAddress->AddressLine1'
to an actual reference to that property in the stdClass.
I have tried this, and it works. But I don't like it.
private function applyChangesToPatient(array $changes, stdClass $patient): stdClass
{
$newPatient = $patient;
foreach ($changes as $key => $value) {
switch ($key) {
case 'delivery_address2':
$newPatient->PatientGeneralInfo->DeliveryAddress->AddressLine2 = $value;
break;
case 'primary_phone':
$newPatient->PatientGeneralInfo->BillingContactInfo->PhoneNumber = $value;
break;
// etc. etc.
}
}
return $newPatient;
}
I really want to use that $fieldMap
array. If that works, I can store the mapping in a separate JSON file and then easily add new mappings when needed -- without the need to change my code!
So, stackoverflow Community? Can you help me?