Applied PHP-CS-Fixer rules

This commit is contained in:
Bernd Bestel 2020-09-01 21:29:47 +02:00
parent 3da8904cba
commit 836bcc82e5
No known key found for this signature in database
GPG Key ID: 71BD34C0D4891300
56 changed files with 150 additions and 467 deletions

12
app.php
View File

@ -38,20 +38,16 @@ AppFactory::setContainer(new DI\Container());
$app = AppFactory::create();
$container = $app->getContainer();
$container->set('view', function (Container $container)
{
$container->set('view', function (Container $container) {
return new Slim\Views\Blade(__DIR__ . '/views', GROCY_DATAPATH . '/viewcache');
});
$container->set('LoginControllerInstance', function (Container $container)
{
$container->set('LoginControllerInstance', function (Container $container) {
return new LoginController($container, 'grocy_session');
});
$container->set('UrlManager', function (Container $container)
{
$container->set('UrlManager', function (Container $container) {
return new UrlManager(GROCY_BASE_URL);
});
$container->set('ApiKeyHeaderName', function (Container $container)
{
$container->set('ApiKeyHeaderName', function (Container $container) {
return 'GROCY-API-KEY';
});

View File

@ -44,22 +44,31 @@ class BaseApiController extends BaseController
protected function queryData(Result $data, array $query)
{
if (isset($query['query']))
{
$data = $this->filter($data, $query['query']);
}
if (isset($query['limit']))
{
$data = $data->limit(intval($query['limit']), intval($query['offset'] ?? 0));
}
if (isset($query['order']))
{
$data = $data->orderBy($query['order']);
}
return $data;
}
protected function filter(Result $data, array $query): Result
{
foreach ($query as $q) {
$matches = array();
preg_match('/(?P<field>' . self::PATTERN_FIELD . ')'
foreach ($query as $q)
{
$matches = [];
preg_match(
'/(?P<field>' . self::PATTERN_FIELD . ')'
. '(?P<op>' . self::PATTERN_OPERATOR . ')'
. '(?P<value>' . self::PATTERN_VALUE . ')/',
$q, $matches
$q,
$matches
);
error_log(var_export($matches, true));
switch ($matches['op']) {
@ -106,5 +115,4 @@ class BaseApiController extends BaseController
return $this->OpenApiSpec;
}
}

View File

@ -112,18 +112,15 @@ class BaseController
$this->View->set('releaseDate', $versionInfo->ReleaseDate);
$localizationService = $this->getLocalizationService();
$this->View->set('__t', function (string $text, ...$placeholderValues) use ($localizationService)
{
$this->View->set('__t', function (string $text, ...$placeholderValues) use ($localizationService) {
return $localizationService->__t($text, $placeholderValues);
});
$this->View->set('__n', function ($number, $singularForm, $pluralForm) use ($localizationService)
{
$this->View->set('__n', function ($number, $singularForm, $pluralForm) use ($localizationService) {
return $localizationService->__n($number, $singularForm, $pluralForm);
});
$this->View->set('GettextPo', $localizationService->GetPoAsJsonString());
$this->View->set('U', function ($relativePath, $isResource = false) use ($container)
{
$this->View->set('U', function ($relativePath, $isResource = false) use ($container) {
return $container->get('UrlManager')->ConstructUrl($relativePath, $isResource);
});
@ -144,7 +141,6 @@ class BaseController
{
unset($constants[$constant]);
}
}
$this->View->set('featureFlags', $constants);
@ -172,7 +168,6 @@ class BaseController
{
$this->View->set('userSettings', null);
}
}
catch (\Exception $ex)
{
@ -181,5 +176,4 @@ class BaseController
return $this->render($response, $page, $data);
}
}

View File

@ -16,7 +16,6 @@ class BatteriesApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -46,7 +45,6 @@ class BatteriesApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function UndoChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -62,12 +60,10 @@ class BatteriesApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function __construct(\DI\Container $container)
{
parent::__construct($container);
}
}

View File

@ -35,7 +35,6 @@ class BatteriesController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('batteries')
]);
}
}
public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -71,5 +70,4 @@ class BatteriesController extends BaseController
{
parent::__construct($container);
}
}

View File

@ -47,7 +47,6 @@ class CalendarApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function IcalSharingLink(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -62,12 +61,10 @@ class CalendarApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function __construct(\DI\Container $container)
{
parent::__construct($container);
}
}

View File

@ -27,7 +27,6 @@ class ChoresApiController extends BaseApiController
{
$this->getChoresService()->CalculateNextExecutionAssignment($chore->id);
}
}
else
{
@ -40,7 +39,6 @@ class ChoresApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ChoreDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -53,7 +51,6 @@ class ChoresApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -95,7 +92,6 @@ class ChoresApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function UndoChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -111,12 +107,10 @@ class ChoresApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function __construct(\DI\Container $container)
{
parent::__construct($container);
}
}

View File

@ -32,7 +32,6 @@ class ChoresController extends BaseController
'products' => $this->getDatabase()->products()->orderBy('name')
]);
}
}
public function ChoresList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -85,5 +84,4 @@ class ChoresController extends BaseController
{
parent::__construct($container);
}
}

View File

@ -23,7 +23,6 @@ class EquipmentController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('equipment')
]);
}
}
public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -39,5 +38,4 @@ class EquipmentController extends BaseController
{
parent::__construct($container);
}
}

View File

@ -73,5 +73,4 @@ class ExceptionController extends BaseApiController
'exception' => $exception
]);
}
}

View File

@ -33,7 +33,6 @@ class FilesApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ServeFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -55,13 +54,11 @@ class FilesApiController extends BaseApiController
{
throw new HttpNotFoundException($request, 'File not found');
}
}
catch (\Exception $ex)
{
throw new HttpNotFoundException($request, $ex->getMessage(), $ex);
}
}
public function ShowFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -84,13 +81,11 @@ class FilesApiController extends BaseApiController
{
throw new HttpNotFoundException($request, 'File not found');
}
}
catch (\Exception $ex)
{
throw new HttpNotFoundException($request, $ex->getMessage(), $ex);
}
}
public function UploadFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -108,7 +103,6 @@ class FilesApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function __construct(\DI\Container $container)
@ -175,5 +169,4 @@ class FilesApiController extends BaseApiController
return $filePath;
}
}

View File

@ -34,13 +34,11 @@ class GenericEntityApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
else
{
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
}
}
public function DeleteObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -59,7 +57,6 @@ class GenericEntityApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function EditObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -87,13 +84,11 @@ class GenericEntityApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
else
{
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
}
}
public function GetObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -123,7 +118,6 @@ class GenericEntityApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
}
}
public function GetObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -143,7 +137,6 @@ class GenericEntityApiController extends BaseApiController
{
$userfieldKeyValuePairs[$userfield->name] = $userfield->value;
}
}
$object->userfields = $userfieldKeyValuePairs;
@ -157,7 +150,6 @@ class GenericEntityApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
}
}
public function GetUserfields(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -170,7 +162,6 @@ class GenericEntityApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function SearchObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -187,13 +178,11 @@ class GenericEntityApiController extends BaseApiController
throw new HttpBadRequestException($request, $ex->getMessage(), $ex);
//return $this->GenericErrorResponse($response, 'The given entity has no field "name"', $ex);
}
}
else
{
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
}
}
public function SetUserfields(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -216,7 +205,6 @@ class GenericEntityApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function __construct(\DI\Container $container)
@ -233,5 +221,4 @@ class GenericEntityApiController extends BaseApiController
{
return in_array($entity, $this->getOpenApiSpec()->components->internalSchemas->ExposedEntity->enum);
}
}

View File

