Skip to content

Commit ff9118d

Browse files
refactor: simplify __get and __isset (#52)
1 parent 06359de commit ff9118d

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

src/Granada/Granada.php

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -411,26 +411,36 @@ public function set_orm($orm)
411411
*/
412412
public function __get($property)
413413
{
414+
$class = static::class;
414415
$result = $this->orm->get($property);
415416

417+
$_has_method = [];
418+
416419
if ($result !== null) {
417-
if (method_exists($this, $method = 'get_' . $property)) {
420+
$method = 'get_' . $property;
421+
if ($_has_method[$class][$method] ??= method_exists($this, $method)) {
418422
return $this->$method($result);
419423
}
420424

421425
return $result;
422-
} elseif (method_exists($this, $method = 'missing_' . $property)) {
426+
}
427+
428+
$method = 'missing_' . $property;
429+
if ($_has_method[$class][$method] ??= method_exists($this, $method)) {
423430
return $this->$method();
424-
} elseif (array_key_exists($property, $this->relationships)) {
431+
}
432+
433+
if (array_key_exists($property, $this->relationships)) {
425434
return $this->relationships[$property];
426-
} elseif (method_exists($this, $property)) {
427-
if ($property != self::_get_id_column_name(get_class($this))) {
435+
}
436+
437+
$method = $property;
438+
if ($_has_method[$class][$method] ??= method_exists($this, $method)) {
439+
if ($property != self::_get_id_column_name($class)) {
428440
$relation = $this->$property();
429441

430442
return $this->relationships[$property] = (in_array($this->relating, ['has_one', 'belongs_to'])) ? $relation->find_one() : $relation->find_many();
431443
}
432-
433-
return null;
434444
}
435445

436446
return null;
@@ -450,7 +460,21 @@ public function __set($property, $value)
450460
*/
451461
public function __isset($property)
452462
{
453-
return array_key_exists($property, $this->relationships) || $this->orm->__isset($property) || method_exists($this, 'get_' . $property) || method_exists($this, 'missing_' . $property) || method_exists($this, $property);
463+
if (array_key_exists($property, $this->relationships)) {
464+
return true;
465+
}
466+
if ($this->orm->__isset($property)) {
467+
return true;
468+
}
469+
470+
$prefix_methods = ['get_', 'missing_', ''];
471+
foreach ($prefix_methods as $prefix) {
472+
if (method_exists($this, $prefix . $property)) {
473+
return true;
474+
}
475+
}
476+
477+
return false;
454478
}
455479

456480
/**

0 commit comments

Comments
 (0)