Skip to content

Commit

Permalink
Merge pull request #39 from dvicklund/bugfix/set-custom-attribute
Browse files Browse the repository at this point in the history
Micro optimize setCustomAttribute call.
  • Loading branch information
dvicklund authored Dec 6, 2023
2 parents 8b1bd48 + 00c4a86 commit e960145
Showing 1 changed file with 24 additions and 23 deletions.
47 changes: 24 additions & 23 deletions src/Traits/CustomAttributeTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,16 @@ public function hasCustomAttribute($attr)
*/
public function getCustomAttribute($attr)
{
$res = false;

if ($attr instanceof Model) {
return $attr;
} else {
$res = $this->customAttributes()->where('custom_attributes.name', $attr)->orWhere('custom_attributes.id', $attr)->get()->first();
}

return $res ? $res : false;

$res = $this->customAttributes()
->where('custom_attributes.name', $attr)
->orWhere('custom_attributes.id', $attr)
->first();

return $res ?? false;
}

/**
Expand All @@ -68,14 +69,20 @@ public function getCustomAttribute($attr)
*/
public function resolveCustomAttributeObject($attr)
{
if ($attr instanceof Model) return $attr;

$attrObj = $this->hasCustomAttribute($attr) ?
$this->getCustomAttribute($attr) :
CustomAttribute::where('id', $attr)->orWhere('name', $attr)->first();

if (!$attrObj) throw new InvalidCustomAttributeException('Could not find custom attribute with key "'.$attr.'"');

if ($attr instanceof Model) {
return $attr;
}

$attrObj = $this->getCustomAttribute($attr);

if ($attrObj === false) {
$attrObj = CustomAttribute::where('id', $attr)->orWhere('name', $attr)->first();
}

if (is_null($attrObj)) {
throw new InvalidCustomAttributeException("Could not find custom attribute with key \"$attr\"");
}

return $attrObj;
}

Expand Down Expand Up @@ -311,22 +318,16 @@ private function createCustomAttribute($name, $displayName, $rawType, $type, $ha
* Sets an customAttributeValue with the given customAttribute name
* and value
*
* @param int|string|Model $id
* @param int|string|Model $identifier
* @param mixed $value
* @param string $type default = null
*
* @return mixed
*/
public function setCustomAttribute($attr, $value, $type = null)
public function setCustomAttribute($identifier, $value, $type = null)
{
try {
if ($attr instanceof Model) {
// do nothing
} else if ($this->hasCustomAttribute($attr)) {
$attr = $this->getCustomAttribute($attr);
} else {
$attr = $this->resolveCustomAttributeObject($attr);
}
$attr = $this->resolveCustomAttributeObject($identifier);

if (is_null($value) && $attr->required) {
throw new RequiredCustomAttributeException('Cannot set required attribute to null');
Expand Down

0 comments on commit e960145

Please sign in to comment.