@ -26,7 +26,6 @@ class GenericEntityController extends BaseController
'userentity' => $this->getDatabase()->userentities($args['userentityId'])
]);
}
}
public function UserfieldEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -48,7 +47,6 @@ class GenericEntityController extends BaseController
'entities' => $this->getUserfieldsService()->GetEntities()
]);
}
}
public function UserfieldsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -80,7 +78,6 @@ class GenericEntityController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName'])
]);
}
}
public function UserobjectsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -99,5 +96,4 @@ class GenericEntityController extends BaseController
{
parent::__construct($container);
}
}

View File

@ -37,7 +37,7 @@ class LoginController extends BaseController
$sessionKey = $this->getSessionService()->CreateSession($user->id, $stayLoggedInPermanently);
setcookie($this->SessionCookieName, $sessionKey, PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX >> 32);
// Cookie expires never, but session validity is up to SessionService
// Cookie expires never, but session validity is up to SessionService
if (password_needs_rehash($user->password, PASSWORD_DEFAULT))
{
@ -52,13 +52,11 @@ class LoginController extends BaseController
{
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/login?invalid=true'));
}
}
else
{
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/login?invalid=true'));
}
}
public function __construct(\DI\Container $container, string $sessionCookieName)
@ -66,5 +64,4 @@ class LoginController extends BaseController
parent::__construct($container);
$this->SessionCookieName = $sessionCookieName;
}
}

View File

@ -35,7 +35,6 @@ class RecipesApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function GetRecipeFulfillment(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -57,18 +56,15 @@ class RecipesApiController extends BaseApiController
{
return $this->ApiResponse($response, $recipeResolved);
}
}
catch (\Exception $ex)
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function __construct(\DI\Container $container)
{
parent::__construct($container);
}
}

View File

@ -70,7 +70,6 @@ class RecipesController extends BaseController
$selectedRecipe = $recipe;
break;
}
}
$selectedRecipePositionsResolved = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $selectedRecipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC');
@ -160,7 +159,6 @@ class RecipesController extends BaseController
'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved()
]);
}
}
public function RecipesSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -172,5 +170,4 @@ class RecipesController extends BaseController
{
parent::__construct($container);
}
}

View File

@ -29,7 +29,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function AddProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -99,7 +98,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function AddProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -113,7 +111,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function AddProductToShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -161,7 +158,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ClearShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -186,7 +182,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ConsumeProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -266,7 +261,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function CurrentStock(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -346,7 +340,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ExternalBarcodeLookup(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -368,7 +361,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function InventoryProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -424,7 +416,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function InventoryProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -438,7 +429,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function OpenProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -473,7 +463,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function OpenProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -487,7 +476,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ProductBarcodeDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -500,7 +488,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ProductDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -513,7 +500,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ProductDetailsByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -527,7 +513,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ProductPriceHistory(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -540,7 +525,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ProductStockEntries(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -599,7 +583,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function StockBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -619,7 +602,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function StockEntry(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -644,7 +626,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function TransferProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -689,7 +670,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function TransferProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -703,7 +683,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function UndoBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -719,7 +698,6 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function UndoTransaction(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -735,12 +713,10 @@ class StockApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function __construct(\DI\Container $container)
{
parent::__construct($container);
}
}

View File

@ -67,7 +67,6 @@ class StockController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('locations')
]);
}
}
public function LocationsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -122,7 +121,6 @@ class StockController extends BaseController
'shoppinglocations' => $this->getDatabase()->shopping_locations()->orderBy('name')
]);
}
}
public function ProductEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -159,7 +157,6 @@ class StockController extends BaseController
'quConversions' => $this->getDatabase()->quantity_unit_conversions()
]);
}
}
public function ProductGroupEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -179,7 +176,6 @@ class StockController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('product_groups')
]);
}
}
public function ProductGroupsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -254,7 +250,6 @@ class StockController extends BaseController
'defaultQuUnit' => $defaultQuUnit
]);
}
}
public function QuantityUnitEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -282,7 +277,6 @@ class StockController extends BaseController
'quantityUnits' => $this->getDatabase()->quantity_units()
]);
}
}
public function QuantityUnitPluralFormTesting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -338,7 +332,6 @@ class StockController extends BaseController
'mode' => 'edit'
]);
}
}
public function ShoppingListItemEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -360,7 +353,6 @@ class StockController extends BaseController
'mode' => 'edit'
]);
}
}
public function ShoppingListSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -385,7 +377,6 @@ class StockController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('shopping_locations')
]);
}
}
public function ShoppingLocationsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -451,5 +442,4 @@ class StockController extends BaseController
{
parent::__construct($container);
}
}

View File

@ -11,10 +11,7 @@ class SystemApiController extends BaseApiController
$constants = get_defined_constants();
// Some GROCY_* constants are not really config settings and therefore should not be exposed
unset($constants['GROCY_AUTHENTICATED']);
unset($constants['GROCY_DATAPATH']);
unset($constants['GROCY_IS_EMBEDDED_INSTALL']);
unset($constants['GROCY_USER_ID']);
unset($constants['GROCY_AUTHENTICATED'], $constants['GROCY_DATAPATH'], $constants['GROCY_IS_EMBEDDED_INSTALL'], $constants['GROCY_USER_ID']);
$returnArray = [];
@ -24,7 +21,6 @@ class SystemApiController extends BaseApiController
{
$returnArray[substr($constant, 6)] = $value;
}
}
return $this->ApiResponse($response, $returnArray);
@ -33,7 +29,6 @@ class SystemApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function GetDbChangedTime(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -63,14 +58,11 @@ class SystemApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
}
public function __construct(\DI\Container $container)
{
parent::__construct($container);
}
}

View File

@ -59,37 +59,37 @@ class SystemController extends BaseController
$entryPage = 'stock';
}
// Stock
// Stock
if ($entryPage === 'stock' && constant('GROCY_FEATURE_FLAG_STOCK'))
{
return '/stockoverview';
}
// Shoppinglist
// Shoppinglist
if ($entryPage === 'shoppinglist' && constant('GROCY_FEATURE_FLAG_SHOPPINGLIST'))
{
return '/shoppinglist';
}
// Recipes
// Recipes
if ($entryPage === 'recipes' && constant('GROCY_FEATURE_FLAG_RECIPES'))
{
return '/recipes';
}
// Chores
// Chores
if ($entryPage === 'chores' && constant('GROCY_FEATURE_FLAG_CHORES'))
{
return '/choresoverview';
}
// Tasks
// Tasks
if ($entryPage === 'tasks' && constant('GROCY_FEATURE_FLAG_TASKS'))
{
return '/tasks';
}
// Batteries
// Batteries
if ($entryPage === 'batteries' && constant('GROCY_FEATURE_FLAG_BATTERIES'))
{
return '/batteriesoverview';
@ -100,13 +100,13 @@ class SystemController extends BaseController
return '/equipment';
}
// Calendar
// Calendar
if ($entryPage === 'calendar' && constant('GROCY_FEATURE_FLAG_CALENDAR'))
{
return '/calendar';
}
// Meal Plan
// Meal Plan
if ($entryPage === 'mealplan' && constant('GROCY_FEATURE_FLAG_RECIPES'))
{
return '/mealplan';
@ -114,5 +114,4 @@ class SystemController extends BaseController
return '/about';
}
}

View File

@ -33,7 +33,6 @@ class TasksApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function UndoTask(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -49,12 +48,10 @@ class TasksApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function __construct(\DI\Container $container)
{
parent::__construct($container);
}
}

View File

@ -54,7 +54,6 @@ class TasksController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('task_categories')
]);
}
}
public function TaskEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -78,7 +77,6 @@ class TasksController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('tasks')
]);
}
}
public function TasksSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -90,5 +88,4 @@ class TasksController extends BaseController
{
parent::__construct($container);
}
}

View File

