From d7808e5e5a5372f3caca0430725d7670903000d3 Mon Sep 17 00:00:00 2001 From: Stefano Arlandini Date: Thu, 17 Jan 2019 17:56:01 +0100 Subject: [PATCH] Allow setting null on a custom field to unset it from a lead --- .../Library/JsonSerializableHelperTrait.php | 24 ++++++++++++++++- .../CloseIoApiWrapper/Model/Lead.php | 27 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/LooplineSystems/CloseIoApiWrapper/Library/JsonSerializableHelperTrait.php b/src/LooplineSystems/CloseIoApiWrapper/Library/JsonSerializableHelperTrait.php index 5705003..7a6c5b3 100644 --- a/src/LooplineSystems/CloseIoApiWrapper/Library/JsonSerializableHelperTrait.php +++ b/src/LooplineSystems/CloseIoApiWrapper/Library/JsonSerializableHelperTrait.php @@ -20,6 +20,28 @@ trait JsonSerializableHelperTrait */ public function jsonSerialize() { - return array_filter(get_object_vars($this)); + $objectVars = get_object_vars($this); + + // The `custom` object is deprecated and doesn't supports setting + // `null` values to unset a field from a lead, so when serializing + // to JSON we flat the pair or field name/field value in the root + // object using as name of the field `custom.` + if (isset($objectVars['custom'])) { + foreach ($objectVars['custom'] as $fieldName => $fieldValue) { + $objectVars['custom.' . $fieldName] = $fieldValue; + } + } + + unset($objectVars['custom']); + + $objectVars = array_filter($objectVars, static function ($value, $key): bool { + if (strpos($key, 'custom.') === 0) { + return true; + } + + return (bool) $value; + }, ARRAY_FILTER_USE_BOTH); + + return $objectVars; } } diff --git a/src/LooplineSystems/CloseIoApiWrapper/Model/Lead.php b/src/LooplineSystems/CloseIoApiWrapper/Model/Lead.php index e6e62d3..c599cfc 100644 --- a/src/LooplineSystems/CloseIoApiWrapper/Model/Lead.php +++ b/src/LooplineSystems/CloseIoApiWrapper/Model/Lead.php @@ -283,6 +283,22 @@ public function setCustom($custom) return $this; } + /** + * Sets the value of a custom field. By passing a `null` value the field + * will be unset from the lead. + * + * @param string $name The name or ID of the field + * @param mixed $value The value + * + * @return $this + */ + public function setCustomField(string $name, $value) + { + $this->custom[$name] = $value; + + return $this; + } + /** * @return string */ @@ -627,4 +643,15 @@ public function setUpdatedByName($updated_by_name) return $this; } + + public function __set(string $name, $value) + { + if (strpos($name, 'custom.') === 0) { + @trigger_error('Setting a custom field using the $object->$fieldName syntax is deprecated since version 0.8. Use the setCustomField() method instead.', E_USER_DEPRECATED); + + $this->custom[substr($name, 7)] = $value; + } else { + $this->$name = $value; + } + } }