'what's the right way to set entity fields from optional fields in Symfony

i'm using the following pattern in symfony

        if (!empty($pssItem["ip"])) $bookingAdditionalInfo->setIpAddress($pssItem["ip"]);
        if (!empty($pssItem["ipLocation"])) $bookingAdditionalInfo->setIpAddressLocation($pssItem["ipLocation"]);
        if (!empty($pssItem["userAgent"])) $bookingAdditionalInfo->setUserAgent($pssItem["userAgent"]);
        if (!empty($pssItem["utmCampaign"])) $bookingAdditionalInfo->setUtmCampaign($pssItem["utmCampaign"]);
        if (!empty($pssItem["utmChannel"])) $bookingAdditionalInfo->setUtmChannel($pssItem["utmChannel"]);
        if (!empty($pssItem["utmMedium"])) $bookingAdditionalInfo->setUtmMedium($pssItem["utmMedium"]);
        if (!empty($pssItem["utmSource"])) $bookingAdditionalInfo->setUtmSource($pssItem["utmSource"]);

is there a way to make this beautiful ?



Solution 1:[1]

I'd start by addressing the inconsistencies:

The ip parameter uses the setIpAddress method, and the ipLocation parameter uses the setIpAddressLocation method.

Once you address the inconsistencies, such as by setting up setIp and setIpAddress methods, you could move over to a loop:

$keys = [
    'ip', 'ipLocation', 'userAgent',
    'utmCampaign', 'utmChannel', 'utmMedium', 'utmSource'
    // note you may want to include other utm possibilities here

];

foreach ($keys as $key) {
    if (!empty($pssItem[$key])) {
        $bookingAdditionalInfo->{'set'.ucfirst($key)}($pssItem[$key]);
    }
}

You might also consider storing such parameters as an array rather than a series of functional calls.

$bookingAdditionalInfo->setParameters($pssItem)

Solution 2:[2]

$reflect          = new \ReflectionClass($bookingAdditionalInfo);    
$propertyAccessor = PropertyAccess::createPropertyAccessor();

foreach ($reflect->getProperties() as $property) {
    $propertyName = $property->getName();

    if (!empty($pssItem[$propertyName])) {
        $propertyAccessor->setValue($bookingAdditionalInfo, $property, $pssItem[$propertyName]);
    }
}

But you should change mismatching properties or array keys, like ipAddressLocation and ipLocation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin Y
Solution 2 Artem