@ -10,17 +10,13 @@ class User
const PERMISSION_ADMIN = 'ADMIN';
const PERMISSION_BATTERIES = 'BATTERIES';
const PERMISSION_BATTERIES_TRACK_CHARGE_CYCLE = 'BATTERIES_TRACK_CHARGE_CYCLE';
const PERMISSION_BATTERIES_UNDO_CHARGE_CYCLE = 'BATTERIES_UNDO_CHARGE_CYCLE';
const PERMISSION_CALENDAR = 'CALENDAR';
const PERMISSION_CHORES = 'CHORES';
const PERMISSION_CHORE_TRACK_EXECUTION = 'CHORE_TRACK_EXECUTION';
const PERMISSION_CHORE_UNDO_EXECUTION = 'CHORE_UNDO_EXECUTION';
const PERMISSION_EQUIPMENT = 'EQUIPMENT';
@ -28,43 +24,28 @@ class User
const PERMISSION_MASTER_DATA_EDIT = 'MASTER_DATA_EDIT';
const PERMISSION_RECIPES = 'RECIPES';
const PERMISSION_RECIPES_MEALPLAN = 'RECIPES_MEALPLAN';
const PERMISSION_SHOPPINGLIST = 'SHOPPINGLIST';
const PERMISSION_SHOPPINGLIST_ITEMS_ADD = 'SHOPPINGLIST_ITEMS_ADD';
const PERMISSION_SHOPPINGLIST_ITEMS_DELETE = 'SHOPPINGLIST_ITEMS_DELETE';
const PERMISSION_STOCK = 'STOCK';
const PERMISSION_STOCK_CONSUME = 'STOCK_CONSUME';
const PERMISSION_STOCK_EDIT = 'STOCK_EDIT';
const PERMISSION_STOCK_INVENTORY = 'STOCK_INVENTORY';
const PERMISSION_STOCK_OPEN = 'STOCK_OPEN';
const PERMISSION_STOCK_PURCHASE = 'STOCK_PURCHASE';
const PERMISSION_STOCK_TRANSFER = 'STOCK_TRANSFER';
const PERMISSION_TASKS = 'TASKS';
const PERMISSION_TASKS_MARK_COMPLETED = 'TASKS_MARK_COMPLETED';
const PERMISSION_TASKS_UNDO_EXECUTION = 'TASKS_UNDO_EXECUTION';
const PERMISSION_USERS = 'USERS';
const PERMISSION_USERS_CREATE = 'USERS_CREATE';
const PERMISSION_USERS_EDIT = 'USERS_EDIT';
const PERMISSION_USERS_EDIT_SELF = 'USERS_EDIT_SELF';
const PERMISSION_USERS_READ = 'USERS_READ';
/**
@ -81,10 +62,9 @@ class User
public function __construct()
{
$this->db = DatabaseService::getInstance()->GetDbConnection();
}
public static function checkPermission($request, string...$permissions): void
public static function checkPermission($request, string ...$permissions): void
{
$user = new self();
@ -94,9 +74,7 @@ class User
{
throw new PermissionMissingException($request, $permission);
}
}
}
public function getPermissionList()
@ -106,14 +84,14 @@ class User
public function hasPermission(string $permission): bool
{
// global $PERMISSION_CACHE;
// global $PERMISSION_CACHE;
// if(isset($PERMISSION_CACHE[$permission]))
// if(isset($PERMISSION_CACHE[$permission]))
// return $PERMISSION_CACHE[$permission];
return $this->getPermissions()->where('permission_name', $permission)->fetch() !== null;
}
public static function hasPermissions(string...$permissions)
public static function hasPermissions(string ...$permissions)
{
$user = new self();
@ -123,7 +101,6 @@ class User
{
return false;
}
}
return true;
@ -133,5 +110,4 @@ class User
{
return $this->db->user_permissions_resolved()->where('user_id', GROCY_USER_ID);
}
}

View File

@ -8,7 +8,8 @@ class UsersApiController extends BaseApiController
{
public function AddPermission(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{
try {
try
{
User::checkPermission($request, User::PERMISSION_ADMIN);
$requestBody = $request->getParsedBody();
@ -26,7 +27,6 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function CreateUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -48,7 +48,6 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function DeleteUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -63,7 +62,6 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function EditUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -88,7 +86,6 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function GetUserSetting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -102,7 +99,6 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function GetUserSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -115,7 +111,6 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function GetUsers(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -129,15 +124,16 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function ListPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{
try {
try
{
User::checkPermission($request, User::PERMISSION_ADMIN);
return $this->ApiResponse($response,
return $this->ApiResponse(
$response,
$this->getDatabase()->user_permissions()->where($args['userId'])
);
}
@ -149,12 +145,12 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function SetPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{
try {
try
{
User::checkPermission($request, User::PERMISSION_ADMIN);
$requestBody = $request->getParsedBody();
$db = $this->getDatabase();
@ -184,7 +180,6 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function SetUserSetting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -200,12 +195,10 @@ class UsersApiController extends BaseApiController
{
return $this->GenericErrorResponse($response, $ex->getMessage());
}
}
public function __construct(\DI\Container $container)
{
parent::__construct($container);
}
}

View File

@ -41,14 +41,12 @@ class UsersController extends BaseController
'mode' => 'edit'
]);
}
}
public function UserSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{
return $this->renderPage($response, 'usersettings', [
'languages' => array_filter(scandir(__DIR__ . '/../localization'), function ($item)
{
'languages' => array_filter(scandir(__DIR__ . '/../localization'), function ($item) {
if ($item == '.' || $item == '..')
{
return false;
@ -56,7 +54,6 @@ class UsersController extends BaseController
return is_dir(__DIR__ . '/../localization/' . $item);
})
]);
}
@ -67,5 +64,4 @@ class UsersController extends BaseController
'users' => $this->getDatabase()->users()->orderBy('username')
]);
}
}

View File

@ -1,6 +1,6 @@
<?php
use \Grocy\Helpers\BaseBarcodeLookupPlugin;
use Grocy\Helpers\BaseBarcodeLookupPlugin;
/*
This class must extend BaseBarcodeLookupPlugin (in namespace \Grocy\Helpers)
@ -55,24 +55,24 @@ class DemoBarcodeLookupPlugin extends BaseBarcodeLookupPlugin
*/
protected function ExecuteLookup($barcode)
{
if ($barcode === 'x') // Demonstration when nothing is found
{
if ($barcode === 'x')
{ // Demonstration when nothing is found
return null;
}
elseif ($barcode === 'e') // Demonstration when an error occurred
{
elseif ($barcode === 'e')
{ // Demonstration when an error occurred
throw new \Exception('This is the error message from the plugin...');
}
else
{
return array(
return [
'name' => 'LookedUpProduct_' . RandomString(5),
'location_id' => $this->Locations[0]->id,
'qu_id_purchase' => $this->QuantityUnits[0]->id,
'qu_id_stock' => $this->QuantityUnits[0]->id,
'qu_factor_purchase_to_stock' => 1,
'barcode' => $barcode
);
];
}
}
}

View File

@ -17,14 +17,14 @@ abstract class BaseBarcodeLookupPlugin
return $pluginOutput;
}
// Plugin must return an associative array
// Plugin must return an associative array
if (!is_array($pluginOutput))
{
throw new \Exception('Plugin output must be an associative array');
}
if (!IsAssociativeArray($pluginOutput)) // $pluginOutput is at least an indexed array here
{
if (!IsAssociativeArray($pluginOutput))
{ // $pluginOutput is at least an indexed array here
throw new \Exception('Plugin output must be an associative array');
}
@ -44,10 +44,9 @@ abstract class BaseBarcodeLookupPlugin
{
throw new \Exception("Plugin output does not provide needed property $prop");
}
}
// $pluginOutput contains all needed properties here
// $pluginOutput contains all needed properties here
// Check referenced entity ids are valid
$locationId = $pluginOutput['location_id'];

View File

