From 7c307baeb1172ca1387966338d11ede4ee6dbb56 Mon Sep 17 00:00:00 2001 From: Thomas Lange Date: Sun, 1 Apr 2018 15:15:49 +0200 Subject: Add method "getByField" --- core/namespace/Item.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/core/namespace/Item.php b/core/namespace/Item.php index d21a4d6..60f7547 100644 --- a/core/namespace/Item.php +++ b/core/namespace/Item.php @@ -167,5 +167,22 @@ abstract class Item implements ItemInterface { return 0; } + + #=============================================================================== + # Return Attribute instance based on field comparison with value + #=============================================================================== + public static function getByField($field, $value, \Database $Database): Attribute { + $exception = (new ReflectionClass(get_called_class()))->getNamespaceName().'\\Exception'; + $attribute = (new ReflectionClass(get_called_class()))->getNamespaceName().'\\Attribute'; + $Statement = $Database->prepare('SELECT * FROM '.$attribute::TABLE." WHERE {$field} = ?"); + + if($Statement->execute([$value])) { + if(!$Attribute = $Statement->fetchObject($attribute)) { + throw new $exception(sprintf("Item with value %s on field %s does not exist.", $value, $field)); + } + + return $Attribute; + } + } } ?> \ No newline at end of file -- cgit v1.2.3