Convert services to singletons and use lazy loading to improve performance (#479)

* use singletons to reduce need to recreate the same objects

* unable to make the constructor private

* comment out debug printing to log file

* correct typo of treating self() as a var instead of a function

* utilise Localisation service as a singleton

* fix errent line that should have been commented

* remove phpinfo

* correct mistake in stock controller

* try storing app in apcu

* serialise inside the app closures

* get timings for db-changed-time

* get timings for db-changed-time

* store localisation service in apcu

* stor translations in apcu instead of localisation service (due to database connection)

* correct syntax error

* forgot to uncomment instance map

* correct indentation and variable out of scope

* more timings for app execution time

* try apc caching for views

* correct scope for Pot variable

* remove additional fopen

* correct timings for app build time

* correct timings for app object build time

* correct timings for app route build time

* get timings for routing timings

* get more in depth timings for routing loading

* fix more in depth timings for routing loading

* start investigating session auth middleware creation

* start investigating session auth middleware creation

* start investigating Login controller time

* start investigating Login controller time

* in depth look at Logincontroller timings

* comment out debug printing

* lazily obtain valus for page rendering

* correct syntax error

* correct scope of variable

* correct visibiity of methds inherited from BaseController

* missing use for Userfieldsservice

* lazy loading of open api spec

* lazy loading of users service

* lazy loading of batteries service

* lazy loading of services in controllers

* lazy loading of services in services

* correct mistake

* fix userservice

* fix userservice

* fix userfieldservice

* fix chores service

* fix calendar service

* remove Dockerfile used for development

* Remove docker compose file used for development

* Clean up app.php

* remove last diff

* Clean up base controller

* Clean up controllers

* lean up middleware

* Clean up and tuen all services into singletons

* remove debug from routes.php

* remove acpu from localisation

* Complete removal of acpu from localisation

* fixes for things broken

* More fixes following merge

* Fix for start up bug. Re factoring singleton code had brroken due to scope of clas var.

* fix bug where getUsersService is declared twice

* bug fixes following merge

* bug fixes following merge

* bug fixes following merge

* bug fixes following merge

* bug fixes following merge

* Fix all the not working things...

* Deleted off-topic files

* Deleted off-topic files

Co-authored-by: Bernd Bestel <bernd@berrnd.de>
This commit is contained in:
zebardy
2020-03-01 23:47:47 +07:00
committed by GitHub
parent 2b1dc7756d
commit 1a5f3ce926
49 changed files with 875 additions and 837 deletions

View File

@@ -18,16 +18,16 @@ class ApiKeyService extends BaseService
}
else
{
$apiKeyRow = $this->Database->api_keys()->where('api_key = :1 AND expires > :2 AND key_type = :3', $apiKey, date('Y-m-d H:i:s', time()), $keyType)->fetch();
$apiKeyRow = $this->getDatabase()->api_keys()->where('api_key = :1 AND expires > :2 AND key_type = :3', $apiKey, date('Y-m-d H:i:s', time()), $keyType)->fetch();
if ($apiKeyRow !== null)
{
// This should not change the database file modification time as this is used
// to determine if REALLY something has changed
$dbModTime = $this->DatabaseService->GetDbChangedTime();
$dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$apiKeyRow->update(array(
'last_used' => date('Y-m-d H:i:s', time())
));
$this->DatabaseService->SetDbChangedTime($dbModTime);
$this->getDatabaseService()->SetDbChangedTime($dbModTime);
return true;
}
@@ -44,8 +44,8 @@ class ApiKeyService extends BaseService
public function CreateApiKey($keyType = self::API_KEY_TYPE_DEFAULT)
{
$newApiKey = $this->GenerateApiKey();
$apiKeyRow = $this->Database->api_keys()->createRow(array(
$apiKeyRow = $this->getDatabase()->api_keys()->createRow(array(
'api_key' => $newApiKey,
'user_id' => GROCY_USER_ID,
'expires' => '2999-12-31 23:59:59', // Default is that API keys expire never
@@ -58,21 +58,21 @@ class ApiKeyService extends BaseService
public function RemoveApiKey($apiKey)
{
$this->Database->api_keys()->where('api_key', $apiKey)->delete();
$this->getDatabase()->api_keys()->where('api_key', $apiKey)->delete();
}
public function GetApiKeyId($apiKey)
{
$apiKey = $this->Database->api_keys()->where('api_key', $apiKey)->fetch();
$apiKey = $this->getDatabase()->api_keys()->where('api_key', $apiKey)->fetch();
return $apiKey->id;
}
public function GetUserByApiKey($apiKey)
{
$apiKeyRow = $this->Database->api_keys()->where('api_key', $apiKey)->fetch();
$apiKeyRow = $this->getDatabase()->api_keys()->where('api_key', $apiKey)->fetch();
if ($apiKeyRow !== null)
{
return $this->Database->users($apiKeyRow->user_id);
return $this->getDatabase()->users($apiKeyRow->user_id);
}
return null;
}
@@ -87,7 +87,7 @@ class ApiKeyService extends BaseService
}
else
{
$apiKeyRow = $this->Database->api_keys()->where('key_type = :1 AND expires > :2', $keyType, date('Y-m-d H:i:s', time()))->fetch();
$apiKeyRow = $this->getDatabase()->api_keys()->where('key_type = :1 AND expires > :2', $keyType, date('Y-m-d H:i:s', time()))->fetch();
if ($apiKeyRow !== null)
{
return $apiKeyRow->api_key;

View File

@@ -5,17 +5,18 @@ namespace Grocy\Services;
class ApplicationService extends BaseService
{
private $InstalledVersion;
public function GetInstalledVersion()
{
if ($this->InstalledVersion == null)
{
$this->InstalledVersion = json_decode(file_get_contents(__DIR__ . '/../version.json'));
if (GROCY_MODE === 'prerelease')
{
$commitHash = trim(exec('git log --pretty="%h" -n1 HEAD'));
$commitDate = trim(exec('git log --date=iso --pretty="%cd" -n1 HEAD'));
$this->InstalledVersion->Version = "pre-release-$commitHash";
$this->InstalledVersion->ReleaseDate = substr($commitDate, 0, 19);
}

View File

@@ -2,20 +2,64 @@
namespace Grocy\Services;
use \Grocy\Services\DatabaseService;
use \Grocy\Services\LocalizationService;
#use \Grocy\Services\DatabaseService;
#use \Grocy\Services\LocalizationService;
class BaseService
{
public function __construct() {
$this->DatabaseService = new DatabaseService();
$this->Database = $this->DatabaseService->GetDbConnection();
$localizationService = new LocalizationService(GROCY_CULTURE);
$this->LocalizationService = $localizationService;
}
protected $DatabaseService;
protected $Database;
protected $LocalizationService;
private static $instances = array();
public static function getInstance()
{
$className = get_called_class();
if(!isset(self::$instances[$className]))
{
self::$instances[$className] = new $className();
}
return self::$instances[$className];
}
protected function getDatabaseService()
{
return DatabaseService::getInstance();
}
protected function getDatabase()
{
return $this->getDatabaseService()->GetDbConnection();
}
protected function getLocalizationService()
{
return LocalizationService::getInstance(GROCY_CULTURE);
}
protected function getStockservice()
{
return StockService::getInstance();
}
protected function getTasksService()
{
return TasksService::getInstance();
}
protected function getChoresService()
{
return ChoresService::getInstance();
}
protected function getBatteriesService()
{
return BatteriesService::getInstance();
}
protected function getUsersService()
{
return UsersService::getInstance();
}
}

View File

@@ -7,7 +7,7 @@ class BatteriesService extends BaseService
public function GetCurrent()
{
$sql = 'SELECT * from batteries_current';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function GetBatteryDetails(int $batteryId)
@@ -17,10 +17,10 @@ class BatteriesService extends BaseService
throw new \Exception('Battery does not exist');
}
$battery = $this->Database->batteries($batteryId);
$batteryChargeCyclesCount = $this->Database->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->count();
$batteryLastChargedTime = $this->Database->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->max('tracked_time');
$nextChargeTime = $this->Database->batteries_current()->where('battery_id', $batteryId)->min('next_estimated_charge_time');
$battery = $this->getDatabase()->batteries($batteryId);
$batteryChargeCyclesCount = $this->getDatabase()->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->count();
$batteryLastChargedTime = $this->getDatabase()->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->max('tracked_time');
$nextChargeTime = $this->getDatabase()->batteries_current()->where('battery_id', $batteryId)->min('next_estimated_charge_time');
return array(
'battery' => $battery,
@@ -37,24 +37,24 @@ class BatteriesService extends BaseService
throw new \Exception('Battery does not exist');
}
$logRow = $this->Database->battery_charge_cycles()->createRow(array(
$logRow = $this->getDatabase()->battery_charge_cycles()->createRow(array(
'battery_id' => $batteryId,
'tracked_time' => $trackedTime
));
$logRow->save();
return $this->Database->lastInsertId();
return $this->getDatabase()->lastInsertId();
}
private function BatteryExists($batteryId)
{
$batteryRow = $this->Database->batteries()->where('id = :1', $batteryId)->fetch();
$batteryRow = $this->getDatabase()->batteries()->where('id = :1', $batteryId)->fetch();
return $batteryRow !== null;
}
public function UndoChargeCycle($chargeCycleId)
{
$logRow = $this->Database->battery_charge_cycles()->where('id = :1 AND undone = 0', $chargeCycleId)->fetch();
$logRow = $this->getDatabase()->battery_charge_cycles()->where('id = :1 AND undone = 0', $chargeCycleId)->fetch();
if ($logRow == null)
{
throw new \Exception('Charge cycle does not exist or was already undone');

View File

@@ -2,11 +2,11 @@
namespace Grocy\Services;
use \Grocy\Services\StockService;
use \Grocy\Services\TasksService;
use \Grocy\Services\ChoresService;
use \Grocy\Services\BatteriesService;
use \Grocy\Services\UsersService;
#use \Grocy\Services\StockService;
#use \Grocy\Services\TasksService;
#use \Grocy\Services\ChoresService;
#use \Grocy\Services\BatteriesService;
#use \Grocy\Services\UsersService;
use \Grocy\Helpers\UrlManager;
class CalendarService extends BaseService
@@ -14,27 +14,17 @@ class CalendarService extends BaseService
public function __construct()
{
parent::__construct();
$this->StockService = new StockService();
$this->TasksService = new TasksService();
$this->ChoresService = new ChoresService();
$this->BatteriesService = new BatteriesService();
$this->UrlManager = new UrlManager(GROCY_BASE_URL);
}
protected $StockService;
protected $TasksService;
protected $ChoresService;
protected $BatteriesService;
protected $UrlManager;
public function GetEvents()
{
$stockEvents = array();
if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{
$products = $this->Database->products();
$titlePrefix = $this->LocalizationService->__t('Product expires') . ': ';
foreach($this->StockService->GetCurrentStock() as $currentStockEntry)
$products = $this->getDatabase()->products();
$titlePrefix = $this->getLocalizationService()->__t('Product expires') . ': ';
foreach($this->getStockService()->GetCurrentStock() as $currentStockEntry)
{
if ($currentStockEntry->amount > 0)
{
@@ -50,8 +40,8 @@ class CalendarService extends BaseService
$taskEvents = array();
if (GROCY_FEATURE_FLAG_TASKS)
{
$titlePrefix = $this->LocalizationService->__t('Task due') . ': ';
foreach($this->TasksService->GetCurrent() as $currentTaskEntry)
$titlePrefix = $this->getLocalizationService()->__t('Task due') . ': ';
foreach($this->getTasksService()->GetCurrent() as $currentTaskEntry)
{
$taskEvents[] = array(
'title' => $titlePrefix . $currentTaskEntry->name,
@@ -64,19 +54,18 @@ class CalendarService extends BaseService
$choreEvents = array();
if (GROCY_FEATURE_FLAG_CHORES)
{
$usersService = new UsersService();
$users = $usersService->GetUsersAsDto();
$users = $this->getUsersService()->GetUsersAsDto();
$chores = $this->Database->chores();
$titlePrefix = $this->LocalizationService->__t('Chore due') . ': ';
foreach($this->ChoresService->GetCurrent() as $currentChoreEntry)
$chores = $this->getDatabase()->chores();
$titlePrefix = $this->getLocalizationService()->__t('Chore due') . ': ';
foreach($this->getChoresService()->GetCurrent() as $currentChoreEntry)
{
$chore = FindObjectInArrayByPropertyValue($chores, 'id', $currentChoreEntry->chore_id);
$assignedToText = '';
if (!empty($currentChoreEntry->next_execution_assigned_to_user_id))
{
$assignedToText = ' (' . $this->LocalizationService->__t('assigned to %s', FindObjectInArrayByPropertyValue($users, 'id', $currentChoreEntry->next_execution_assigned_to_user_id)->display_name) . ')';
$assignedToText = ' (' . $this->getLocalizationService()->__t('assigned to %s', FindObjectInArrayByPropertyValue($users, 'id', $currentChoreEntry->next_execution_assigned_to_user_id)->display_name) . ')';
}
$choreEvents[] = array(
@@ -90,9 +79,9 @@ class CalendarService extends BaseService
$batteryEvents = array();
if (GROCY_FEATURE_FLAG_BATTERIES)
{
$batteries = $this->Database->batteries();
$titlePrefix = $this->LocalizationService->__t('Battery charge cycle due') . ': ';
foreach($this->BatteriesService->GetCurrent() as $currentBatteryEntry)
$batteries = $this->getDatabase()->batteries();
$titlePrefix = $this->getLocalizationService()->__t('Battery charge cycle due') . ': ';
foreach($this->getBatteriesService()->GetCurrent() as $currentBatteryEntry)
{
$batteryEvents[] = array(
'title' => $titlePrefix . FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->name,
@@ -105,13 +94,13 @@ class CalendarService extends BaseService
$mealPlanRecipeEvents = array();
if (GROCY_FEATURE_FLAG_RECIPES)
{
$recipes = $this->Database->recipes();
$mealPlanDayRecipes = $this->Database->recipes()->where('type', 'mealplan-day');
$titlePrefix = $this->LocalizationService->__t('Meal plan recipe') . ': ';
$recipes = $this->getDatabase()->recipes();
$mealPlanDayRecipes = $this->getDatabase()->recipes()->where('type', 'mealplan-day');
$titlePrefix = $this->getLocalizationService()->__t('Meal plan recipe') . ': ';
foreach($mealPlanDayRecipes as $mealPlanDayRecipe)
{
$recipesOfCurrentDay = $this->Database->recipes_nestings_resolved()->where('recipe_id = :1 AND includes_recipe_id != :1', $mealPlanDayRecipe->id);
$recipesOfCurrentDay = $this->getDatabase()->recipes_nestings_resolved()->where('recipe_id = :1 AND includes_recipe_id != :1', $mealPlanDayRecipe->id);
foreach ($recipesOfCurrentDay as $recipeOfCurrentDay)
{
$mealPlanRecipeEvents[] = array(
@@ -123,8 +112,8 @@ class CalendarService extends BaseService
}
}
$mealPlanDayNotes = $this->Database->meal_plan()->where('type', 'note');
$titlePrefix = $this->LocalizationService->__t('Meal plan note') . ': ';
$mealPlanDayNotes = $this->getDatabase()->meal_plan()->where('type', 'note');
$titlePrefix = $this->getLocalizationService()->__t('Meal plan note') . ': ';
$mealPlanNotesEvents = array();
foreach($mealPlanDayNotes as $mealPlanDayNote)
{
@@ -135,9 +124,9 @@ class CalendarService extends BaseService
);
}
$products = $this->Database->products();
$mealPlanDayProducts = $this->Database->meal_plan()->where('type', 'product');
$titlePrefix = $this->LocalizationService->__t('Meal plan product') . ': ';
$products = $this->getDatabase()->products();
$mealPlanDayProducts = $this->getDatabase()->meal_plan()->where('type', 'product');
$titlePrefix = $this->getLocalizationService()->__t('Meal plan product') . ': ';
$mealPlanProductEvents = array();
foreach($mealPlanDayProducts as $mealPlanDayProduct)
{

View File

@@ -2,7 +2,7 @@
namespace Grocy\Services;
use \Grocy\Services\StockService;
#use \Grocy\Services\StockService;
class ChoresService extends BaseService
{
@@ -21,15 +21,12 @@ class ChoresService extends BaseService
public function __construct()
{
parent::__construct();
$this->StockService = new StockService();
}
protected $StockService;
public function GetCurrent()
{
$sql = 'SELECT * from chores_current';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function GetChoreDetails(int $choreId)
@@ -38,16 +35,15 @@ class ChoresService extends BaseService
{
throw new \Exception('Chore does not exist');
}
$usersService = new UsersService();
$users = $usersService->GetUsersAsDto();
$chore = $this->Database->chores($choreId);
$choreTrackedCount = $this->Database->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->count();
$choreLastTrackedTime = $this->Database->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time');
$nextExecutionTime = $this->Database->chores_current()->where('chore_id', $choreId)->min('next_estimated_execution_time');
$lastChoreLogRow = $this->Database->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch();
$users = $this->getUsersService()->GetUsersAsDto();
$chore = $this->getDatabase()->chores($choreId);
$choreTrackedCount = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->count();
$choreLastTrackedTime = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time');
$nextExecutionTime = $this->getDatabase()->chores_current()->where('chore_id', $choreId)->min('next_estimated_execution_time');
$lastChoreLogRow = $this->getDatabase()->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch();
$lastDoneByUser = null;
if ($lastChoreLogRow !== null && !empty($lastChoreLogRow))
{
@@ -77,31 +73,31 @@ class ChoresService extends BaseService
throw new \Exception('Chore does not exist');
}
$userRow = $this->Database->users()->where('id = :1', $doneBy)->fetch();
$userRow = $this->getDatabase()->users()->where('id = :1', $doneBy)->fetch();
if ($userRow === null)
{
throw new \Exception('User does not exist');
}
$chore = $this->Database->chores($choreId);
$chore = $this->getDatabase()->chores($choreId);
if ($chore->track_date_only == 1)
{
$trackedTime = substr($trackedTime, 0, 10) . ' 00:00:00';
}
$logRow = $this->Database->chores_log()->createRow(array(
$logRow = $this->getDatabase()->chores_log()->createRow(array(
'chore_id' => $choreId,
'tracked_time' => $trackedTime,
'done_by_user_id' => $doneBy
));
$logRow->save();
$lastInsertId = $this->Database->lastInsertId();
$lastInsertId = $this->getDatabase()->lastInsertId();
$this->CalculateNextExecutionAssignment($choreId);
if ($chore->consume_product_on_execution == 1 && !empty($chore->product_id))
{
$this->StockService->ConsumeProduct($chore->product_id, $chore->product_amount, false, StockService::TRANSACTION_TYPE_CONSUME);
$this->getStockService()->ConsumeProduct($chore->product_id, $chore->product_amount, false, StockService::TRANSACTION_TYPE_CONSUME);
}
return $lastInsertId;
@@ -109,13 +105,13 @@ class ChoresService extends BaseService
private function ChoreExists($choreId)
{
$choreRow = $this->Database->chores()->where('id = :1', $choreId)->fetch();
$choreRow = $this->getDatabase()->chores()->where('id = :1', $choreId)->fetch();
return $choreRow !== null;
}
public function UndoChoreExecution($executionId)
{
$logRow = $this->Database->chores_log()->where('id = :1 AND undone = 0', $executionId)->fetch();
$logRow = $this->getDatabase()->chores_log()->where('id = :1 AND undone = 0', $executionId)->fetch();
if ($logRow == null)
{
throw new \Exception('Execution does not exist or was already undone');
@@ -135,13 +131,12 @@ class ChoresService extends BaseService
throw new \Exception('Chore does not exist');
}
$chore = $this->Database->chores($choreId);
$choreLastTrackedTime = $this->Database->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time');
$lastChoreLogRow = $this->Database->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch();
$chore = $this->getDatabase()->chores($choreId);
$choreLastTrackedTime = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time');
$lastChoreLogRow = $this->getDatabase()->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch();
$lastDoneByUserId = $lastChoreLogRow->done_by_user_id;
$usersService = new UsersService();
$users = $usersService->GetUsersAsDto();
$users = $this->getUsersService()->GetUsersAsDto();
$assignedUsers = array();
foreach ($users as $user)
{
@@ -198,7 +193,7 @@ class ChoresService extends BaseService
}
else if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST)
{
$row = $this->Database->chores_execution_users_statistics()->where('chore_id = :1', $choreId)->orderBy('execution_count')->limit(1)->fetch();
$row = $this->getDatabase()->chores_execution_users_statistics()->where('chore_id = :1', $choreId)->orderBy('execution_count')->limit(1)->fetch();
if ($row != null)
{
$nextExecutionUserId = $row->user_id;

View File

@@ -6,7 +6,7 @@ class DatabaseMigrationService extends BaseService
{
public function MigrateDatabase()
{
$this->DatabaseService->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))");
$this->getDatabaseService()->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))");
$sqlMigrationFiles = array();
foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file)
@@ -41,21 +41,21 @@ class DatabaseMigrationService extends BaseService
private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql)
{
$rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
$rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
if (intval($rowCount) === 0)
{
$this->DatabaseService->ExecuteDbStatement($sql);
$this->DatabaseService->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
$this->getDatabaseService()->ExecuteDbStatement($sql);
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
}
}
private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile)
{
$rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
$rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
if (intval($rowCount) === 0)
{
include $phpFile;
$this->DatabaseService->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
}
}
}

View File

@@ -2,10 +2,22 @@
namespace Grocy\Services;
use \Grocy\Services\ApplicationService;
#use \Grocy\Services\ApplicationService;
class DatabaseService
{
private static $instance = null;
public static function getInstance()
{
if (self::$instance == null)
{
self::$instance = new self();
}
return self::$instance;
}
private function GetDbFilePath()
{
if (GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease')
@@ -16,34 +28,34 @@ class DatabaseService
return GROCY_DATAPATH . '/grocy.db';
}
private $DbConnectionRaw;
private static $DbConnectionRaw = null;
/**
* @return \PDO
*/
public function GetDbConnectionRaw()
{
if ($this->DbConnectionRaw == null)
if (self::$DbConnectionRaw == null)
{
$pdo = new \PDO('sqlite:' . $this->GetDbFilePath());
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->DbConnectionRaw = $pdo;
self::$DbConnectionRaw = $pdo;
}
return $this->DbConnectionRaw;
return self::$DbConnectionRaw;
}
private $DbConnection;
private static $DbConnection = null;
/**
* @return \LessQL\Database
*/
public function GetDbConnection()
{
if ($this->DbConnection == null)
if (self::$DbConnection == null)
{
$this->DbConnection = new \LessQL\Database($this->GetDbConnectionRaw());
self::$DbConnection = new \LessQL\Database($this->GetDbConnectionRaw());
}
return $this->DbConnection;
return self::$DbConnection;
}
/**

View File

@@ -2,7 +2,7 @@
namespace Grocy\Services;
use \Grocy\Services\LocalizationService;
#use \Grocy\Services\LocalizationService;
class DemoDataGeneratorService extends BaseService
{
@@ -12,11 +12,11 @@ class DemoDataGeneratorService extends BaseService
$this->LocalizationService = new LocalizationService(GROCY_CULTURE);
}
protected $LocalizationService;
protected $LocalizationService;
public function PopulateDemoData()
{
$rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn();
$rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn();
if (intval($rowCount) === 0)
{
$loremIpsum = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.';
@@ -183,7 +183,7 @@ class DemoDataGeneratorService extends BaseService
INSERT INTO migrations (migration) VALUES (-1);
";
$this->DatabaseService->ExecuteDbStatement($sql);
$this->getDatabaseService()->ExecuteDbStatement($sql);
$stockService = new StockService();
$stockService->AddProduct(3, 1, date('Y-m-d', strtotime('+180 days')), StockService::TRANSACTION_TYPE_PURCHASE, date('Y-m-d', strtotime('-10 days')), $this->RandomPrice());
@@ -319,13 +319,13 @@ class DemoDataGeneratorService extends BaseService
private function __t_sql(string $text)
{
$localizedText = $this->LocalizationService->__t($text, null);
$localizedText = $this->getLocalizationService()->__t($text, null);
return str_replace("'", "''", $localizedText);
}
private function __n_sql($number, string $singularForm, string $pluralForm)
{
$localizedText = $this->LocalizationService->__n($number, $singularForm, $pluralForm);
$localizedText = $this->getLocalizationService()->__n($number, $singularForm, $pluralForm);
return str_replace("'", "''", $localizedText);
}

View File

@@ -11,9 +11,9 @@ class FilesService extends BaseService
public function __construct()
{
parent::__construct();
$this->StoragePath = GROCY_DATAPATH . '/storage';
if (!file_exists($this->StoragePath))
{
mkdir($this->StoragePath);

View File

@@ -2,24 +2,44 @@
namespace Grocy\Services;
use \Grocy\Services\DatabaseService;
#use \Grocy\Services\DatabaseService;
use \Gettext\Translation;
use \Gettext\Translations;
use \Gettext\Translator;
class LocalizationService
{
private static $instanceMap = array();
public function __construct(string $culture)
{
$this->Culture = $culture;
$this->DatabaseService = new DatabaseService();
$this->Database = $this->DatabaseService->GetDbConnection();
$this->LoadLocalizations($culture);
}
protected $DatabaseService;
protected $Database;
protected function getDatabaseService()
{
return DatabaseService::getInstance();
}
protected function getdatabase()
{
return $this->getDatabaseService()->GetDbConnection();
}
public static function getInstance(string $culture)
{
if (!in_array($culture, self::$instanceMap))
{
self::$instanceMap[$culture] = new self($culture);
}
return self::$instanceMap[$culture];
}
protected $Pot;
protected $PotMain;
protected $Po;
@@ -57,7 +77,7 @@ class LocalizationService
$quantityUnits = null;
try
{
$quantityUnits = $this->Database->quantity_units()->fetchAll();
$quantityUnits = $this->getDatabase()->quantity_units()->fetchAll();
}
catch (\Exception $ex)
{

View File

@@ -2,7 +2,7 @@
namespace Grocy\Services;
use \Grocy\Services\StockService;
#use \Grocy\Services\StockService;
class RecipesService extends BaseService
{
@@ -13,46 +13,43 @@ class RecipesService extends BaseService
public function __construct()
{
parent::__construct();
$this->StockService = new StockService();
}
protected $StockService;
public function GetRecipesPosResolved()
{
$sql = 'SELECT * FROM recipes_pos_resolved';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return $this->getDataBaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function GetRecipesResolved()
{
$sql = 'SELECT * FROM recipes_resolved';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return $this->getDataBaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function AddNotFulfilledProductsToShoppingList($recipeId, $excludedProductIds = null)
{
$recipe = $this->Database->recipes($recipeId);
$recipe = $this->getDataBase()->recipes($recipeId);
$recipePositions = $this->GetRecipesPosResolved();
foreach ($recipePositions as $recipePosition)
{
if($recipePosition->recipe_id == $recipeId && !in_array($recipePosition->product_id, $excludedProductIds))
{
$product = $this->Database->products($recipePosition->product_id);
$product = $this->getDataBase()->products($recipePosition->product_id);
$toOrderAmount = ceil(($recipePosition->missing_amount - $recipePosition->amount_on_shopping_list) / $product->qu_factor_purchase_to_stock);
if ($recipe->not_check_shoppinglist == 1)
{
$toOrderAmount = ceil($recipePosition->missing_amount / $product->qu_factor_purchase_to_stock);
}
if($toOrderAmount > 0)
{
$shoppinglistRow = $this->Database->shopping_list()->createRow(array(
$shoppinglistRow = $this->getDataBase()->shopping_list()->createRow(array(
'product_id' => $recipePosition->product_id,
'amount' => $toOrderAmount,
'note' => $this->LocalizationService->__t('Added for recipe %s', $recipe->name)
'note' => $this->getLocalizationService()->__t('Added for recipe %s', $recipe->name)
));
$shoppinglistRow->save();
}
@@ -68,26 +65,26 @@ class RecipesService extends BaseService
}
$transactionId = uniqid();
$recipePositions = $this->Database->recipes_pos_resolved()->where('recipe_id', $recipeId)->fetchAll();
$recipePositions = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id', $recipeId)->fetchAll();
foreach ($recipePositions as $recipePosition)
{
if ($recipePosition->only_check_single_unit_in_stock == 0)
{
$this->StockService->ConsumeProduct($recipePosition->product_id, $recipePosition->recipe_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true);
$this->getStockService()->ConsumeProduct($recipePosition->product_id, $recipePosition->recipe_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true);
}
}
$recipeRow = $this->Database->recipes()->where('id = :1', $recipeId)->fetch();
$recipeRow = $this->getDatabase()->recipes()->where('id = :1', $recipeId)->fetch();
if (!empty($recipeRow->product_id))
{
$recipeResolvedRow = $this->Database->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch();
$this->StockService->AddProduct($recipeRow->product_id, floatval($recipeRow->desired_servings), null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), floatval($recipeResolvedRow->costs));
$recipeResolvedRow = $this->getDatabase()->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch();
$this->getStockService()->AddProduct($recipeRow->product_id, floatval($recipeRow->desired_servings), null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), floatval($recipeResolvedRow->costs));
}
}
private function RecipeExists($recipeId)
{
$recipeRow = $this->Database->recipes()->where('id = :1', $recipeId)->fetch();
$recipeRow = $this->getDataBase()->recipes()->where('id = :1', $recipeId)->fetch();
return $recipeRow !== null;
}
}

View File

@@ -4,6 +4,7 @@ namespace Grocy\Services;
class SessionService extends BaseService
{
/**
* @return boolean
*/
@@ -15,16 +16,16 @@ class SessionService extends BaseService
}
else
{
$sessionRow = $this->Database->sessions()->where('session_key = :1 AND expires > :2', $sessionKey, date('Y-m-d H:i:s', time()))->fetch();
$sessionRow = $this->getDatabase()->sessions()->where('session_key = :1 AND expires > :2', $sessionKey, date('Y-m-d H:i:s', time()))->fetch();
if ($sessionRow !== null)
{
// This should not change the database file modification time as this is used
// to determine if REALLY something has changed
$dbModTime = $this->DatabaseService->GetDbChangedTime();
$dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$sessionRow->update(array(
'last_used' => date('Y-m-d H:i:s', time())
));
$this->DatabaseService->SetDbChangedTime($dbModTime);
$this->getDatabaseService()->SetDbChangedTime($dbModTime);
return true;
}
@@ -41,14 +42,14 @@ class SessionService extends BaseService
public function CreateSession($userId, $stayLoggedInPermanently = false)
{
$newSessionKey = $this->GenerateSessionKey();
$expires = date('Y-m-d H:i:s', intval(time() + 2592000)); // Default is that sessions expire in 30 days
if ($stayLoggedInPermanently === true)
{
$expires = date('Y-m-d H:i:s', PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX>>32); // Never
}
$sessionRow = $this->Database->sessions()->createRow(array(
$sessionRow = $this->getDatabase()->sessions()->createRow(array(
'user_id' => $userId,
'session_key' => $newSessionKey,
'expires' => $expires
@@ -60,22 +61,22 @@ class SessionService extends BaseService
public function RemoveSession($sessionKey)
{
$this->Database->sessions()->where('session_key', $sessionKey)->delete();
$this->getDatabase()->sessions()->where('session_key', $sessionKey)->delete();
}
public function GetUserBySessionKey($sessionKey)
{
$sessionRow = $this->Database->sessions()->where('session_key', $sessionKey)->fetch();
$sessionRow = $this->getDatabase()->sessions()->where('session_key', $sessionKey)->fetch();
if ($sessionRow !== null)
{
return $this->Database->users($sessionRow->user_id);
return $this->getDatabase()->users($sessionRow->user_id);
}
return null;
}
public function GetDefaultUser()
{
return $this->Database->users(1);
return $this->getDatabase()->users(1);
}
private function GenerateSessionKey()

View File

@@ -27,9 +27,9 @@ class StockService extends BaseService
$sql = 'SELECT * FROM stock_current WHERE best_before_date IS NOT NULL UNION SELECT id, 0, 0, null, 0, 0, 0 FROM ' . $missingProductsView . ' WHERE id NOT IN (SELECT product_id FROM stock_current)';
}
$currentStockMapped = $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_OBJ);
$currentStockMapped = $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_OBJ);
$relevantProducts = $this->Database->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)');
$relevantProducts = $this->getDatabase()->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)');
foreach ($relevantProducts as $product)
{
$currentStockMapped[$product->id][0]->product_id = $product->id;
@@ -42,19 +42,19 @@ class StockService extends BaseService
public function GetCurrentStockLocationContent()
{
$sql = 'SELECT * FROM stock_current_location_content';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function GetCurrentStockLocations()
{
$sql = 'SELECT * FROM stock_current_locations';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function GetCurrentProductPrices()
{
$sql = 'SELECT * FROM products_current_price';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function GetMissingProducts()
@@ -65,17 +65,17 @@ class StockService extends BaseService
$sql = 'SELECT * FROM stock_missing_products';
}
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function GetProductStockLocations($productId)
{
return $this->Database->stock_current_locations()->where('product_id', $productId)->fetchAll();
return $this->getDatabase()->stock_current_locations()->where('product_id', $productId)->fetchAll();
}
public function GetProductIdFromBarcode(string $barcode)
{
$potentialProduct = $this->Database->products()->where("',' || barcode || ',' LIKE '%,' || :1 || ',%' AND IFNULL(barcode, '') != ''", $barcode)->limit(1)->fetch();
$potentialProduct = $this->getDatabase()->products()->where("',' || barcode || ',' LIKE '%,' || :1 || ',%' AND IFNULL(barcode, '') != ''", $barcode)->limit(1)->fetch();
if ($potentialProduct === null)
{
@@ -117,24 +117,24 @@ class StockService extends BaseService
$stockCurrentRow->is_aggregated_amount = 0;
}
$product = $this->Database->products($productId);
$productLastPurchased = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_PURCHASE)->where('undone', 0)->max('purchased_date');
$productLastUsed = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone', 0)->max('used_date');
$nextBestBeforeDate = $this->Database->stock()->where('product_id', $productId)->min('best_before_date');
$quPurchase = $this->Database->quantity_units($product->qu_id_purchase);
$quStock = $this->Database->quantity_units($product->qu_id_stock);
$location = $this->Database->locations($product->location_id);
$averageShelfLifeDays = intval($this->Database->stock_average_product_shelf_life()->where('id', $productId)->fetch()->average_shelf_life_days);
$product = $this->getDatabase()->products($productId);
$productLastPurchased = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_PURCHASE)->where('undone', 0)->max('purchased_date');
$productLastUsed = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone', 0)->max('used_date');
$nextBestBeforeDate = $this->getDatabase()->stock()->where('product_id', $productId)->min('best_before_date');
$quPurchase = $this->getDatabase()->quantity_units($product->qu_id_purchase);
$quStock = $this->getDatabase()->quantity_units($product->qu_id_stock);
$location = $this->getDatabase()->locations($product->location_id);
$averageShelfLifeDays = intval($this->getDatabase()->stock_average_product_shelf_life()->where('id', $productId)->fetch()->average_shelf_life_days);
$lastPrice = null;
$lastLogRow = $this->Database->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->orderBy('row_created_timestamp', 'DESC')->limit(1)->fetch();
$lastLogRow = $this->getDatabase()->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->orderBy('row_created_timestamp', 'DESC')->limit(1)->fetch();
if ($lastLogRow !== null && !empty($lastLogRow))
{
$lastPrice = $lastLogRow->price;
}
$consumeCount = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 0')->sum('amount') * -1;
$consumeCountSpoiled = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 1')->sum('amount') * -1;
$consumeCount = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 0')->sum('amount') * -1;
$consumeCountSpoiled = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 1')->sum('amount') * -1;
if ($consumeCount == 0)
{
$consumeCount = 1;
@@ -168,7 +168,7 @@ class StockService extends BaseService
}
$returnData = array();
$rows = $this->Database->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->whereNOT('price', null)->orderBy('purchased_date', 'DESC');
$rows = $this->getDatabase()->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->whereNOT('price', null)->orderBy('purchased_date', 'DESC');
foreach ($rows as $row)
{
$returnData[] = array(
@@ -181,7 +181,7 @@ class StockService extends BaseService
public function GetStockEntry($entryId)
{
return $this->Database->stock()->where('id', $entryId)->fetch();
return $this->getDatabase()->stock()->where('id', $entryId)->fetch();
}
public function GetProductStockEntries($productId, $excludeOpened = false, $allowSubproductSubstitution = false)
@@ -201,7 +201,7 @@ class StockService extends BaseService
$sqlWhereAndOpen = 'AND open = 0';
}
return $this->Database->stock()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen, $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll();
return $this->getDatabase()->stock()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen, $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll();
}
public function GetProductStockEntriesForLocation($productId, $locationId, $excludeOpened = false, $allowSubproductSubstitution = false)
@@ -257,7 +257,7 @@ class StockService extends BaseService
$stockId = uniqid();
$logRow = $this->Database->stock_log()->createRow(array(
$logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $productId,
'amount' => $amount,
'best_before_date' => $bestBeforeDate,
@@ -270,9 +270,9 @@ class StockService extends BaseService
));
$logRow->save();
$returnValue = $this->Database->lastInsertId();
$returnValue = $this->getDatabase()->lastInsertId();
$stockRow = $this->Database->stock()->createRow(array(
$stockRow = $this->getDatabase()->stock()->createRow(array(
'product_id' => $productId,
'amount' => $amount,
'best_before_date' => $bestBeforeDate,
@@ -319,6 +319,7 @@ class StockService extends BaseService
if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION)
{
if ($locationId === null) // Consume from any location
{
$potentialStockEntries = $this->GetProductStockEntries($productId, false, $allowSubproductSubstitution);
@@ -353,7 +354,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount) // Take the whole stock entry
{
$logRow = $this->Database->stock_log()->createRow(array(
$logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1,
'best_before_date' => $stockEntry->best_before_date,
@@ -377,7 +378,7 @@ class StockService extends BaseService
{
$restStockAmount = $stockEntry->amount - $amount;
$logRow = $this->Database->stock_log()->createRow(array(
$logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $amount * -1,
'best_before_date' => $stockEntry->best_before_date,
@@ -401,7 +402,7 @@ class StockService extends BaseService
}
}
return $this->Database->lastInsertId();
return $this->getDatabase()->lastInsertId();
}
else
{
@@ -443,7 +444,7 @@ class StockService extends BaseService
$amount = abs($amount - floatval($productDetails->stock_amount) - floatval($productDetails->product->tare_weight));
}
$productStockAmountAtFromLocation = $this->Database->stock()->where('product_id = :1 AND location_id = :2', $productId, $locationIdFrom)->sum('amount');
$productStockAmountAtFromLocation = $this->getDatabase()->stock()->where('product_id = :1 AND location_id = :2', $productId, $locationIdFrom)->sum('amount');
$potentialStockEntriesAtFromLocation = $this->GetProductStockEntriesForLocation($productId, $locationIdFrom);
if ($amount > $productStockAmountAtFromLocation)
@@ -472,8 +473,8 @@ class StockService extends BaseService
if (GROCY_FEATURE_FLAG_STOCK_PRODUCT_FREEZING)
{
$locationFrom = $this->Database->locations()->where('id', $locationIdFrom)->fetch();
$locationTo = $this->Database->locations()->where('id', $locationIdTo)->fetch();
$locationFrom = $this->getDatabase()->locations()->where('id', $locationIdFrom)->fetch();
$locationTo = $this->getDatabase()->locations()->where('id', $locationIdTo)->fetch();
// Product was moved from a non-freezer to freezer location -> freeze
if (intval($locationFrom->is_freezer) === 0 && intval($locationTo->is_freezer) === 1 && $productDetails->product->default_best_before_days_after_freezing > 0)
@@ -491,7 +492,7 @@ class StockService extends BaseService
$correlationId = uniqid();
if ($amount >= $stockEntry->amount) // Take the whole stock entry
{
$logRowForLocationFrom = $this->Database->stock_log()->createRow(array(
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1,
'best_before_date' => $stockEntry->best_before_date,
@@ -506,7 +507,7 @@ class StockService extends BaseService
));
$logRowForLocationFrom->save();
$logRowForLocationTo = $this->Database->stock_log()->createRow(array(
$logRowForLocationTo = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount,
'best_before_date' => $newBestBeforeDate,
@@ -532,7 +533,7 @@ class StockService extends BaseService
{
$restStockAmount = $stockEntry->amount - $amount;
$logRowForLocationFrom = $this->Database->stock_log()->createRow(array(
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $amount * -1,
'best_before_date' => $stockEntry->best_before_date,
@@ -547,7 +548,7 @@ class StockService extends BaseService
));
$logRowForLocationFrom->save();
$logRowForLocationTo = $this->Database->stock_log()->createRow(array(
$logRowForLocationTo = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $amount,
'best_before_date' => $newBestBeforeDate,
@@ -568,7 +569,7 @@ class StockService extends BaseService
));
// The transfered amount gets into a new stock entry
$stockEntryNew = $this->Database->stock()->createRow(array(
$stockEntryNew = $this->getDatabase()->stock()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $amount,
'best_before_date' => $newBestBeforeDate,
@@ -585,13 +586,13 @@ class StockService extends BaseService
}
}
return $this->Database->lastInsertId();
return $this->getDatabase()->lastInsertId();
}
public function EditStockEntry(int $stockRowId, int $amount, $bestBeforeDate, $locationId, $price, $open, $purchasedDate)
{
$stockRow = $this->Database->stock()->where('id = :1', $stockRowId)->fetch();
$stockRow = $this->getDatabase()->stock()->where('id = :1', $stockRowId)->fetch();
if ($stockRow === null)
{
@@ -600,7 +601,7 @@ class StockService extends BaseService
$correlationId = uniqid();
$transactionId = uniqid();
$logOldRowForStockUpdate = $this->Database->stock_log()->createRow(array(
$logOldRowForStockUpdate = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockRow->product_id,
'amount' => $stockRow->amount,
'best_before_date' => $stockRow->best_before_date,
@@ -636,7 +637,7 @@ class StockService extends BaseService
'purchased_date' => $purchasedDate
));
$logNewRowForStockUpdate = $this->Database->stock_log()->createRow(array(
$logNewRowForStockUpdate = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockRow->product_id,
'amount' => $amount,
'best_before_date' => $bestBeforeDate,
@@ -652,7 +653,7 @@ class StockService extends BaseService
));
$logNewRowForStockUpdate->save();
return $this->Database->lastInsertId();
return $this->getDatabase()->lastInsertId();
}
public function InventoryProduct(int $productId, float $newAmount, $bestBeforeDate, $locationId = null, $price = null)
@@ -713,9 +714,9 @@ class StockService extends BaseService
throw new \Exception('Product does not exist');
}
$productStockAmountUnopened = $this->Database->stock()->where('product_id = :1 AND open = 0', $productId)->sum('amount');
$productStockAmountUnopened = $this->getDatabase()->stock()->where('product_id = :1 AND open = 0', $productId)->sum('amount');
$potentialStockEntries = $this->GetProductStockEntries($productId, true);
$product = $this->Database->products($productId);
$product = $this->getDatabase()->products($productId);
if ($amount > $productStockAmountUnopened)
{
@@ -742,7 +743,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount) // Mark the whole stock entry as opened
{
$logRow = $this->Database->stock_log()->createRow(array(
$logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount,
'best_before_date' => $stockEntry->best_before_date,
@@ -766,7 +767,7 @@ class StockService extends BaseService
{
$restStockAmount = $stockEntry->amount - $amount;
$newStockRow = $this->Database->stock()->createRow(array(
$newStockRow = $this->getDatabase()->stock()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $restStockAmount,
'best_before_date' => $stockEntry->best_before_date,
@@ -776,7 +777,7 @@ class StockService extends BaseService
));
$newStockRow->save();
$logRow = $this->Database->stock_log()->createRow(array(
$logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id,
'amount' => $amount,
'best_before_date' => $stockEntry->best_before_date,
@@ -799,7 +800,7 @@ class StockService extends BaseService
}
}
return $this->Database->lastInsertId();
return $this->getDatabase()->lastInsertId();
}
public function AddMissingProductsToShoppingList($listId = 1)
@@ -812,10 +813,10 @@ class StockService extends BaseService
$missingProducts = $this->GetMissingProducts();
foreach ($missingProducts as $missingProduct)
{
$product = $this->Database->products()->where('id', $missingProduct->id)->fetch();
$product = $this->getDatabase()->products()->where('id', $missingProduct->id)->fetch();
$amountToAdd = ceil($missingProduct->amount_missing / $product->qu_factor_purchase_to_stock);
$alreadyExistingEntry = $this->Database->shopping_list()->where('product_id', $missingProduct->id)->fetch();
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $missingProduct->id)->fetch();
if ($alreadyExistingEntry) // Update
{
if ($alreadyExistingEntry->amount < $amountToAdd)
@@ -828,7 +829,7 @@ class StockService extends BaseService
}
else // Insert
{
$shoppinglistRow = $this->Database->shopping_list()->createRow(array(
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow(array(
'product_id' => $missingProduct->id,
'amount' => $amountToAdd,
'shopping_list_id' => $listId
@@ -845,7 +846,7 @@ class StockService extends BaseService
throw new \Exception('Shopping list does not exist');
}
$this->Database->shopping_list()->where('shopping_list_id = :1', $listId)->delete();
$this->getDatabase()->shopping_list()->where('shopping_list_id = :1', $listId)->delete();
}
@@ -856,7 +857,7 @@ class StockService extends BaseService
throw new \Exception('Shopping list does not exist');
}
$productRow = $this->Database->shopping_list()->where('product_id = :1', $productId)->fetch();
$productRow = $this->getDatabase()->shopping_list()->where('product_id = :1', $productId)->fetch();
//If no entry was found with for this product, we return gracefully
if ($productRow != null && !empty($productRow))
@@ -886,7 +887,7 @@ class StockService extends BaseService
throw new \Exception('Product does not exist');
}
$alreadyExistingEntry = $this->Database->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch();
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch();
if ($alreadyExistingEntry) // Update
{
$alreadyExistingEntry->update(array(
@@ -897,7 +898,7 @@ class StockService extends BaseService
}
else // Insert
{
$shoppinglistRow = $this->Database->shopping_list()->createRow(array(
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow(array(
'product_id' => $productId,
'amount' => $amount,
'shopping_list_id' => $listId,
@@ -909,19 +910,19 @@ class StockService extends BaseService
private function ProductExists($productId)
{
$productRow = $this->Database->products()->where('id = :1', $productId)->fetch();
$productRow = $this->getDatabase()->products()->where('id = :1', $productId)->fetch();
return $productRow !== null;
}
private function LocationExists($locationId)
{
$locationRow = $this->Database->locations()->where('id = :1', $locationId)->fetch();
$locationRow = $this->getDatabase()->locations()->where('id = :1', $locationId)->fetch();
return $locationRow !== null;
}
private function ShoppingListExists($listId)
{
$shoppingListRow = $this->Database->shopping_lists()->where('id = :1', $listId)->fetch();
$shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch();
return $shoppingListRow !== null;
}
@@ -937,7 +938,7 @@ class StockService extends BaseService
if (file_exists($path))
{
require_once $path;
return new $pluginName($this->Database->locations()->fetchAll(), $this->Database->quantity_units()->fetchAll());
return new $pluginName($this->getDatabase()->locations()->fetchAll(), $this->getDatabase()->quantity_units()->fetchAll());
}
else
{
@@ -955,7 +956,7 @@ class StockService extends BaseService
if ($addFoundProduct === true)
{
// Add product to database and include new product id in output
$newRow = $this->Database->products()->createRow($pluginOutput);
$newRow = $this->getDatabase()->products()->createRow($pluginOutput);
$newRow->save();
$pluginOutput['id'] = $newRow->id;
@@ -967,7 +968,7 @@ class StockService extends BaseService
public function UndoBooking($bookingId, $skipCorrelatedBookings = false)
{
$logRow = $this->Database->stock_log()->where('id = :1 AND undone = 0', $bookingId)->fetch();
$logRow = $this->getDatabase()->stock_log()->where('id = :1 AND undone = 0', $bookingId)->fetch();
if ($logRow == null)
{
throw new \Exception('Booking does not exist or was already undone');
@@ -976,7 +977,7 @@ class StockService extends BaseService
// Undo all correlated bookings first, in order from newest first to the oldest
if (!$skipCorrelatedBookings && !empty($logRow->correlation_id))
{
$correlatedBookings = $this->Database->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll();
$correlatedBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll();
foreach ($correlatedBookings as $correlatedBooking)
{
$this->UndoBooking($correlatedBooking->id, true);
@@ -984,7 +985,7 @@ class StockService extends BaseService
return;
}
$hasSubsequentBookings = $this->Database->stock_log()->where('stock_id = :1 AND id != :2 AND (correlation_id is not null OR correlation_id != :3) AND id > :2 AND undone = 0', $logRow->stock_id, $logRow->id, $logRow->correlation_id)->count() > 0;
$hasSubsequentBookings = $this->getDatabase()->stock_log()->where('stock_id = :1 AND id != :2 AND (correlation_id is not null OR correlation_id != :3) AND id > :2 AND undone = 0', $logRow->stock_id, $logRow->id, $logRow->correlation_id)->count() > 0;
if ($hasSubsequentBookings)
{
throw new \Exception('Booking has subsequent dependent bookings, undo not possible');
@@ -993,7 +994,7 @@ class StockService extends BaseService
if ($logRow->transaction_type === self::TRANSACTION_TYPE_PURCHASE || ($logRow->transaction_type === self::TRANSACTION_TYPE_INVENTORY_CORRECTION && $logRow->amount > 0))
{
// Remove corresponding stock entry
$stockRows = $this->Database->stock()->where('stock_id', $logRow->stock_id);
$stockRows = $this->getDatabase()->stock()->where('stock_id', $logRow->stock_id);
$stockRows->delete();
// Update log entry
@@ -1005,7 +1006,7 @@ class StockService extends BaseService
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_CONSUME || ($logRow->transaction_type === self::TRANSACTION_TYPE_INVENTORY_CORRECTION && $logRow->amount < 0))
{
// Add corresponding amount back to stock
$stockRow = $this->Database->stock()->createRow(array(
$stockRow = $this->getDatabase()->stock()->createRow(array(
'product_id' => $logRow->product_id,
'amount' => $logRow->amount * -1,
'best_before_date' => $logRow->best_before_date,
@@ -1024,7 +1025,7 @@ class StockService extends BaseService
}
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_TRANSFER_TO)
{
$stockRow = $this->Database->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch();
$stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch();
if ($stockRow === null)
{
throw new \Exception('Booking does not exist or was already undone');
@@ -1051,10 +1052,10 @@ class StockService extends BaseService
{
// Add corresponding amount back to stock or
// create a row if missing
$stockRow = $this->Database->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch();
$stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch();
if ($stockRow === null)
{
$stockRow = $this->Database->stock()->createRow(array(
$stockRow = $this->getDatabase()->stock()->createRow(array(
'product_id' => $logRow->product_id,
'amount' => $logRow->amount * -1,
'best_before_date' => $logRow->best_before_date,
@@ -1079,7 +1080,7 @@ class StockService extends BaseService
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_PRODUCT_OPENED)
{
// Remove opened flag from corresponding log entry
$stockRows = $this->Database->stock()->where('stock_id = :1 AND amount = :2 AND purchased_date = :3', $logRow->stock_id, $logRow->amount, $logRow->purchased_date)->limit(1);
$stockRows = $this->getDatabase()->stock()->where('stock_id = :1 AND amount = :2 AND purchased_date = :3', $logRow->stock_id, $logRow->amount, $logRow->purchased_date)->limit(1);
$stockRows->update(array(
'open' => 0,
'opened_date' => null
@@ -1102,7 +1103,7 @@ class StockService extends BaseService
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_STOCK_EDIT_OLD)
{
// Make sure there is a stock row still
$stockRow = $this->Database->stock()->where('id = :1', $logRow->stock_row_id)->fetch();
$stockRow = $this->getDatabase()->stock()->where('id = :1', $logRow->stock_row_id)->fetch();
if ($stockRow == null)
{
throw new \Exception('Booking does not exist or was already undone');
@@ -1139,7 +1140,7 @@ class StockService extends BaseService
public function UndoTransaction($transactionId)
{
$transactionBookings = $this->Database->stock_log()->where('undone = 0 AND transaction_id = :1', $transactionId)->orderBy('id', 'DESC')->fetchAll();
$transactionBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND transaction_id = :1', $transactionId)->orderBy('id', 'DESC')->fetchAll();
if (count($transactionBookings) === 0)
{

View File

@@ -7,7 +7,7 @@ class TasksService extends BaseService
public function GetCurrent()
{
$sql = 'SELECT * from tasks_current';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function MarkTaskAsCompleted($taskId, $doneTime)
@@ -17,7 +17,7 @@ class TasksService extends BaseService
throw new \Exception('Task does not exist');
}
$taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch();
$taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch();
$taskRow->update(array(
'done' => 1,
'done_timestamp' => $doneTime
@@ -33,7 +33,7 @@ class TasksService extends BaseService
throw new \Exception('Task does not exist');
}
$taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch();
$taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch();
$taskRow->update(array(
'done' => 0,
'done_timestamp' => null
@@ -44,7 +44,7 @@ class TasksService extends BaseService
private function TaskExists($taskId)
{
$taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch();
$taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch();
return $taskRow !== null;
}
}

View File

@@ -18,11 +18,19 @@ class UserfieldsService extends BaseService
public function __construct()
{
parent::__construct();
$this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json'));
}
protected $OpenApiSpec;
protected $OpenApiSpec = null;
protected function getOpenApispec()
{
if($this->OpenApiSpec == null)
{
$this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json'));
}
return $this->OpenApiSpec;
}
public function GetFields($entity)
{
if (!$this->IsValidEntity($entity))
@@ -30,17 +38,17 @@ class UserfieldsService extends BaseService
throw new \Exception('Entity does not exist or is not exposed');
}
return $this->Database->userfields()->where('entity', $entity)->orderBy('name')->fetchAll();
return $this->getDatabase()->userfields()->where('entity', $entity)->orderBy('name')->fetchAll();
}
public function GetField($fieldId)
{
return $this->Database->userfields($fieldId);
return $this->getDatabase()->userfields($fieldId);
}
public function GetAllFields()
{
return $this->Database->userfields()->orderBy('name')->fetchAll();
return $this->getDatabase()->userfields()->orderBy('name')->fetchAll();
}
public function GetValues($entity, $objectId)
@@ -50,7 +58,7 @@ class UserfieldsService extends BaseService
throw new \Exception('Entity does not exist or is not exposed');
}
$userfields = $this->Database->userfield_values_resolved()->where('entity = :1 AND object_id = :2', $entity, $objectId)->orderBy('name')->fetchAll();
$userfields = $this->getDatabase()->userfield_values_resolved()->where('entity = :1 AND object_id = :2', $entity, $objectId)->orderBy('name')->fetchAll();
$userfieldKeyValuePairs = array();
foreach ($userfields as $userfield)
{
@@ -67,7 +75,7 @@ class UserfieldsService extends BaseService
throw new \Exception('Entity does not exist or is not exposed');
}
return $this->Database->userfield_values_resolved()->where('entity', $entity)->orderBy('name')->fetchAll();
return $this->getDatabase()->userfield_values_resolved()->where('entity', $entity)->orderBy('name')->fetchAll();
}
public function SetValues($entity, $objectId, $userfields)
@@ -79,7 +87,7 @@ class UserfieldsService extends BaseService
foreach ($userfields as $key => $value)
{
$fieldRow = $this->Database->userfields()->where('entity = :1 AND name = :2', $entity, $key)->fetch();
$fieldRow = $this->getDatabase()->userfields()->where('entity = :1 AND name = :2', $entity, $key)->fetch();
if ($fieldRow === null)
{
@@ -88,7 +96,7 @@ class UserfieldsService extends BaseService
$fieldId = $fieldRow->id;
$alreadyExistingEntry = $this->Database->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch();
$alreadyExistingEntry = $this->getDatabase()->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch();
if ($alreadyExistingEntry) // Update
{
$alreadyExistingEntry->update(array(
@@ -97,7 +105,7 @@ class UserfieldsService extends BaseService
}
else // Insert
{
$newRow = $this->Database->userfield_values()->createRow(array(
$newRow = $this->getDatabase()->userfield_values()->createRow(array(
'field_id' => $fieldId,
'object_id' => $objectId,
'value' => $value
@@ -109,10 +117,10 @@ class UserfieldsService extends BaseService
public function GetEntities()
{
$exposedDefaultEntities = $this->OpenApiSpec->components->internalSchemas->ExposedEntity->enum;
$exposedDefaultEntities = $this->getOpenApiSpec()->components->internalSchemas->ExposedEntity->enum;
$userentities = array();
foreach ($this->Database->userentities()->orderBy('name') as $userentity)
foreach ($this->getDatabase()->userentities()->orderBy('name') as $userentity)
{
$userentities[] = 'userentity-' . $userentity->name;
}

View File

@@ -6,7 +6,7 @@ class UsersService extends BaseService
{
public function CreateUser(string $username, string $firstName, string $lastName, string $password)
{
$newUserRow = $this->Database->users()->createRow(array(
$newUserRow = $this->getDatabase()->users()->createRow(array(
'username' => $username,
'first_name' => $firstName,
'last_name' => $lastName,
@@ -22,7 +22,7 @@ class UsersService extends BaseService
throw new \Exception('User does not exist');
}
$user = $this->Database->users($userId);
$user = $this->getDatabase()->users($userId);
$user->update(array(
'username' => $username,
'first_name' => $firstName,
@@ -33,13 +33,13 @@ class UsersService extends BaseService
public function DeleteUser($userId)
{
$row = $this->Database->users($userId);
$row = $this->getDatabase()->users($userId);
$row->delete();
}
public function GetUsersAsDto()
{
$users = $this->Database->users();
$users = $this->getDatabase()->users();
$returnUsers = array();
foreach ($users as $user)
{
@@ -52,7 +52,7 @@ class UsersService extends BaseService
public function GetUserSetting($userId, $settingKey)
{
$settingRow = $this->Database->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch();
$settingRow = $this->getDatabase()->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch();
if ($settingRow !== null)
{
return $settingRow->value;
@@ -67,7 +67,7 @@ class UsersService extends BaseService
{
$settings = array();
$settingRows = $this->Database->user_settings()->where('user_id = :1', $userId)->fetchAll();
$settingRows = $this->getDatabase()->user_settings()->where('user_id = :1', $userId)->fetchAll();
foreach ($settingRows as $settingRow)
{
$settings[$settingRow->key] = $settingRow->value;
@@ -80,7 +80,7 @@ class UsersService extends BaseService
public function SetUserSetting($userId, $settingKey, $settingValue)
{
$settingRow = $this->Database->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch();
$settingRow = $this->getDatabase()->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch();
if ($settingRow !== null)
{
$settingRow->update(array(
@@ -90,7 +90,7 @@ class UsersService extends BaseService
}
else
{
$settingRow = $this->Database->user_settings()->createRow(array(
$settingRow = $this->getDatabase()->user_settings()->createRow(array(
'user_id' => $userId,
'key' => $settingKey,
'value' => $settingValue
@@ -101,7 +101,7 @@ class UsersService extends BaseService
private function UserExists($userId)
{
$userRow = $this->Database->users()->where('id = :1', $userId)->fetch();
$userRow = $this->getDatabase()->users()->where('id = :1', $userId)->fetch();
return $userRow !== null;
}
}