@ -24,7 +24,6 @@ class PrerequisiteChecker
{
throw new ERequirementNotMet('/vendor/autoload.php not found. Have you run Composer?');
}
}
private function checkForConfigDistFile()
@ -33,7 +32,6 @@ class PrerequisiteChecker
{
throw new ERequirementNotMet('config-dist.php not found. Please do not remove this file.');
}
}
private function checkForConfigFile()
@ -42,7 +40,6 @@ class PrerequisiteChecker
{
throw new ERequirementNotMet('config.php in data directory (' . GROCY_DATAPATH . ') not found. Have you copied config-dist.php to the data directory and renamed it to config.php?');
}
}
private function checkForPhpExtensions()
@ -55,9 +52,7 @@ class PrerequisiteChecker
{
throw new ERequirementNotMet("PHP module '{$extension}' not installed, but required.");
}
}
}
private function checkForSqliteVersion()
@ -68,7 +63,6 @@ class PrerequisiteChecker
{
throw new ERequirementNotMet('SQLite ' . REQUIRED_SQLITE_VERSION . ' is required, however you are running ' . $sqliteVersion);
}
}
private function getSqlVersionAsString()
@ -76,5 +70,4 @@ class PrerequisiteChecker
$dbh = new PDO('sqlite::memory:');
return $dbh->query('select sqlite_version()')->fetch()[0];
}
}

View File

@ -12,11 +12,10 @@ class UrlManager
{
return rtrim($this->BasePath, '/') . $relativePath;
}
else // Is not a resource and URL rewriting is disabled
{
else
{ // Is not a resource and URL rewriting is disabled
return rtrim($this->BasePath, '/') . '/index.php' . $relativePath;
}
}
public function __construct(string $basePath)
@ -29,7 +28,6 @@ class UrlManager
{
$this->BasePath = $basePath;
}
}
private function GetBaseUrl()
@ -41,5 +39,4 @@ class UrlManager
return (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]";
}
}

View File

@ -9,7 +9,6 @@ function FindObjectInArrayByPropertyValue($array, $propertyName, $propertyValue)
{
return $object;
}
}
return null;
@ -25,7 +24,7 @@ function FindAllObjectsInArrayByPropertyValue($array, $propertyName, $propertyVa
{
case '==':
if ($object-> {$propertyName}
if ($object->{$propertyName}
== $propertyValue)
{
$returnArray[] = $object;
@ -34,7 +33,7 @@ function FindAllObjectsInArrayByPropertyValue($array, $propertyName, $propertyVa
break;
case '>':
if ($object-> {$propertyName}
if ($object->{$propertyName}
> $propertyValue)
{
$returnArray[] = $object;
@ -43,7 +42,7 @@ function FindAllObjectsInArrayByPropertyValue($array, $propertyName, $propertyVa
break;
case '<':
if ($object-> {$propertyName}
if ($object->{$propertyName}
< $propertyValue)
{
$returnArray[] = $object;
@ -51,7 +50,6 @@ function FindAllObjectsInArrayByPropertyValue($array, $propertyName, $propertyVa
break;
}
}
return $returnArray;
@ -90,7 +88,6 @@ function FindAllItemsInArrayByValue($array, $value, $operator = '==')
break;
}
}
return $returnArray;
@ -122,7 +119,6 @@ function GetClassConstants($className, $prefix = null)
$matchingKeys = preg_grep('!^' . $prefix . '!', array_keys($constants));
return array_intersect_key($constants, array_flip($matchingKeys));
}
}
function RandomString($length, $allowedChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
@ -188,17 +184,15 @@ function Setting(string $name, $value)
{
define('GROCY_' . $name, ExternalSettingValue(file_get_contents($settingOverrideFile)));
}
elseif (getenv('GROCY_' . $name) !== false) // An environment variable with the same name and prefix GROCY_ overwrites the given setting
{
elseif (getenv('GROCY_' . $name) !== false)
{ // An environment variable with the same name and prefix GROCY_ overwrites the given setting
define('GROCY_' . $name, ExternalSettingValue(getenv('GROCY_' . $name)));
}
else
{
define('GROCY_' . $name, $value);
}
}
}
global $GROCY_DEFAULT_USER_SETTINGS;
@ -211,7 +205,6 @@ function DefaultUserSetting(string $name, $value)
{
$GROCY_DEFAULT_USER_SETTINGS[$name] = $value;
}
}
function GetUserDisplayName($user)

View File

@ -17,7 +17,7 @@ class ApiKeyAuthMiddleware extends AuthMiddleware
$this->ApiKeyHeaderName = $this->AppContainer->get('ApiKeyHeaderName');
}
function authenticate(Request $request)
public function authenticate(Request $request)
{
if (!defined('GROCY_SHOW_AUTH_VIEWS'))
{
@ -33,7 +33,7 @@ class ApiKeyAuthMiddleware extends AuthMiddleware
$apiKeyService = new ApiKeyService();
// First check of the API key in the configured header
// First check of the API key in the configured header
if (!$request->hasHeader($this->ApiKeyHeaderName) || !$apiKeyService->IsValidApiKey($request->getHeaderLine($this->ApiKeyHeaderName)))
{
$validApiKey = false;
@ -43,14 +43,14 @@ class ApiKeyAuthMiddleware extends AuthMiddleware
$usedApiKey = $request->getHeaderLine($this->ApiKeyHeaderName);
}
// Not recommended, but it's also possible to provide the API key via a query parameter (same name as the configured header)
// Not recommended, but it's also possible to provide the API key via a query parameter (same name as the configured header)
if (!$validApiKey && !empty($request->getQueryParam($this->ApiKeyHeaderName)) && $apiKeyService->IsValidApiKey($request->getQueryParam($this->ApiKeyHeaderName)))
{
$validApiKey = true;
$usedApiKey = $request->getQueryParam($this->ApiKeyHeaderName);
}
// Handling of special purpose API keys
// Handling of special purpose API keys
if (!$validApiKey)
{
if ($routeName === 'calendar-ical')
@ -59,21 +59,16 @@ class ApiKeyAuthMiddleware extends AuthMiddleware
{
$validApiKey = true;
}
}
}
if ($validApiKey)
{
return $apiKeyService->GetUserByApiKey($usedApiKey);
}
else
{
return null;
}
}
}

View File

@ -30,9 +30,7 @@ abstract class AuthMiddleware extends BaseMiddleware
{
return $handler->handle($request);
}
else
if ($routeName === 'login')
elseif ($routeName === 'login')
{
define('GROCY_AUTHENTICATED', false);
return $handler->handle($request);
@ -66,7 +64,6 @@ abstract class AuthMiddleware extends BaseMiddleware
{
return $response->withHeader('Location', $this->AppContainer->get('UrlManager')->ConstructUrl('/login'));
}
}
else
{
@ -76,9 +73,7 @@ abstract class AuthMiddleware extends BaseMiddleware
return $response = $handler->handle($request);
}
}
}
/**
@ -86,5 +81,5 @@ abstract class AuthMiddleware extends BaseMiddleware
* @return mixed|null the user row or null if the request is not authenticated
* @throws \Exception Throws an \Exception if config is invalid.
*/
protected abstract function authenticate(Request $request);
abstract protected function authenticate(Request $request);
}

View File

@ -28,14 +28,13 @@ class CorsMiddleware
else
{
$response = $handler->handle($request);
}
//$routeContext = RouteContext::fromRequest($request);
//$routeContext = RouteContext::fromRequest($request);
//$routingResults = $routeContext->getRoutingResults();
//$routingResults = $routeContext->getRoutingResults();
//$methods = $routingResults->getAllowedMethods();
//$methods = $routingResults->getAllowedMethods();
//$requestHeaders = $request->getHeaderLine('Access-Control-Request-Headers');
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
@ -44,5 +43,4 @@ class CorsMiddleware
return $response;
}
}

View File

@ -22,5 +22,4 @@ class DefaultAuthMiddleware extends AuthMiddleware
$user = $auth->authenticate($request);
return $user;
}
}

View File

@ -25,7 +25,5 @@ class JsonMiddleware extends BaseMiddleware
return $response;
}
}
}

View File

