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

Time:04-26

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 ?

CodePudding user response:

$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

CodePudding user response:

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)
  • Related