Skip to content

Commit e960145

Browse files
authored
Merge pull request #39 from dvicklund/bugfix/set-custom-attribute
Micro optimize setCustomAttribute call.
2 parents 8b1bd48 + 00c4a86 commit e960145

1 file changed

Lines changed: 24 additions & 23 deletions

File tree

src/Traits/CustomAttributeTrait.php

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,16 @@ public function hasCustomAttribute($attr)
4444
*/
4545
public function getCustomAttribute($attr)
4646
{
47-
$res = false;
48-
4947
if ($attr instanceof Model) {
5048
return $attr;
51-
} else {
52-
$res = $this->customAttributes()->where('custom_attributes.name', $attr)->orWhere('custom_attributes.id', $attr)->get()->first();
5349
}
54-
55-
return $res ? $res : false;
50+
51+
$res = $this->customAttributes()
52+
->where('custom_attributes.name', $attr)
53+
->orWhere('custom_attributes.id', $attr)
54+
->first();
55+
56+
return $res ?? false;
5657
}
5758

5859
/**
@@ -68,14 +69,20 @@ public function getCustomAttribute($attr)
6869
*/
6970
public function resolveCustomAttributeObject($attr)
7071
{
71-
if ($attr instanceof Model) return $attr;
72-
73-
$attrObj = $this->hasCustomAttribute($attr) ?
74-
$this->getCustomAttribute($attr) :
75-
CustomAttribute::where('id', $attr)->orWhere('name', $attr)->first();
76-
77-
if (!$attrObj) throw new InvalidCustomAttributeException('Could not find custom attribute with key "'.$attr.'"');
78-
72+
if ($attr instanceof Model) {
73+
return $attr;
74+
}
75+
76+
$attrObj = $this->getCustomAttribute($attr);
77+
78+
if ($attrObj === false) {
79+
$attrObj = CustomAttribute::where('id', $attr)->orWhere('name', $attr)->first();
80+
}
81+
82+
if (is_null($attrObj)) {
83+
throw new InvalidCustomAttributeException("Could not find custom attribute with key \"$attr\"");
84+
}
85+
7986
return $attrObj;
8087
}
8188

@@ -311,22 +318,16 @@ private function createCustomAttribute($name, $displayName, $rawType, $type, $ha
311318
* Sets an customAttributeValue with the given customAttribute name
312319
* and value
313320
*
314-
* @param int|string|Model $id
321+
* @param int|string|Model $identifier
315322
* @param mixed $value
316323
* @param string $type default = null
317324
*
318325
* @return mixed
319326
*/
320-
public function setCustomAttribute($attr, $value, $type = null)
327+
public function setCustomAttribute($identifier, $value, $type = null)
321328
{
322329
try {
323-
if ($attr instanceof Model) {
324-
// do nothing
325-
} else if ($this->hasCustomAttribute($attr)) {
326-
$attr = $this->getCustomAttribute($attr);
327-
} else {
328-
$attr = $this->resolveCustomAttributeObject($attr);
329-
}
330+
$attr = $this->resolveCustomAttributeObject($identifier);
330331

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

0 commit comments

Comments
 (0)