@ -28,9 +28,7 @@ class LocaleMiddleware extends BaseMiddleware
{
return $locale;
}
}
}
$langs = implode(',', $request->getHeader('Accept-Language'));
@ -38,12 +36,13 @@ class LocaleMiddleware extends BaseMiddleware
// src: https://gist.github.com/spolischook/0cde9c6286415cddc088
$prefLocales = array_reduce(
explode(',', $langs),
function ($res, $el)
{
function ($res, $el) {
list($l, $q) = array_merge(explode(';q=', $el), [1]);
$res[$l] = (float) $q;
return $res;
}, []);
},
[]
);
arsort($prefLocales);
$availableLocales = scandir(__DIR__ . '/../localization');
@ -55,25 +54,23 @@ class LocaleMiddleware extends BaseMiddleware
return $locale;
}
// e.g. en_GB
// e.g. en_GB
if (in_array(substr($locale, 0, 5), $availableLocales))
{
return substr($locale, 0, 5);
}
// e.g: cs
// e.g: cs
// or en
// or en
// or de
// or de
if (in_array(substr($locale, 0, 2), $availableLocales))
{
return substr($locale, 0, 2);
}
}
return GROCY_DEFAULT_LOCALE;
}
}

View File

@ -8,7 +8,7 @@ use Psr\Http\Message\ServerRequestInterface as Request;
class ReverseProxyAuthMiddleware extends AuthMiddleware
{
function authenticate(Request $request)
public function authenticate(Request $request)
{
if (!defined('GROCY_SHOW_AUTH_VIEWS'))
{
@ -36,5 +36,4 @@ class ReverseProxyAuthMiddleware extends AuthMiddleware
return $user;
}
}

View File

@ -16,7 +16,7 @@ class SessionAuthMiddleware extends AuthMiddleware
$this->SessionCookieName = $this->AppContainer->get('LoginControllerInstance')->GetSessionCookieName();
}
function authenticate(Request $request)
public function authenticate(Request $request)
{
if (!defined('GROCY_SHOW_AUTH_VIEWS'))
{
@ -33,7 +33,5 @@ class SessionAuthMiddleware extends AuthMiddleware
{
return $sessionService->GetUserBySessionKey($_COOKIE[$this->SessionCookieName]);
}
}
}

View File

@ -4,12 +4,9 @@ use Grocy\Middleware\AuthMiddleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Routing\RouteCollectorProxy;
use Grocy\Middleware\JsonMiddleware;
$app->group('', function(RouteCollectorProxy $group)
{
$app->group('', function (RouteCollectorProxy $group) {
// System routes
$group->get('/', '\Grocy\Controllers\SystemController:Root')->setName('root');
$group->get('/about', '\Grocy\Controllers\SystemController:About');
@ -139,8 +136,7 @@ $app->group('', function(RouteCollectorProxy $group)
$group->get('/manageapikeys/new', '\Grocy\Controllers\OpenApiController:CreateNewApiKey');
});
$app->group('/api', function(RouteCollectorProxy $group)
{
$app->group('/api', function (RouteCollectorProxy $group) {
// OpenAPI
$group->get('/openapi/specification', '\Grocy\Controllers\OpenApiController:DocumentationSpec');
@ -263,7 +259,6 @@ $app->group('/api', function(RouteCollectorProxy $group)
})->add(JsonMiddleware::class);
// Handle CORS preflight OPTIONS requests
$app->options('/api/{routes:.+}', function(Request $request, Response $response): Response
{
$app->options('/api/{routes:.+}', function (Request $request, Response $response): Response {
return $response->withStatus(204);
});

View File

@ -32,7 +32,7 @@ class ApiKeyService extends BaseService
return $apiKey->id;
}
// Returns any valid key for $keyType,
// Returns any valid key for $keyType,
// not allowed for key type "default"
public function GetOrCreateApiKey($keyType)
{
@ -52,9 +52,7 @@ class ApiKeyService extends BaseService
{
return $this->CreateApiKey($keyType);
}
}
}
public function GetUserByApiKey($apiKey)
@ -84,7 +82,7 @@ class ApiKeyService extends BaseService
if ($apiKeyRow !== null)
{
// This should not change the database file modification time as this is used
// This should not change the database file modification time as this is used
// to determine if REALLY something has changed
$dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$apiKeyRow->update([
@ -98,9 +96,7 @@ class ApiKeyService extends BaseService
{
return false;
}
}
}
public function RemoveApiKey($apiKey)
@ -112,5 +108,4 @@ class ApiKeyService extends BaseService
{
return RandomString(50);
}
}

View File

@ -29,8 +29,7 @@ class ApplicationService extends BaseService
}
// Sort changelog items to have the changelog descending by newest version
usort($changelogItems, function ($a, $b)
{
usort($changelogItems, function ($a, $b) {
if ($a['release_number'] == $b['release_number'])
{
return 0;
@ -59,7 +58,6 @@ class ApplicationService extends BaseService
$this->InstalledVersion->Version = "pre-release-$commitHash";
$this->InstalledVersion->ReleaseDate = substr($commitDate, 0, 19);
}
}
return $this->InstalledVersion;
@ -77,5 +75,4 @@ class ApplicationService extends BaseService
'sqlite_version' => $sqliteVersion
];
}
}

View File

@ -61,5 +61,4 @@ class BaseService
{
return UsersService::getInstance();
}
}

View File

@ -66,5 +66,4 @@ class BatteriesService extends BaseService
$batteryRow = $this->getDatabase()->batteries()->where('id = :1', $batteryId)->fetch();
return $batteryRow !== null;
}
}

View File

@ -2,14 +2,6 @@
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\Helpers\UrlManager;
class CalendarService extends BaseService
@ -34,9 +26,7 @@ class CalendarService extends BaseService
'link' => $this->UrlManager->ConstructUrl('/stockoverview')
];
}
}
}
$taskEvents = [];
@ -54,7 +44,6 @@ class CalendarService extends BaseService
'link' => $this->UrlManager->ConstructUrl('/tasks')
];
}
}
$choreEvents = [];
@ -85,7 +74,6 @@ class CalendarService extends BaseService
'allDay' => $chore->track_date_only == 1
];
}
}
$batteryEvents = [];
@ -104,7 +92,6 @@ class CalendarService extends BaseService
'link' => $this->UrlManager->ConstructUrl('/batteriesoverview')
];
}
}
$mealPlanRecipeEvents = [];
@ -129,7 +116,6 @@ class CalendarService extends BaseService
'link' => $this->UrlManager->ConstructUrl('/recipes' . '?recipe=' . $recipeOfCurrentDay->includes_recipe_id . '#fullscreen')
];
}
}
$mealPlanDayNotes = $this->getDatabase()->meal_plan()->where('type', 'note');
@ -158,7 +144,6 @@ class CalendarService extends BaseService
'date_format' => 'date'
];
}
}
return array_merge($stockEvents, $taskEvents, $choreEvents, $batteryEvents, $mealPlanRecipeEvents, $mealPlanNotesEvents, $mealPlanProductEvents);
@ -169,5 +154,4 @@ class CalendarService extends BaseService
parent::__construct();
$this->UrlManager = new UrlManager(GROCY_BASE_URL);
}
}

View File

@ -5,23 +5,15 @@ namespace Grocy\Services;
class ChoresService extends BaseService
{
const CHORE_ASSIGNMENT_TYPE_IN_ALPHABETICAL_ORDER = 'in-alphabetical-order';
const CHORE_ASSIGNMENT_TYPE_NO_ASSIGNMENT = 'no-assignment';
const CHORE_ASSIGNMENT_TYPE_RANDOM = 'random';
const CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST = 'who-least-did-first';
const CHORE_PERIOD_TYPE_DAILY = 'daily';
const CHORE_PERIOD_TYPE_DYNAMIC_REGULAR = 'dynamic-regular';
const CHORE_PERIOD_TYPE_MANUALLY = 'manually';
const CHORE_PERIOD_TYPE_MONTHLY = 'monthly';
const CHORE_PERIOD_TYPE_WEEKLY = 'weekly';
const CHORE_PERIOD_TYPE_YEARLY = 'yearly';
public function CalculateNextExecutionAssignment($choreId)
@ -45,33 +37,29 @@ class ChoresService extends BaseService
{
$assignedUsers[] = $user;
}
}
$nextExecutionUserId = null;
if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_RANDOM)
{
// Random assignment and only 1 user in the group? Well, ok - will be hard to guess the next one...
// Random assignment and only 1 user in the group? Well, ok - will be hard to guess the next one...
if (count($assignedUsers) == 1)
{
$nextExecutionUserId = array_shift($assignedUsers)->id;
}
else
{
// Randomness in small groups will likely often result in the same user, so try it as long as this is the case
// Randomness in small groups will likely often result in the same user, so try it as long as this is the case
while ($nextExecutionUserId == null || $nextExecutionUserId == $lastDoneByUserId)
{
$nextExecutionUserId = $assignedUsers[array_rand($assignedUsers)]->id;
}
}
}
else if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_IN_ALPHABETICAL_ORDER)
{
usort($assignedUsers, function ($a, $b)
elseif ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_IN_ALPHABETICAL_ORDER)
{
usort($assignedUsers, function ($a, $b) {
return strcmp($a->display_name, $b->display_name);
});
@ -88,24 +76,21 @@ class ChoresService extends BaseService
{
$nextRoundMatches = true;
}
}
// If nothing has matched, probably it was the last user in the sorted list -> the first one is the next one
// If nothing has matched, probably it was the last user in the sorted list -> the first one is the next one
if ($nextExecutionUserId == null)
{
$nextExecutionUserId = array_shift($assignedUsers)->id;
}
}
else if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST)
elseif ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST)
{
$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;
}
}
$chore->update([
@ -217,5 +202,4 @@ class ChoresService extends BaseService
$choreRow = $this->getDatabase()->chores()->where('id = :1', $choreId)->fetch();
return $choreRow !== null;
}
}

View File

@ -24,16 +24,12 @@ class DatabaseMigrationService extends BaseService
$migrationNumber = ltrim($migrationFile->getBasename('.php'), '0');
$this->ExecutePhpMigrationWhenNeeded($migrationNumber, $migrationFile->getPathname());
}
else
if ($migrationFile->getExtension() === 'sql')
elseif ($migrationFile->getExtension() === 'sql')
{
$migrationNumber = ltrim($migrationFile->getBasename('.sql'), '0');
$this->ExecuteSqlMigrationWhenNeeded($migrationNumber, file_get_contents($migrationFile->getPathname()));
}
}
}
private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile)
@ -45,7 +41,6 @@ class DatabaseMigrationService extends BaseService
include $phpFile;
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
}
}
private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql)
@ -57,7 +52,5 @@ class DatabaseMigrationService extends BaseService
$this->getDatabaseService()->ExecuteDbStatement($sql);
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
}
}
}

View File

@ -2,8 +2,6 @@
namespace Grocy\Services;
#use \Grocy\Services\ApplicationService;
class DatabaseService
{
private static $DbConnection = null;
@ -99,5 +97,4 @@ class DatabaseService
return GROCY_DATAPATH . '/grocy.db';
}
}

View File

@ -2,8 +2,6 @@
namespace Grocy\Services;
#use \Grocy\Services\LocalizationService;
class DemoDataGeneratorService extends BaseService
{
protected $LocalizationService;
@ -311,7 +309,6 @@ class DemoDataGeneratorService extends BaseService
$this->DownloadFileIfNotAlreadyExists('https://releases.grocy.info/demoresources/chocolate_sauce.jpg', "$recipePicturesFolder/chocolate_sauce.jpg");
$this->DownloadFileIfNotAlreadyExists('https://releases.grocy.info/demoresources/pancakes_chocolate_sauce.jpg', "$recipePicturesFolder/pancakes_chocolate_sauce.jpg");
}
}
public function __construct()
@ -331,7 +328,6 @@ class DemoDataGeneratorService extends BaseService
]
])));
}
}
private function NextSupermarketId()
@ -366,5 +362,4 @@ class DemoDataGeneratorService extends BaseService
$localizedText = $this->getLocalizationService()->__t($text, null);
return str_replace("'", "''", $localizedText);
}
}

View File

@ -34,22 +34,17 @@ class FilesService extends BaseService
{
$image->resizeToBestFit($bestFitWidth, $bestFitHeight);
}
else
if ($bestFitHeight !== null)
elseif ($bestFitHeight !== null)
{
$image->resizeToHeight($bestFitHeight);
}
else
if ($bestFitWidth !== null)
elseif ($bestFitWidth !== null)
{
$image->resizeToWidth($bestFitWidth);
}
$image->save($filePathDownscaled);
}
}
catch (ImageResizeException $ex)
{
@ -81,7 +76,5 @@ class FilesService extends BaseService
{
mkdir($this->StoragePath);
}
}
}

View File

@ -2,7 +2,6 @@
namespace Grocy\Services;
#use \Grocy\Services\DatabaseService;
use Gettext\Translation;
use Gettext\Translations;
use Gettext\Translator;
@ -31,9 +30,7 @@ class LocalizationService
$this->PotMain[] = $translation;
$this->PotMain->toPoFile(__DIR__ . '/../localization/strings.pot');
}
}
}
public function GetPluralCount()
@ -46,7 +43,6 @@ class LocalizationService
{
return 2;
}
}
public function GetPluralDefinition()
@ -59,7 +55,6 @@ class LocalizationService
{
return '(n != 1)';
}
}
public function GetPoAsJsonString()
@ -93,7 +88,6 @@ class LocalizationService
{
return vsprintf($this->Translator->gettext($text), ...$placeholderValues);
}
}
public static function getInstance(string $culture)
@ -137,7 +131,6 @@ class LocalizationService
{
$this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/demo_data.pot'));
}
}
$this->PoUserStrings = new Translations();
@ -213,5 +206,4 @@ class LocalizationService
$this->Translator = new Translator();
$this->Translator->loadTranslations($this->Po);
}
}

View File

@ -2,8 +2,6 @@
namespace Grocy\Services;
#use \Grocy\Services\StockService;
use LessQL\Result;
class RecipesService extends BaseService
@ -42,11 +40,8 @@ class RecipesService extends BaseService
]);
$shoppinglistRow->save();
}
}
}
}
public function ConsumeRecipe($recipeId)
@ -65,7 +60,6 @@ class RecipesService extends BaseService
{
$this->getStockService()->ConsumeProduct($recipePosition->product_id, $recipePosition->recipe_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true);
}
}
$recipeRow = $this->getDatabase()->recipes()->where('id = :1', $recipeId)->fetch();
@ -75,7 +69,6 @@ class RecipesService extends BaseService
$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));
}
}
public function GetRecipesPosResolved()
@ -99,5 +92,4 @@ class RecipesService extends BaseService
$recipeRow = $this->getDataBase()->recipes()->where('id = :1', $recipeId)->fetch();
return $recipeRow !== null;
}
}

View File

@ -13,7 +13,7 @@ class SessionService extends BaseService
$expires = date('Y-m-d H:i:s', intval(time() + 2592000));
// Default is that sessions expire in 30 days
// 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
@ -61,7 +61,7 @@ class SessionService extends BaseService
if ($sessionRow !== null)
{
// This should not change the database file modification time as this is used
// This should not change the database file modification time as this is used
// to determine if REALLY something has changed
$dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$sessionRow->update([
@ -75,9 +75,7 @@ class SessionService extends BaseService
{
return false;
}
}
}
public function RemoveSession($sessionKey)
@ -89,5 +87,4 @@ class SessionService extends BaseService
{
return RandomString(50);
}
}

View File

@ -5,21 +5,13 @@ namespace Grocy\Services;
class StockService extends BaseService
{
const TRANSACTION_TYPE_CONSUME = 'consume';
const TRANSACTION_TYPE_INVENTORY_CORRECTION = 'inventory-correction';
const TRANSACTION_TYPE_PRODUCT_OPENED = 'product-opened';
const TRANSACTION_TYPE_PURCHASE = 'purchase';
const TRANSACTION_TYPE_SELF_PRODUCTION = 'self-production';
const TRANSACTION_TYPE_STOCK_EDIT_NEW = 'stock-edit-new';
const TRANSACTION_TYPE_STOCK_EDIT_OLD = 'stock-edit-old';
const TRANSACTION_TYPE_TRANSFER_FROM = 'transfer_from';
const TRANSACTION_TYPE_TRANSFER_TO = 'transfer_to';
public function AddMissingProductsToShoppingList($listId = 1)
@ -38,8 +30,8 @@ class StockService extends BaseService
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $missingProduct->id)->fetch();
if ($alreadyExistingEntry) // Update
{
if ($alreadyExistingEntry)
{ // Update
if ($alreadyExistingEntry->amount < $amountToAdd)
{
$alreadyExistingEntry->update([
@ -47,10 +39,9 @@ class StockService extends BaseService
'shopping_list_id' => $listId
]);
}
}
else // Insert
{
else
{ // Insert
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([
'product_id' => $missingProduct->id,
'amount' => $amountToAdd,
@ -58,9 +49,7 @@ class StockService extends BaseService
]);
$shoppinglistRow->save();
}
}
}
public function AddProduct(int $productId, float $amount, $bestBeforeDate, $transactionType, $purchasedDate, $price, $quFactorPurchaseToStock, $locationId = null, $shoppingLocationId = null, &$transactionId = null)
@ -70,9 +59,9 @@ class StockService extends BaseService
throw new \Exception('Product does not exist or is inactive');
}
// Tare weight handling
// Tare weight handling
// The given amount is the new total amount including the container weight (gross)
// The given amount is the new total amount including the container weight (gross)
// The amount to be posted needs to be the given amount - stock amount - tare weight
$productDetails = (object) $this->GetProductDetails($productId);
@ -86,14 +75,14 @@ class StockService extends BaseService
$amount = $amount - floatval($productDetails->stock_amount) - floatval($productDetails->product->tare_weight);
}
//Sets the default best before date, if none is supplied
//Sets the default best before date, if none is supplied
if ($bestBeforeDate == null)
{
if (intval($productDetails->product->default_best_before_days) == -1)
{
$bestBeforeDate = date('2999-12-31');
}
else if (intval($productDetails->product->default_best_before_days) > 0)
elseif (intval($productDetails->product->default_best_before_days) > 0)
{
$bestBeforeDate = date('Y-m-d', strtotime(date('Y-m-d') . ' + ' . $productDetails->product->default_best_before_days . ' days'));
}
@ -101,7 +90,6 @@ class StockService extends BaseService
{
$bestBeforeDate = date('Y-m-d');
}
}
if ($transactionType === self::TRANSACTION_TYPE_PURCHASE || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION || $transactionType == self::TRANSACTION_TYPE_SELF_PRODUCTION)
@ -149,7 +137,6 @@ class StockService extends BaseService
{
throw new \Exception("Transaction type $transactionType is not valid (StockService.AddProduct)");
}
}
public function AddProductToShoppingList($productId, $amount = 1, $note = null, $listId = 1)
@ -165,16 +152,16 @@ class StockService extends BaseService
}
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch();
if ($alreadyExistingEntry) // Update
{
if ($alreadyExistingEntry)
{ // Update
$alreadyExistingEntry->update([
'amount' => ($alreadyExistingEntry->amount + $amount),
'shopping_list_id' => $listId,
'note' => $note
]);
}
else // Insert
{
else
{ // Insert
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([
'product_id' => $productId,
'amount' => $amount,
@ -183,7 +170,6 @@ class StockService extends BaseService
]);
$shoppinglistRow->save();
}
}
public function ClearShoppingList($listId = 1)
@ -208,9 +194,9 @@ class StockService extends BaseService
throw new \Exception('Location does not exist');
}
// Tare weight handling
// Tare weight handling
// The given amount is the new total amount including the container weight (gross)
// The given amount is the new total amount including the container weight (gross)
// The amount to be posted needs to be the absolute value of the given amount - stock amount - tare weight
$productDetails = (object) $this->GetProductDetails($productId);
@ -226,12 +212,12 @@ class StockService extends BaseService
if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION)
{
if ($locationId === null) // Consume from any location
{
if ($locationId === null)
{ // Consume from any location
$potentialStockEntries = $this->GetProductStockEntries($productId, false, $allowSubproductSubstitution);
}
else // Consume only from the supplied location
{
else
{ // Consume only from the supplied location
$potentialStockEntries = $this->GetProductStockEntriesForLocation($productId, $locationId, false, $allowSubproductSubstitution);
}
@ -259,8 +245,8 @@ class StockService extends BaseService
break;
}
if ($amount >= $stockEntry->amount) // Take the whole stock entry
{
if ($amount >= $stockEntry->amount)
{ // Take the whole stock entry
$logRow = $this->getDatabase()->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1,
@ -281,8 +267,8 @@ class StockService extends BaseService
$amount -= $stockEntry->amount;
}
else // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount
{
else
{ // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount
$restStockAmount = $stockEntry->amount - $amount;
$logRow = $this->getDatabase()->stock_log()->createRow([
@ -307,7 +293,6 @@ class StockService extends BaseService
$amount = 0;
}
}
return $this->getDatabase()->lastInsertId();
@ -316,7 +301,6 @@ class StockService extends BaseService
{
throw new Exception("Transaction type $transactionType is not valid (StockService.ConsumeProduct)");
}
}
public function EditStockEntry(int $stockRowId, float $amount, $bestBeforeDate, $locationId, $shoppingLocationId, $price, $open, $purchasedDate, $quFactorPurchaseToStock)
@ -354,9 +338,7 @@ class StockService extends BaseService
{
$openedDate = date('Y-m-d');
}
else
if (!$open)
elseif (!$open)
{
$openedDate = null;
}
@ -399,8 +381,8 @@ class StockService extends BaseService
$plugin = $this->LoadBarcodeLookupPlugin();
$pluginOutput = $plugin->Lookup($barcode);
if ($pluginOutput !== null) // Lookup was successful
{
if ($pluginOutput !== null)
{ // Lookup was successful
if ($addFoundProduct === true)
{
// Add product to database and include new product id in output
@ -409,7 +391,6 @@ class StockService extends BaseService
$pluginOutput['id'] = $newRow->id;
}
}
return $pluginOutput;
@ -466,7 +447,6 @@ class StockService extends BaseService
{
return $this->getDatabase()->uihelper_stock_current_overview_including_opened();
}
}
public function GetExpiringProducts(int $days = 5, bool $excludeExpired = false)
@ -605,7 +585,7 @@ class StockService extends BaseService
public function GetProductStockEntries($productId, $excludeOpened = false, $allowSubproductSubstitution = false, $ordered = true)
{
// In order of next use:
// In order of next use:
// First expiring first, then first in first out
$sqlWhereProductId = 'product_id = :1';
@ -623,7 +603,9 @@ class StockService extends BaseService
}
$result = $this->getDatabase()->stock()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen, $productId);
if ($ordered)
{
return $result->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC');
}
return $result;
}
@ -662,9 +644,9 @@ class StockService extends BaseService
$shoppingLocationId = $productDetails->last_shopping_location_id;
}
// Tare weight handling
// Tare weight handling
// The given amount is the new total amount including the container weight (gross)
// The given amount is the new total amount including the container weight (gross)
// So assume that the amount in stock is the amount also including the container weight
$containerWeight = 0;
@ -677,9 +659,7 @@ class StockService extends BaseService
{
throw new \Exception('The new amount cannot equal the current stock amount');
}
else
if ($newAmount > floatval($productDetails->stock_amount) + $containerWeight)
elseif ($newAmount > floatval($productDetails->stock_amount) + $containerWeight)
{
$bookingAmount = $newAmount - floatval($productDetails->stock_amount);
@ -690,9 +670,7 @@ class StockService extends BaseService
return $this->AddProduct($productId, $bookingAmount, $bestBeforeDate, self::TRANSACTION_TYPE_INVENTORY_CORRECTION, date('Y-m-d'), $price, $locationId, $shoppingLocationId);
}
else
if ($newAmount < $productDetails->stock_amount + $containerWeight)
elseif ($newAmount < $productDetails->stock_amount + $containerWeight)
{
$bookingAmount = $productDetails->stock_amount - $newAmount;
@ -747,8 +725,8 @@ class StockService extends BaseService
$newBestBeforeDate = date('Y-m-d', strtotime('+' . $product->default_best_before_days_after_open . ' days'));
}
if ($amount >= $stockEntry->amount) // Mark the whole stock entry as opened
{
if ($amount >= $stockEntry->amount)
{ // Mark the whole stock entry as opened
$logRow = $this->getDatabase()->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount,
@ -772,8 +750,8 @@ class StockService extends BaseService
$amount -= $stockEntry->amount;
}
else // Stock entry amount is > than needed amount -> split the stock entry
{
else
{ // Stock entry amount is > than needed amount -> split the stock entry
$restStockAmount = $stockEntry->amount - $amount;
$newStockRow = $this->getDatabase()->stock()->createRow([
@ -812,7 +790,6 @@ class StockService extends BaseService
$amount = 0;
}
}
return $this->getDatabase()->lastInsertId();
@ -827,7 +804,7 @@ class StockService extends BaseService
$productRow = $this->getDatabase()->shopping_list()->where('product_id = :1', $productId)->fetch();
//If no entry was found with for this product, we return gracefully
//If no entry was found with for this product, we return gracefully
if ($productRow != null && !empty($productRow))
{
$newAmount = $productRow->amount - $amount;
@ -839,9 +816,7 @@ class StockService extends BaseService
{
$productRow->update(['amount' => $newAmount]);
}
}
}
public function TransferProduct(int $productId, float $amount, int $locationIdFrom, int $locationIdTo, $specificStockEntryId = 'default', &$transactionId = null)
@ -861,9 +836,9 @@ class StockService extends BaseService
throw new \Exception('Destination location does not exist');
}
// Tare weight handling
// Tare weight handling
// The given amount is the new total amount including the container weight (gross)
// The given amount is the new total amount including the container weight (gross)
// The amount to be posted needs to be the absolute value of the given amount - stock amount - tare weight
$productDetails = (object) $this->GetProductDetails($productId);
@ -871,7 +846,6 @@ class StockService extends BaseService
{
// Hard fail for now, as we not yet support transfering tare weight enabled products
throw new \Exception('Transfering tare weight enabled products is not yet possible');
if ($amount < floatval($productDetails->product->tare_weight))
{
throw new \Exception('The amount cannot be lower than the defined tare weight');
@ -912,23 +886,22 @@ class StockService extends BaseService
$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
// 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)
{
$newBestBeforeDate = date('Y-m-d', strtotime('+' . $productDetails->product->default_best_before_days_after_freezing . ' days'));
}
// Product was moved from a freezer to non-freezer location -> thaw
// Product was moved from a freezer to non-freezer location -> thaw
if (intval($locationFrom->is_freezer) === 1 && intval($locationTo->is_freezer) === 0 && $productDetails->product->default_best_before_days_after_thawing > 0)
{
$newBestBeforeDate = date('Y-m-d', strtotime('+' . $productDetails->product->default_best_before_days_after_thawing . ' days'));
}
}
$correlationId = uniqid();
if ($amount >= $stockEntry->amount) // Take the whole stock entry
{
if ($amount >= $stockEntry->amount)
{ // Take the whole stock entry
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1,
@ -968,8 +941,8 @@ class StockService extends BaseService
$amount -= $stockEntry->amount;
}
else // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount
{
else
{ // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount
$restStockAmount = $stockEntry->amount - $amount;
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([
@ -1026,7 +999,6 @@ class StockService extends BaseService
$amount = 0;
}
}
return $this->getDatabase()->lastInsertId();
@ -1041,7 +1013,7 @@ class StockService extends BaseService
throw new \Exception('Booking does not exist or was already undone');
}
// Undo all correlated bookings first, in order from newest first to the oldest
// Undo all correlated bookings first, in order from newest first to the oldest
if (!$skipCorrelatedBookings && !empty($logRow->correlation_id))
{
$correlatedBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll();
@ -1122,7 +1094,7 @@ class StockService extends BaseService
}
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_TRANSFER_FROM)
{
// Add corresponding amount back to stock or
// Add corresponding amount back to stock or
// create a row if missing
$stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch();
@ -1214,7 +1186,6 @@ class StockService extends BaseService
{
throw new \Exception('This booking cannot be undone');
}
}
public function UndoTransaction($transactionId)
@ -1230,7 +1201,6 @@ class StockService extends BaseService
{
$this->UndoBooking($transactionBooking->id, true);
}
}
private function LoadBarcodeLookupPlugin()
@ -1253,7 +1223,6 @@ class StockService extends BaseService
{
throw new \Exception("Plugin $pluginName was not found");
}
}
private function LocationExists($locationId)
@ -1273,5 +1242,4 @@ class StockService extends BaseService
$shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch();
return $shoppingListRow !== null;
}
}

View File

@ -46,5 +46,4 @@ class TasksService extends BaseService
$taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch();
return $taskRow !== null;
}
}

View File

@ -5,27 +5,16 @@ namespace Grocy\Services;
class UserfieldsService extends BaseService
{
const USERFIELD_TYPE_CHECKBOX = 'checkbox';
const USERFIELD_TYPE_DATE = 'date';
const USERFIELD_TYPE_DATETIME = 'datetime';
const USERFIELD_TYPE_DECIMAL_NUMBER = 'number-decimal';
const USERFIELD_TYPE_FILE = 'file';
const USERFIELD_TYPE_IMAGE = 'image';
const USERFIELD_TYPE_INTEGRAL_NUMBER = 'number-integral';
const USERFIELD_TYPE_LINK = 'link';
const USERFIELD_TYPE_PRESET_CHECKLIST = 'preset-checklist';
const USERFIELD_TYPE_PRESET_LIST = 'preset-list';
const USERFIELD_TYPE_SINGLE_LINE_TEXT = 'text-single-line';
const USERFIELD_TYPE_SINGLE_MULTILINE_TEXT = 'text-multi-line';
protected $OpenApiSpec = null;
@ -117,14 +106,14 @@ class UserfieldsService extends BaseService
$alreadyExistingEntry = $this->getDatabase()->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch();
if ($alreadyExistingEntry) // Update
{
if ($alreadyExistingEntry)
{ // Update
$alreadyExistingEntry->update([
'value' => $value
]);
}
else // Insert
{
else
{ // Insert
$newRow = $this->getDatabase()->userfield_values()->createRow([
'field_id' => $fieldId,
'object_id' => $objectId,
@ -132,9 +121,7 @@ class UserfieldsService extends BaseService
]);
$newRow->save();
}
}
}
public function __construct()
@ -156,5 +143,4 @@ class UserfieldsService extends BaseService
{
return in_array($entity, $this->GetEntities());
}
}

View File

@ -62,7 +62,6 @@ class UsersService extends BaseService
{
return null;
}
}
public function GetUserSettings($userId)
@ -106,7 +105,6 @@ class UsersService extends BaseService
]);
$settingRow->save();
}
}
private function UserExists($userId)
@ -114,5 +112,4 @@ class UsersService extends BaseService
$userRow = $this->getDatabase()->users()->where('id = :1', $userId)->fetch();
return $userRow !== null;
}
}