From 69559d648656d7dce44b66af042b615d6306d260 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Mon, 17 Feb 2025 14:41:01 +0100 Subject: [PATCH 01/17] Style fixes --- lib/AppInfo/Application.php | 32 +- lib/Controller/ObjectsController.php | 151 ++- lib/Db/Ability.php | 105 +- lib/Db/AbilityMapper.php | 102 +- lib/Db/Character.php | 187 +-- lib/Db/CharacterMapper.php | 84 +- lib/Db/Condition.php | 53 +- lib/Db/ConditionMapper.php | 84 +- lib/Db/Effect.php | 103 +- lib/Db/EffectMapper.php | 84 +- lib/Db/Event.php | 109 +- lib/Db/EventMapper.php | 84 +- lib/Db/Item.php | 97 +- lib/Db/ItemMapper.php | 84 +- lib/Db/Player.php | 157 +-- lib/Db/PlayerMapper.php | 84 +- lib/Db/Setting.php | 157 +-- lib/Db/SettingMapper.php | 84 +- lib/Db/Skill.php | 121 +- lib/Db/SkillMapper.php | 84 +- lib/Db/Template.php | 101 +- lib/Db/TemplateMapper.php | 86 +- lib/Migration/Version0Date20240826193657.php | 310 ++--- lib/Migration/Version0Date20241015141612.php | 78 +- lib/Sections/LarpingAppAdmin.php | 18 +- lib/Service/CharacterService.php | 111 +- lib/Service/ObjectService.php | 1137 +++++++++--------- lib/Service/SearchService.php | 725 ++++++----- lib/Settings/LarpingAppAdmin.php | 15 +- 29 files changed, 2348 insertions(+), 2279 deletions(-) diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index ccb5590..2c6bae1 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -14,23 +14,23 @@ */ class Application extends App implements IBootstrap { - public const APP_ID = 'larpingapp'; + public const APP_ID = 'larpingapp'; - /** - * Constructor - * - * @param array $urlParams - */ - public function __construct(array $urlParams = []) - { - parent::__construct(appName: self::APP_ID, urlParams: $urlParams); - } + /** + * Constructor + * + * @param array $urlParams + */ + public function __construct(array $urlParams = []) + { + parent::__construct(appName: self::APP_ID, urlParams: $urlParams); + } - public function register(IRegistrationContext $context): void - { - } + public function register(IRegistrationContext $context): void + { + } - public function boot(IBootContext $context): void - { - } + public function boot(IBootContext $context): void + { + } } diff --git a/lib/Controller/ObjectsController.php b/lib/Controller/ObjectsController.php index f1c12b9..e3aec11 100644 --- a/lib/Controller/ObjectsController.php +++ b/lib/Controller/ObjectsController.php @@ -16,27 +16,26 @@ class ObjectsController extends Controller { public function __construct( - $appName, - IRequest $request, - private readonly ObjectService $objectService, - private readonly CharacterService $characterService - ) - { + $appName, + IRequest $request, + private readonly ObjectService $objectService, + private readonly CharacterService $characterService + ) { parent::__construct($appName, $request); } - /** - * Return (and search) all objects - * - * @NoAdminRequired - * @NoCSRFRequired + /** + * Return (and search) all objects + * + * @NoAdminRequired + * @NoCSRFRequired * * @param string $objectType The type of object to return - * - * @return JSONResponse - */ - public function index(string $objectType): JSONResponse - { + * + * @return JSONResponse + */ + public function index(string $objectType): JSONResponse + { // Retrieve all request parameters $requestParams = $this->request->getParams(); @@ -48,18 +47,18 @@ public function index(string $objectType): JSONResponse // Return JSON response return new JSONResponse($data); - } - - /** - * Read a single object - * - * @NoAdminRequired - * @NoCSRFRequired - * - * @return JSONResponse - */ - public function show(string $objectType, string $id): JSONResponse - { + } + + /** + * Read a single object + * + * @NoAdminRequired + * @NoCSRFRequired + * + * @return JSONResponse + */ + public function show(string $objectType, string $id): JSONResponse + { try { // Get extend parameter if present $extend = $requestParams['extend'] ?? $requestParams['_extend'] ?? []; @@ -78,18 +77,18 @@ public function show(string $objectType, string $id): JSONResponse 400 ); } - } - - /** - * Create an object - * - * @NoAdminRequired - * @NoCSRFRequired - * - * @return JSONResponse - */ - public function create(string $objectType): JSONResponse - { + } + + /** + * Create an object + * + * @NoAdminRequired + * @NoCSRFRequired + * + * @return JSONResponse + */ + public function create(string $objectType): JSONResponse + { try { // Get all parameters from the request $data = $this->request->getParams(); @@ -120,18 +119,18 @@ public function create(string $objectType): JSONResponse 400 ); } - } - - /** - * Update an object - * - * @NoAdminRequired - * @NoCSRFRequired - * - * @return JSONResponse - */ - public function update(string $objectType, string $id): JSONResponse - { + } + + /** + * Update an object + * + * @NoAdminRequired + * @NoCSRFRequired + * + * @return JSONResponse + */ + public function update(string $objectType, string $id): JSONResponse + { try { // Get all parameters from the request $data = $this->request->getParams(); @@ -161,18 +160,18 @@ public function update(string $objectType, string $id): JSONResponse 400 ); } - } - - /** - * Delete an object - * - * @NoAdminRequired - * @NoCSRFRequired - * - * @return JSONResponse - */ - public function destroy(string $objectType, string $id): JSONResponse - { + } + + /** + * Delete an object + * + * @NoAdminRequired + * @NoCSRFRequired + * + * @return JSONResponse + */ + public function destroy(string $objectType, string $id): JSONResponse + { try { // Delete the object $result = $this->objectService->deleteObject($objectType, $id); @@ -185,15 +184,15 @@ public function destroy(string $objectType, string $id): JSONResponse 400 ); } - } + } - /** + /** * Get audit trail for a specific object * * @NoAdminRequired * @NoCSRFRequired - * - * @return JSONResponse + * + * @return JSONResponse */ public function getAuditTrail(string $objectType, string $id): JSONResponse { @@ -253,8 +252,8 @@ public function getUses(string $objectType, string $id): JSONResponse * @NoAdminRequired * @NoCSRFRequired * - * @param string $objectType The type of object to lock - * @param string $id The ID of the object to lock + * @param string $objectType The type of object to lock + * @param string $id The ID of the object to lock * @return JSONResponse */ public function lock(string $objectType, string $id): JSONResponse @@ -285,8 +284,8 @@ public function lock(string $objectType, string $id): JSONResponse * @NoAdminRequired * @NoCSRFRequired * - * @param string $objectType The type of object to unlock - * @param string $id The ID of the object to unlock + * @param string $objectType The type of object to unlock + * @param string $id The ID of the object to unlock * @return JSONResponse */ public function unlock(string $objectType, string $id): JSONResponse @@ -308,8 +307,8 @@ public function unlock(string $objectType, string $id): JSONResponse * @NoAdminRequired * @NoCSRFRequired * - * @param string $objectType The type of object to check - * @param string $id The ID of the object to check + * @param string $objectType The type of object to check + * @param string $id The ID of the object to check * @return JSONResponse */ public function isLocked(string $objectType, string $id): JSONResponse @@ -331,8 +330,8 @@ public function isLocked(string $objectType, string $id): JSONResponse * @NoAdminRequired * @NoCSRFRequired * - * @param string $objectType The type of object to revert - * @param string $id The ID of the object to revert + * @param string $objectType The type of object to revert + * @param string $id The ID of the object to revert * @return JSONResponse */ public function revert(string $objectType, string $id): JSONResponse diff --git a/lib/Db/Ability.php b/lib/Db/Ability.php index 62a30f7..95a20a5 100644 --- a/lib/Db/Ability.php +++ b/lib/Db/Ability.php @@ -9,66 +9,69 @@ class Ability extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?int $base = 0; - protected ?bool $allowedNegative = false; - public function __construct() { - $this->addType(fieldName: 'name', type: 'string'); - $this->addType(fieldName: 'description', type: 'string'); - $this->addType(fieldName: 'base', type: 'string'); - $this->addType(fieldName: 'allowedNegative', type: 'boolean'); + protected ?string $name = null; + protected ?string $description = null; + protected ?int $base = 0; + protected ?bool $allowedNegative = false; + public function __construct() + { + $this->addType(fieldName: 'name', type: 'string'); + $this->addType(fieldName: 'description', type: 'string'); + $this->addType(fieldName: 'base', type: 'string'); + $this->addType(fieldName: 'allowedNegative', type: 'boolean'); - } + } - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } - $method = 'set'.ucfirst($key); + $method = 'set'.ucfirst($key); - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } - return $this; - } + return $this; + } - public function jsonSerialize(): array - { - $array = [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'base' => $this->base, - 'allowedNegative' => $this->allowedNegative, - ]; + public function jsonSerialize(): array + { + $array = [ + 'id' => $this->id, + 'name' => $this->name, + 'description' => $this->description, + 'base' => $this->base, + 'allowedNegative' => $this->allowedNegative, + ]; - $jsonFields = $this->getJsonFields(); + $jsonFields = $this->getJsonFields(); - foreach ($array as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === null) { - $array[$key] = []; - } - } + foreach ($array as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === null) { + $array[$key] = []; + } + } - return $array; - } + return $array; + } } diff --git a/lib/Db/AbilityMapper.php b/lib/Db/AbilityMapper.php index bb9b0ef..a3c25aa 100644 --- a/lib/Db/AbilityMapper.php +++ b/lib/Db/AbilityMapper.php @@ -10,50 +10,50 @@ class AbilityMapper extends QBMapper { - /** - * The name of the database table for abilities - * - * @var string - * @psalm-var string - * @phpstan-var string - */ - private const TABLE_NAME = 'larpingapp_abilities'; - - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_abilities'); - } + /** + * The name of the database table for abilities + * + * @var string + * @psalm-var string + * @phpstan-var string + */ + private const TABLE_NAME = 'larpingapp_abilities'; + + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_abilities'); + } - public function find(int $id): Ability - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Ability + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_abilities') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_abilities') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_abilities') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_abilities') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -63,21 +63,21 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Ability - { - $ability = new Ability(); - $ability->hydrate(object: $object); - return $this->insert(entity: $ability); - } + public function createFromArray(array $object): Ability + { + $ability = new Ability(); + $ability->hydrate(object: $object); + return $this->insert(entity: $ability); + } - public function updateFromArray(int $id, array $object): Ability - { - $ability = $this->find($id); - $ability->hydrate($object); + public function updateFromArray(int $id, array $object): Ability + { + $ability = $this->find($id); + $ability->hydrate($object); - return $this->update($ability); - } + return $this->update($ability); + } } diff --git a/lib/Db/Character.php b/lib/Db/Character.php index c3039c6..3b3e079 100644 --- a/lib/Db/Character.php +++ b/lib/Db/Character.php @@ -8,104 +8,107 @@ class Character extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $ocName = null; - protected ?string $description = null; - protected ?string $background = null; - protected ?string $itemsAndMoney = null; - protected ?string $notice = null; - protected ?string $faith = null; - protected ?string $slNotesPublic = null; - protected ?string $slNotesPrivate = null; - protected ?string $card = null; - protected ?array $stats = []; - protected ?int $gold = null; - protected ?int $silver = null; - protected ?int $copper = null; - protected ?array $events = []; - protected ?array $skills = []; - protected ?array $items = []; - protected ?array $conditions = null; - protected ?string $type = 'player'; - protected ?string $approved = 'no'; + protected ?string $name = null; + protected ?string $ocName = null; + protected ?string $description = null; + protected ?string $background = null; + protected ?string $itemsAndMoney = null; + protected ?string $notice = null; + protected ?string $faith = null; + protected ?string $slNotesPublic = null; + protected ?string $slNotesPrivate = null; + protected ?string $card = null; + protected ?array $stats = []; + protected ?int $gold = null; + protected ?int $silver = null; + protected ?int $copper = null; + protected ?array $events = []; + protected ?array $skills = []; + protected ?array $items = []; + protected ?array $conditions = null; + protected ?string $type = 'player'; + protected ?string $approved = 'no'; - public function __construct() { - $this->addType('name', 'string'); - $this->addType('ocName', 'string'); - $this->addType('description', 'string'); - $this->addType('background', 'string'); - $this->addType('itemsAndMoney', 'string'); - $this->addType('notice', 'string'); - $this->addType('faith', 'string'); - $this->addType('slNotesPublic', 'string'); - $this->addType('slNotesPrivate', 'string'); - $this->addType('card', 'string'); - $this->addType('stats', 'json'); - $this->addType('gold', 'integer'); - $this->addType('silver', 'integer'); - $this->addType('copper', 'integer'); - $this->addType('events', 'json'); - $this->addType('skills', 'json'); - $this->addType('items', 'json'); - $this->addType('conditions', 'json'); - $this->addType('type', 'string'); - $this->addType('approved', 'string'); - } + public function __construct() + { + $this->addType('name', 'string'); + $this->addType('ocName', 'string'); + $this->addType('description', 'string'); + $this->addType('background', 'string'); + $this->addType('itemsAndMoney', 'string'); + $this->addType('notice', 'string'); + $this->addType('faith', 'string'); + $this->addType('slNotesPublic', 'string'); + $this->addType('slNotesPrivate', 'string'); + $this->addType('card', 'string'); + $this->addType('stats', 'json'); + $this->addType('gold', 'integer'); + $this->addType('silver', 'integer'); + $this->addType('copper', 'integer'); + $this->addType('events', 'json'); + $this->addType('skills', 'json'); + $this->addType('items', 'json'); + $this->addType('conditions', 'json'); + $this->addType('type', 'string'); + $this->addType('approved', 'string'); + } - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } - $method = 'set'.ucfirst($key); + $method = 'set'.ucfirst($key); - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } - return $this; - } + return $this; + } - public function jsonSerialize(): array - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'ocName' => $this->ocName, - 'description' => $this->description, - 'background' => $this->background, - 'itemsAndMoney' => $this->itemsAndMoney, - 'notice' => $this->notice, - 'faith' => $this->faith, - 'slNotesPublic' => $this->slNotesPublic, - 'slNotesPrivate' => $this->slNotesPrivate, - 'card' => $this->card, - 'stats' => $this->stats, - 'gold' => $this->gold, - 'silver' => $this->silver, - 'copper' => $this->copper, - 'events' => $this->events, - 'skills' => $this->skills, - 'items' => $this->items, - 'conditions' => $this->conditions, - 'type' => $this->type, - 'approved' => $this->approved, - ]; - } + public function jsonSerialize(): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'ocName' => $this->ocName, + 'description' => $this->description, + 'background' => $this->background, + 'itemsAndMoney' => $this->itemsAndMoney, + 'notice' => $this->notice, + 'faith' => $this->faith, + 'slNotesPublic' => $this->slNotesPublic, + 'slNotesPrivate' => $this->slNotesPrivate, + 'card' => $this->card, + 'stats' => $this->stats, + 'gold' => $this->gold, + 'silver' => $this->silver, + 'copper' => $this->copper, + 'events' => $this->events, + 'skills' => $this->skills, + 'items' => $this->items, + 'conditions' => $this->conditions, + 'type' => $this->type, + 'approved' => $this->approved, + ]; + } } diff --git a/lib/Db/CharacterMapper.php b/lib/Db/CharacterMapper.php index 94532a1..8a5a8e4 100644 --- a/lib/Db/CharacterMapper.php +++ b/lib/Db/CharacterMapper.php @@ -10,41 +10,41 @@ class CharacterMapper extends QBMapper { - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_characters'); - } + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_characters'); + } - public function find(int $id): Character - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Character + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_characters') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_characters') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_characters') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_characters') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -54,21 +54,21 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Character - { - $character = new Character(); - $character->hydrate(object: $object); - return $this->insert(entity: $character); - } + public function createFromArray(array $object): Character + { + $character = new Character(); + $character->hydrate(object: $object); + return $this->insert(entity: $character); + } - public function updateFromArray(int $id, array $object): Character - { - $character = $this->find($id); - $character->hydrate($object); + public function updateFromArray(int $id, array $object): Character + { + $character = $this->find($id); + $character->hydrate($object); - return $this->update($character); - } + return $this->update($character); + } } diff --git a/lib/Db/Condition.php b/lib/Db/Condition.php index 72870ce..5156b73 100644 --- a/lib/Db/Condition.php +++ b/lib/Db/Condition.php @@ -14,7 +14,8 @@ class Condition extends Entity implements JsonSerializable protected ?array $effects = []; protected ?bool $unique = false; - public function __construct() { + public function __construct() + { $this->addType('name', 'string'); $this->addType('description', 'string'); $this->addType('effect', 'string'); @@ -22,35 +23,37 @@ public function __construct() { $this->addType('unique', 'boolean'); } - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } - $method = 'set'.ucfirst($key); + $method = 'set'.ucfirst($key); - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } - return $this; - } + return $this; + } public function jsonSerialize(): array { diff --git a/lib/Db/ConditionMapper.php b/lib/Db/ConditionMapper.php index 8e8c1f2..99f4251 100644 --- a/lib/Db/ConditionMapper.php +++ b/lib/Db/ConditionMapper.php @@ -10,41 +10,41 @@ class ConditionMapper extends QBMapper { - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_conditions'); - } + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_conditions'); + } - public function find(int $id): Condition - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Condition + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_conditions') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_conditions') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_conditions') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_conditions') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -54,21 +54,21 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Condition - { - $condition = new Condition(); - $condition->hydrate(object: $object); - return $this->insert(entity: $condition); - } + public function createFromArray(array $object): Condition + { + $condition = new Condition(); + $condition->hydrate(object: $object); + return $this->insert(entity: $condition); + } - public function updateFromArray(int $id, array $object): Condition - { - $condition = $this->find($id); - $condition->hydrate($object); + public function updateFromArray(int $id, array $object): Condition + { + $condition = $this->find($id); + $condition->hydrate($object); - return $this->update($condition); - } + return $this->update($condition); + } } diff --git a/lib/Db/Effect.php b/lib/Db/Effect.php index 1774e54..bf68f13 100644 --- a/lib/Db/Effect.php +++ b/lib/Db/Effect.php @@ -8,62 +8,65 @@ class Effect extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?string $statId = null; - protected ?int $modifier = null; - protected ?string $modification = 'positive'; - protected ?string $cumulative = 'non-cumulative'; + protected ?string $name = null; + protected ?string $description = null; + protected ?string $statId = null; + protected ?int $modifier = null; + protected ?string $modification = 'positive'; + protected ?string $cumulative = 'non-cumulative'; - public function __construct() { - $this->addType('name', 'string'); - $this->addType('description', 'string'); - $this->addType('statId', 'string'); - $this->addType('modifier', 'integer'); - $this->addType('modification', 'string'); - $this->addType('cumulative', 'string'); - } + public function __construct() + { + $this->addType('name', 'string'); + $this->addType('description', 'string'); + $this->addType('statId', 'string'); + $this->addType('modifier', 'integer'); + $this->addType('modification', 'string'); + $this->addType('cumulative', 'string'); + } - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } - $method = 'set'.ucfirst($key); + $method = 'set'.ucfirst($key); - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } - return $this; - } + return $this; + } - public function jsonSerialize(): array - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'statId' => $this->statId, - 'modifier' => $this->modifier, - 'modification' => $this->modification, - 'cumulative' => $this->cumulative, - ]; - } + public function jsonSerialize(): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'description' => $this->description, + 'statId' => $this->statId, + 'modifier' => $this->modifier, + 'modification' => $this->modification, + 'cumulative' => $this->cumulative, + ]; + } } \ No newline at end of file diff --git a/lib/Db/EffectMapper.php b/lib/Db/EffectMapper.php index 566234e..beca6c0 100644 --- a/lib/Db/EffectMapper.php +++ b/lib/Db/EffectMapper.php @@ -10,41 +10,41 @@ class EffectMapper extends QBMapper { - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_effects'); - } + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_effects'); + } - public function find(int $id): Effect - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Effect + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_effects') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_effects') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_effects') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_effects') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -54,21 +54,21 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Effect - { - $effect = new Effect(); - $effect->hydrate(object: $object); - return $this->insert(entity: $effect); - } + public function createFromArray(array $object): Effect + { + $effect = new Effect(); + $effect->hydrate(object: $object); + return $this->insert(entity: $effect); + } - public function updateFromArray(int $id, array $object): Effect - { - $effect = $this->find($id); - $effect->hydrate($object); + public function updateFromArray(int $id, array $object): Effect + { + $effect = $this->find($id); + $effect->hydrate($object); - return $this->update($effect); - } + return $this->update($effect); + } } diff --git a/lib/Db/Event.php b/lib/Db/Event.php index ed19ed9..0f8fe2a 100644 --- a/lib/Db/Event.php +++ b/lib/Db/Event.php @@ -8,65 +8,68 @@ class Event extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?array $players = []; - protected ?array $effects = []; - protected ?string $startDate = null; - protected ?string $endDate = null; - protected ?string $location = null; + protected ?string $name = null; + protected ?string $description = null; + protected ?array $players = []; + protected ?array $effects = []; + protected ?string $startDate = null; + protected ?string $endDate = null; + protected ?string $location = null; - public function __construct() { - $this->addType('name', 'string'); - $this->addType('description', 'string'); - $this->addType('players', 'array'); - $this->addType('effects', 'json'); - $this->addType('startDate', 'string'); - $this->addType('endDate', 'string'); - $this->addType('location', 'string'); - } + public function __construct() + { + $this->addType('name', 'string'); + $this->addType('description', 'string'); + $this->addType('players', 'array'); + $this->addType('effects', 'json'); + $this->addType('startDate', 'string'); + $this->addType('endDate', 'string'); + $this->addType('location', 'string'); + } - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } - $method = 'set'.ucfirst($key); + $method = 'set'.ucfirst($key); - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } - return $this; - } + return $this; + } - public function jsonSerialize(): array - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'players' => $this->players, - 'effects' => $this->effects, - 'startDate' => $this->startDate, - 'endDate' => $this->endDate, - 'location' => $this->location, - ]; - } + public function jsonSerialize(): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'description' => $this->description, + 'players' => $this->players, + 'effects' => $this->effects, + 'startDate' => $this->startDate, + 'endDate' => $this->endDate, + 'location' => $this->location, + ]; + } } \ No newline at end of file diff --git a/lib/Db/EventMapper.php b/lib/Db/EventMapper.php index 9adb7ba..4e6e243 100644 --- a/lib/Db/EventMapper.php +++ b/lib/Db/EventMapper.php @@ -10,41 +10,41 @@ class EventMapper extends QBMapper { - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_events'); - } + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_events'); + } - public function find(int $id): Event - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Event + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_events') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_events') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_events') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_events') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -54,21 +54,21 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Event - { - $event = new Event(); - $event->hydrate(object: $object); - return $this->insert(entity: $event); - } + public function createFromArray(array $object): Event + { + $event = new Event(); + $event->hydrate(object: $object); + return $this->insert(entity: $event); + } - public function updateFromArray(int $id, array $object): Event - { - $event = $this->find($id); - $event->hydrate($object); + public function updateFromArray(int $id, array $object): Event + { + $event = $this->find($id); + $event->hydrate($object); - return $this->update($event); - } + return $this->update($event); + } } diff --git a/lib/Db/Item.php b/lib/Db/Item.php index 3fda657..fede777 100644 --- a/lib/Db/Item.php +++ b/lib/Db/Item.php @@ -8,59 +8,62 @@ class Item extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?string $effect = null; - protected ?array $effects = null; - protected ?bool $unique = true; + protected ?string $name = null; + protected ?string $description = null; + protected ?string $effect = null; + protected ?array $effects = null; + protected ?bool $unique = true; - public function __construct() { - $this->addType('name', 'string'); - $this->addType('description', 'string'); - $this->addType('effect', 'string'); - $this->addType('effects', 'json'); - $this->addType('unique', 'boolean'); - } + public function __construct() + { + $this->addType('name', 'string'); + $this->addType('description', 'string'); + $this->addType('effect', 'string'); + $this->addType('effects', 'json'); + $this->addType('unique', 'boolean'); + } - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } - $method = 'set'.ucfirst($key); + $method = 'set'.ucfirst($key); - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } - return $this; - } + return $this; + } - public function jsonSerialize(): array - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'effect' => $this->effect, - 'effects' => $this->effects, - 'unique' => $this->unique, - ]; - } + public function jsonSerialize(): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'description' => $this->description, + 'effect' => $this->effect, + 'effects' => $this->effects, + 'unique' => $this->unique, + ]; + } } \ No newline at end of file diff --git a/lib/Db/ItemMapper.php b/lib/Db/ItemMapper.php index 62fcde8..e7f0b90 100644 --- a/lib/Db/ItemMapper.php +++ b/lib/Db/ItemMapper.php @@ -10,41 +10,41 @@ class ItemMapper extends QBMapper { - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_items'); - } + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_items'); + } - public function find(int $id): Item - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Item + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_items') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_items') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_items') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_items') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -54,21 +54,21 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Item - { - $item = new Item(); - $item->hydrate(object: $object); - return $this->insert(entity: $item); - } + public function createFromArray(array $object): Item + { + $item = new Item(); + $item->hydrate(object: $object); + return $this->insert(entity: $item); + } - public function updateFromArray(int $id, array $object): Item - { - $item = $this->find($id); - $item->hydrate($object); + public function updateFromArray(int $id, array $object): Item + { + $item = $this->find($id); + $item->hydrate($object); - return $this->update($item); - } + return $this->update($item); + } } diff --git a/lib/Db/Player.php b/lib/Db/Player.php index 9e97da5..43de612 100644 --- a/lib/Db/Player.php +++ b/lib/Db/Player.php @@ -9,81 +9,84 @@ class Player extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $summary = null; - protected ?string $description = null; - protected ?string $image = null; - protected ?string $search = null; - - protected bool $listed = false; - protected ?string $organisation = null; - protected ?array $metadata = null; - - public function __construct() { - $this->addType(fieldName: 'name', type: 'string'); - $this->addType(fieldName: 'summary', type: 'string'); - $this->addType(fieldName: 'description', type: 'string'); - $this->addType(fieldName: 'image', type: 'string'); - $this->addType(fieldName: 'search', type: 'string'); - $this->addType(fieldName: 'listed', type: 'boolean'); - $this->addType(fieldName: 'organisation', type: 'string'); - $this->addType(fieldName: 'metadata', type: 'json'); - - } - - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } - - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } - - return $this; - } - - public function jsonSerialize(): array - { - $array = [ - 'id' => $this->id, - 'name' => $this->name, - 'summary' => $this->summary, - 'description' => $this->description, - 'image' => $this->image, - 'search' => $this->search, - 'listed' => $this->listed, - 'metadata' => $this->metadata, - 'organisation'=> $this->organisation, - - ]; - - $jsonFields = $this->getJsonFields(); - - foreach ($array as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === null) { - $array[$key] = []; - } - } - - return $array; - } + protected ?string $name = null; + protected ?string $summary = null; + protected ?string $description = null; + protected ?string $image = null; + protected ?string $search = null; + + protected bool $listed = false; + protected ?string $organisation = null; + protected ?array $metadata = null; + + public function __construct() + { + $this->addType(fieldName: 'name', type: 'string'); + $this->addType(fieldName: 'summary', type: 'string'); + $this->addType(fieldName: 'description', type: 'string'); + $this->addType(fieldName: 'image', type: 'string'); + $this->addType(fieldName: 'search', type: 'string'); + $this->addType(fieldName: 'listed', type: 'boolean'); + $this->addType(fieldName: 'organisation', type: 'string'); + $this->addType(fieldName: 'metadata', type: 'json'); + + } + + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } + + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); + + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } + + $method = 'set'.ucfirst($key); + + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } + + return $this; + } + + public function jsonSerialize(): array + { + $array = [ + 'id' => $this->id, + 'name' => $this->name, + 'summary' => $this->summary, + 'description' => $this->description, + 'image' => $this->image, + 'search' => $this->search, + 'listed' => $this->listed, + 'metadata' => $this->metadata, + 'organisation'=> $this->organisation, + + ]; + + $jsonFields = $this->getJsonFields(); + + foreach ($array as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === null) { + $array[$key] = []; + } + } + + return $array; + } } diff --git a/lib/Db/PlayerMapper.php b/lib/Db/PlayerMapper.php index 96ec91c..7855e64 100644 --- a/lib/Db/PlayerMapper.php +++ b/lib/Db/PlayerMapper.php @@ -10,41 +10,41 @@ class PlayerMapper extends QBMapper { - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_players'); - } + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_players'); + } - public function find(int $id): Player - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Player + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_players') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_players') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_players') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_players') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -54,21 +54,21 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Player - { - $player = new Player(); - $player->hydrate(object: $object); - return $this->insert(entity: $player); - } + public function createFromArray(array $object): Player + { + $player = new Player(); + $player->hydrate(object: $object); + return $this->insert(entity: $player); + } - public function updateFromArray(int $id, array $object): Player - { - $player = $this->find($id); - $player->hydrate($object); + public function updateFromArray(int $id, array $object): Player + { + $player = $this->find($id); + $player->hydrate($object); - return $this->update($player); - } + return $this->update($player); + } } diff --git a/lib/Db/Setting.php b/lib/Db/Setting.php index 3cd4e1d..48bec93 100644 --- a/lib/Db/Setting.php +++ b/lib/Db/Setting.php @@ -9,81 +9,84 @@ class Setting extends Entity implements JsonSerializable { - protected ?string $title = null; - protected ?string $summary = null; - protected ?string $description = null; - protected ?string $image = null; - protected ?string $search = null; - - protected bool $listed = false; - protected ?string $organisation = null; - protected ?array $metadata = null; - - public function __construct() { - $this->addType(fieldName: 'title', type: 'string'); - $this->addType(fieldName: 'summary', type: 'string'); - $this->addType(fieldName: 'description', type: 'string'); - $this->addType(fieldName: 'image', type: 'string'); - $this->addType(fieldName: 'search', type: 'string'); - $this->addType(fieldName: 'listed', type: 'boolean'); - $this->addType(fieldName: 'organisation', type: 'string'); - $this->addType(fieldName: 'metadata', type: 'json'); - - } - - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } - - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } - - return $this; - } - - public function jsonSerialize(): array - { - $array = [ - 'id' => $this->id, - 'title' => $this->title, - 'summary' => $this->summary, - 'description' => $this->description, - 'image' => $this->image, - 'search' => $this->search, - 'listed' => $this->listed, - 'metadata' => $this->metadata, - 'organisation'=> $this->organisation, - - ]; - - $jsonFields = $this->getJsonFields(); - - foreach ($array as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === null) { - $array[$key] = []; - } - } - - return $array; - } + protected ?string $title = null; + protected ?string $summary = null; + protected ?string $description = null; + protected ?string $image = null; + protected ?string $search = null; + + protected bool $listed = false; + protected ?string $organisation = null; + protected ?array $metadata = null; + + public function __construct() + { + $this->addType(fieldName: 'title', type: 'string'); + $this->addType(fieldName: 'summary', type: 'string'); + $this->addType(fieldName: 'description', type: 'string'); + $this->addType(fieldName: 'image', type: 'string'); + $this->addType(fieldName: 'search', type: 'string'); + $this->addType(fieldName: 'listed', type: 'boolean'); + $this->addType(fieldName: 'organisation', type: 'string'); + $this->addType(fieldName: 'metadata', type: 'json'); + + } + + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } + + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); + + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } + + $method = 'set'.ucfirst($key); + + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } + + return $this; + } + + public function jsonSerialize(): array + { + $array = [ + 'id' => $this->id, + 'title' => $this->title, + 'summary' => $this->summary, + 'description' => $this->description, + 'image' => $this->image, + 'search' => $this->search, + 'listed' => $this->listed, + 'metadata' => $this->metadata, + 'organisation'=> $this->organisation, + + ]; + + $jsonFields = $this->getJsonFields(); + + foreach ($array as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === null) { + $array[$key] = []; + } + } + + return $array; + } } diff --git a/lib/Db/SettingMapper.php b/lib/Db/SettingMapper.php index 92c1dcd..f6aafc0 100644 --- a/lib/Db/SettingMapper.php +++ b/lib/Db/SettingMapper.php @@ -10,41 +10,41 @@ class SettingMapper extends QBMapper { - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_settings'); - } + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_settings'); + } - public function find(int $id): Setting - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Setting + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_settings') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_settings') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_settings') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_settings') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -54,21 +54,21 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Setting - { - $setting = new Setting(); - $setting->hydrate(object: $object); - return $this->insert(entity: $setting); - } + public function createFromArray(array $object): Setting + { + $setting = new Setting(); + $setting->hydrate(object: $object); + return $this->insert(entity: $setting); + } - public function updateFromArray(int $id, array $object): Setting - { - $setting = $this->find($id); - $setting->hydrate($object); + public function updateFromArray(int $id, array $object): Setting + { + $setting = $this->find($id); + $setting->hydrate($object); - return $this->update($setting); - } + return $this->update($setting); + } } diff --git a/lib/Db/Skill.php b/lib/Db/Skill.php index 8c025bc..848d27a 100644 --- a/lib/Db/Skill.php +++ b/lib/Db/Skill.php @@ -8,71 +8,74 @@ class Skill extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?string $effect = null; - protected ?array $effects = null; - protected ?array $requiredSkills = []; - protected ?array $requiredStats = []; - protected ?array $requiredConditions = []; - protected ?array $requiredEffects = []; - protected ?int $requiredScore = null; + protected ?string $name = null; + protected ?string $description = null; + protected ?string $effect = null; + protected ?array $effects = null; + protected ?array $requiredSkills = []; + protected ?array $requiredStats = []; + protected ?array $requiredConditions = []; + protected ?array $requiredEffects = []; + protected ?int $requiredScore = null; - public function __construct() { - $this->addType('name', 'string'); - $this->addType('description', 'string'); - $this->addType('effect', 'string'); - $this->addType('effects', 'json'); - $this->addType('requiredSkills', 'json'); - $this->addType('requiredStats', 'json'); - $this->addType('requiredConditions', 'json'); - $this->addType('requiredEffects', 'json'); - $this->addType('requiredScore', 'integer'); - } + public function __construct() + { + $this->addType('name', 'string'); + $this->addType('description', 'string'); + $this->addType('effect', 'string'); + $this->addType('effects', 'json'); + $this->addType('requiredSkills', 'json'); + $this->addType('requiredStats', 'json'); + $this->addType('requiredConditions', 'json'); + $this->addType('requiredEffects', 'json'); + $this->addType('requiredScore', 'integer'); + } - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } - $method = 'set'.ucfirst($key); + $method = 'set'.ucfirst($key); - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } - return $this; - } + return $this; + } - public function jsonSerialize(): array - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'effect' => $this->effect, - 'effects' => $this->effects, - 'requiredSkills' => $this->requiredSkills, - 'requiredStats' => $this->requiredStats, - 'requiredConditions' => $this->requiredConditions, - 'requiredEffects' => $this->requiredEffects, - 'requiredScore' => $this->requiredScore, - ]; - } + public function jsonSerialize(): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'description' => $this->description, + 'effect' => $this->effect, + 'effects' => $this->effects, + 'requiredSkills' => $this->requiredSkills, + 'requiredStats' => $this->requiredStats, + 'requiredConditions' => $this->requiredConditions, + 'requiredEffects' => $this->requiredEffects, + 'requiredScore' => $this->requiredScore, + ]; + } } \ No newline at end of file diff --git a/lib/Db/SkillMapper.php b/lib/Db/SkillMapper.php index 20b2f4e..905d9a1 100644 --- a/lib/Db/SkillMapper.php +++ b/lib/Db/SkillMapper.php @@ -10,41 +10,41 @@ class SkillMapper extends QBMapper { - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_skills'); - } + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_skills'); + } - public function find(int $id): Skill - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Skill + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_skills') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_skills') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_skills') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_skills') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -54,21 +54,21 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Skill - { - $skill = new Skill(); - $skill->hydrate(object: $object); - return $this->insert(entity: $skill); - } + public function createFromArray(array $object): Skill + { + $skill = new Skill(); + $skill->hydrate(object: $object); + return $this->insert(entity: $skill); + } - public function updateFromArray(int $id, array $object): Skill - { - $skill = $this->find($id); - $skill->hydrate($object); + public function updateFromArray(int $id, array $object): Skill + { + $skill = $this->find($id); + $skill->hydrate($object); - return $this->update($skill); - } + return $this->update($skill); + } } diff --git a/lib/Db/Template.php b/lib/Db/Template.php index fef383c..97cb28e 100644 --- a/lib/Db/Template.php +++ b/lib/Db/Template.php @@ -8,53 +8,56 @@ class Template extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?string $template = null; - - public function __construct() { - $this->addType('name', 'string'); - $this->addType('description', 'string'); - $this->addType('template', 'string'); - } - - public function getJsonFields(): array - { - return array_keys( - array_filter($this->getFieldTypes(), function ($field) { - return $field === 'json'; - }) - ); - } - - public function hydrate(array $object): self - { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { -// ("Error writing $key"); - } - } - - return $this; - } - - public function jsonSerialize(): array - { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'template' => $this->template, - ]; - } + protected ?string $name = null; + protected ?string $description = null; + protected ?string $template = null; + + public function __construct() + { + $this->addType('name', 'string'); + $this->addType('description', 'string'); + $this->addType('template', 'string'); + } + + public function getJsonFields(): array + { + return array_keys( + array_filter( + $this->getFieldTypes(), function ($field) { + return $field === 'json'; + } + ) + ); + } + + public function hydrate(array $object): self + { + $jsonFields = $this->getJsonFields(); + + foreach($object as $key => $value) { + if (in_array($key, $jsonFields) === true && $value === []) { + $value = []; + } + + $method = 'set'.ucfirst($key); + + try { + $this->$method($value); + } catch (\Exception $exception) { + // ("Error writing $key"); + } + } + + return $this; + } + + public function jsonSerialize(): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'description' => $this->description, + 'template' => $this->template, + ]; + } } \ No newline at end of file diff --git a/lib/Db/TemplateMapper.php b/lib/Db/TemplateMapper.php index ae15588..bf1ea4e 100644 --- a/lib/Db/TemplateMapper.php +++ b/lib/Db/TemplateMapper.php @@ -10,41 +10,41 @@ class TemplateMapper extends QBMapper { - public function __construct(IDBConnection $db) - { - parent::__construct($db, 'larpingapp_templates'); - } + public function __construct(IDBConnection $db) + { + parent::__construct($db, 'larpingapp_templates'); + } - public function find(int $id): Template - { - $qb = $this->db->getQueryBuilder(); + public function find(int $id): Template + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_templates') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); + $qb->select('*') + ->from('larpingapp_templates') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) + ); - return $this->findEntity(query: $qb); - } + return $this->findEntity(query: $qb); + } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array - { - $qb = $this->db->getQueryBuilder(); + public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + { + $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_templates') - ->setMaxResults($limit) - ->setFirstResult($offset); + $qb->select('*') + ->from('larpingapp_templates') + ->setMaxResults($limit) + ->setFirstResult($offset); foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } + if ($value === 'IS NOT NULL') { + $qb->andWhere($qb->expr()->isNotNull($filter)); + } elseif ($value === 'IS NULL') { + $qb->andWhere($qb->expr()->isNull($filter)); + } else { + $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); + } } if (!empty($searchConditions)) { @@ -54,24 +54,24 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters } } - return $this->findEntities(query: $qb); - } + return $this->findEntities(query: $qb); + } - public function createFromArray(array $object): Template - { - $template = new Template(); - $template->hydrate(object: $object); + public function createFromArray(array $object): Template + { + $template = new Template(); + $template->hydrate(object: $object); -// var_dump($catalog->getTitle()); + // var_dump($catalog->getTitle()); - return $this->insert(entity: $template); - } + return $this->insert(entity: $template); + } - public function updateFromArray(int $id, array $object): Template - { - $template = $this->find($id); - $template->hydrate($object); + public function updateFromArray(int $id, array $object): Template + { + $template = $this->find($id); + $template->hydrate($object); - return $this->update($template); - } + return $this->update($template); + } } diff --git a/lib/Migration/Version0Date20240826193657.php b/lib/Migration/Version0Date20240826193657.php index 9a57e83..5a8f827 100644 --- a/lib/Migration/Version0Date20240826193657.php +++ b/lib/Migration/Version0Date20240826193657.php @@ -19,157 +19,161 @@ /** * FIXME Auto-generated migration step: Please modify to your needs! */ -class Version0Date20240826193657 extends SimpleMigrationStep { - - /** - * @param IOutput $output - * @param Closure(): ISchemaWrapper $schemaClosure - * @param array $options - */ - public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void { - } - - /** - * @param IOutput $output - * @param Closure(): ISchemaWrapper $schemaClosure - * @param array $options - * @return null|ISchemaWrapper - */ - public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { - /** - * @var ISchemaWrapper $schema - */ - $schema = $schemaClosure(); - - if (!$schema->hasTable('larpingapp_abilities')) { - $table = $schema->createTable('larpingapp_abilities'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->setPrimaryKey(['id']); - } - - if (!$schema->hasTable('larpingapp_settings')) { - $table = $schema->createTable('larpingapp_settings'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->setPrimaryKey(['id']); - } - - if (!$schema->hasTable('larpingapp_players')) { - $table = $schema->createTable('larpingapp_players'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->setPrimaryKey(['id']); - } - - if (!$schema->hasTable('larpingapp_characters')) { - $table = $schema->createTable('larpingapp_characters'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('oc_name', Types::STRING, ['notnull' => false, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->addColumn('background', Types::TEXT, ['notnull' => false]); - $table->addColumn('items_and_money', Types::TEXT, ['notnull' => false]); - $table->addColumn('notice', Types::TEXT, ['notnull' => false]); - $table->addColumn('faith', Types::STRING, ['notnull' => false, 'length' => 255]); - $table->addColumn('sl_notes_public', Types::TEXT, ['notnull' => false]); - $table->addColumn('sl_notes_private', Types::TEXT, ['notnull' => false]); - $table->addColumn('card', Types::STRING, ['notnull' => false, 'length' => 255]); - $table->addColumn('stats', Types::JSON, ['notnull' => false]); - $table->addColumn('gold', Types::INTEGER, ['notnull' => false]); - $table->addColumn('silver', Types::INTEGER, ['notnull' => false]); - $table->addColumn('copper', Types::INTEGER, ['notnull' => false]); - $table->addColumn('events', Types::JSON, ['notnull' => false]); - $table->addColumn('skills', Types::JSON, ['notnull' => false]); - $table->addColumn('items', Types::JSON, ['notnull' => false]); - $table->addColumn('conditions', Types::JSON, ['notnull' => false]); - $table->addColumn('type', Types::STRING, ['notnull' => true, 'length' => 50, 'default' => 'player']); - $table->addColumn('approved', Types::STRING, ['notnull' => false, 'length' => 50]); - $table->setPrimaryKey(['id']); - } - - if (!$schema->hasTable('larpingapp_conditions')) { - $table = $schema->createTable('larpingapp_conditions'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->addColumn('effect', Types::TEXT, ['notnull' => false]); - $table->addColumn('effects', Types::JSON, ['notnull' => false]); - $table->addColumn('unique', Types::BOOLEAN, ['notnull' => true, 'default' => false]); - $table->setPrimaryKey(['id']); - } - - if (!$schema->hasTable('larpingapp_effects')) { - $table = $schema->createTable('larpingapp_effects'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->addColumn('stat_id', Types::STRING, ['notnull' => false, 'length' => 255]); - $table->addColumn('modifier', Types::INTEGER, ['notnull' => false]); - $table->addColumn('modification', Types::STRING, ['notnull' => true, 'length' => 50, 'default' => 'positive']); - $table->addColumn('cumulative', Types::STRING, ['notnull' => true, 'length' => 50, 'default' => 'non-cumulative']); - $table->setPrimaryKey(['id']); - } - - if (!$schema->hasTable('larpingapp_events')) { - $table = $schema->createTable('larpingapp_events'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->addColumn('players', Types::JSON, ['notnull' => false]); - $table->addColumn('effects', Types::JSON, ['notnull' => false]); - $table->addColumn('start_date', Types::STRING, ['notnull' => false]); - $table->addColumn('end_date', Types::STRING, ['notnull' => false]); - $table->addColumn('location', Types::STRING, ['notnull' => false, 'length' => 255]); - $table->setPrimaryKey(['id']); - } - - if (!$schema->hasTable('larpingapp_items')) { - $table = $schema->createTable('larpingapp_items'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->addColumn('effect', Types::TEXT, ['notnull' => false]); - $table->addColumn('effects', Types::JSON, ['notnull' => false]); - $table->addColumn('unique', Types::BOOLEAN, ['notnull' => true, 'default' => true]); - $table->setPrimaryKey(['id']); - } - - if (!$schema->hasTable('larpingapp_skills')) { - $table = $schema->createTable('larpingapp_skills'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->addColumn('effect', Types::TEXT, ['notnull' => false]); - $table->addColumn('effects', Types::JSON, ['notnull' => false]); - $table->addColumn('required_skills', Types::JSON, ['notnull' => false]); - $table->addColumn('required_stats', Types::JSON, ['notnull' => false]); - $table->addColumn('required_conditions', Types::JSON, ['notnull' => false]); - $table->addColumn('required_effects', Types::JSON, ['notnull' => false]); - $table->addColumn('required_score', Types::INTEGER, ['notnull' => false]); - $table->setPrimaryKey(['id']); - } - - if (!$schema->hasTable('larpingapp_templates')) { - $table = $schema->createTable('larpingapp_templates'); - $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); - $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); - $table->addColumn('description', Types::TEXT, ['notnull' => false]); - $table->addColumn('template', Types::TEXT, ['notnull' => false]); - $table->setPrimaryKey(['id']); - } - - return $schema; - } - - /** - * @param IOutput $output - * @param Closure(): ISchemaWrapper $schemaClosure - * @param array $options - */ - public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void { - } +class Version0Date20240826193657 extends SimpleMigrationStep +{ + + /** + * @param IOutput $output + * @param Closure(): ISchemaWrapper $schemaClosure + * @param array $options + */ + public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void + { + } + + /** + * @param IOutput $output + * @param Closure(): ISchemaWrapper $schemaClosure + * @param array $options + * @return null|ISchemaWrapper + */ + public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper + { + /** + * @var ISchemaWrapper $schema + */ + $schema = $schemaClosure(); + + if (!$schema->hasTable('larpingapp_abilities')) { + $table = $schema->createTable('larpingapp_abilities'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->setPrimaryKey(['id']); + } + + if (!$schema->hasTable('larpingapp_settings')) { + $table = $schema->createTable('larpingapp_settings'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->setPrimaryKey(['id']); + } + + if (!$schema->hasTable('larpingapp_players')) { + $table = $schema->createTable('larpingapp_players'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->setPrimaryKey(['id']); + } + + if (!$schema->hasTable('larpingapp_characters')) { + $table = $schema->createTable('larpingapp_characters'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('oc_name', Types::STRING, ['notnull' => false, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->addColumn('background', Types::TEXT, ['notnull' => false]); + $table->addColumn('items_and_money', Types::TEXT, ['notnull' => false]); + $table->addColumn('notice', Types::TEXT, ['notnull' => false]); + $table->addColumn('faith', Types::STRING, ['notnull' => false, 'length' => 255]); + $table->addColumn('sl_notes_public', Types::TEXT, ['notnull' => false]); + $table->addColumn('sl_notes_private', Types::TEXT, ['notnull' => false]); + $table->addColumn('card', Types::STRING, ['notnull' => false, 'length' => 255]); + $table->addColumn('stats', Types::JSON, ['notnull' => false]); + $table->addColumn('gold', Types::INTEGER, ['notnull' => false]); + $table->addColumn('silver', Types::INTEGER, ['notnull' => false]); + $table->addColumn('copper', Types::INTEGER, ['notnull' => false]); + $table->addColumn('events', Types::JSON, ['notnull' => false]); + $table->addColumn('skills', Types::JSON, ['notnull' => false]); + $table->addColumn('items', Types::JSON, ['notnull' => false]); + $table->addColumn('conditions', Types::JSON, ['notnull' => false]); + $table->addColumn('type', Types::STRING, ['notnull' => true, 'length' => 50, 'default' => 'player']); + $table->addColumn('approved', Types::STRING, ['notnull' => false, 'length' => 50]); + $table->setPrimaryKey(['id']); + } + + if (!$schema->hasTable('larpingapp_conditions')) { + $table = $schema->createTable('larpingapp_conditions'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->addColumn('effect', Types::TEXT, ['notnull' => false]); + $table->addColumn('effects', Types::JSON, ['notnull' => false]); + $table->addColumn('unique', Types::BOOLEAN, ['notnull' => true, 'default' => false]); + $table->setPrimaryKey(['id']); + } + + if (!$schema->hasTable('larpingapp_effects')) { + $table = $schema->createTable('larpingapp_effects'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->addColumn('stat_id', Types::STRING, ['notnull' => false, 'length' => 255]); + $table->addColumn('modifier', Types::INTEGER, ['notnull' => false]); + $table->addColumn('modification', Types::STRING, ['notnull' => true, 'length' => 50, 'default' => 'positive']); + $table->addColumn('cumulative', Types::STRING, ['notnull' => true, 'length' => 50, 'default' => 'non-cumulative']); + $table->setPrimaryKey(['id']); + } + + if (!$schema->hasTable('larpingapp_events')) { + $table = $schema->createTable('larpingapp_events'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->addColumn('players', Types::JSON, ['notnull' => false]); + $table->addColumn('effects', Types::JSON, ['notnull' => false]); + $table->addColumn('start_date', Types::STRING, ['notnull' => false]); + $table->addColumn('end_date', Types::STRING, ['notnull' => false]); + $table->addColumn('location', Types::STRING, ['notnull' => false, 'length' => 255]); + $table->setPrimaryKey(['id']); + } + + if (!$schema->hasTable('larpingapp_items')) { + $table = $schema->createTable('larpingapp_items'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->addColumn('effect', Types::TEXT, ['notnull' => false]); + $table->addColumn('effects', Types::JSON, ['notnull' => false]); + $table->addColumn('unique', Types::BOOLEAN, ['notnull' => true, 'default' => true]); + $table->setPrimaryKey(['id']); + } + + if (!$schema->hasTable('larpingapp_skills')) { + $table = $schema->createTable('larpingapp_skills'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->addColumn('effect', Types::TEXT, ['notnull' => false]); + $table->addColumn('effects', Types::JSON, ['notnull' => false]); + $table->addColumn('required_skills', Types::JSON, ['notnull' => false]); + $table->addColumn('required_stats', Types::JSON, ['notnull' => false]); + $table->addColumn('required_conditions', Types::JSON, ['notnull' => false]); + $table->addColumn('required_effects', Types::JSON, ['notnull' => false]); + $table->addColumn('required_score', Types::INTEGER, ['notnull' => false]); + $table->setPrimaryKey(['id']); + } + + if (!$schema->hasTable('larpingapp_templates')) { + $table = $schema->createTable('larpingapp_templates'); + $table->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'notnull' => true, 'length' => 20]); + $table->addColumn('name', Types::STRING, ['notnull' => true, 'length' => 255]); + $table->addColumn('description', Types::TEXT, ['notnull' => false]); + $table->addColumn('template', Types::TEXT, ['notnull' => false]); + $table->setPrimaryKey(['id']); + } + + return $schema; + } + + /** + * @param IOutput $output + * @param Closure(): ISchemaWrapper $schemaClosure + * @param array $options + */ + public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void + { + } } diff --git a/lib/Migration/Version0Date20241015141612.php b/lib/Migration/Version0Date20241015141612.php index 1e6102e..8415213 100644 --- a/lib/Migration/Version0Date20241015141612.php +++ b/lib/Migration/Version0Date20241015141612.php @@ -19,41 +19,45 @@ /** * Migration step for creating the larpingapp_abilities table */ -class Version0Date20241015141612 extends SimpleMigrationStep { - - /** - * @param IOutput $output - * @param Closure(): ISchemaWrapper $schemaClosure - * @param array $options - */ - public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void { - } - - /** - * @param IOutput $output - * @param Closure(): ISchemaWrapper $schemaClosure - * @param array $options - * @return null|ISchemaWrapper - */ - public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { - /** - * @var ISchemaWrapper $schema - */ - $schema = $schemaClosure(); - - // Update the abilities table to add the base column - $table = $schema->getTable('larpingapp_abilities'); - $table->addColumn('base', Types::INTEGER, ['notnull' => true, 'default' => 0]); - $table->addColumn('allowed_negative', Types::BOOLEAN, ['notnull' => true, 'default' => false]); - - return $schema; - } - - /** - * @param IOutput $output - * @param Closure(): ISchemaWrapper $schemaClosure - * @param array $options - */ - public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void { - } +class Version0Date20241015141612 extends SimpleMigrationStep +{ + + /** + * @param IOutput $output + * @param Closure(): ISchemaWrapper $schemaClosure + * @param array $options + */ + public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void + { + } + + /** + * @param IOutput $output + * @param Closure(): ISchemaWrapper $schemaClosure + * @param array $options + * @return null|ISchemaWrapper + */ + public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper + { + /** + * @var ISchemaWrapper $schema + */ + $schema = $schemaClosure(); + + // Update the abilities table to add the base column + $table = $schema->getTable('larpingapp_abilities'); + $table->addColumn('base', Types::INTEGER, ['notnull' => true, 'default' => 0]); + $table->addColumn('allowed_negative', Types::BOOLEAN, ['notnull' => true, 'default' => false]); + + return $schema; + } + + /** + * @param IOutput $output + * @param Closure(): ISchemaWrapper $schemaClosure + * @param array $options + */ + public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void + { + } } diff --git a/lib/Sections/LarpingAppAdmin.php b/lib/Sections/LarpingAppAdmin.php index 6982217..905275c 100644 --- a/lib/Sections/LarpingAppAdmin.php +++ b/lib/Sections/LarpingAppAdmin.php @@ -5,28 +5,34 @@ use OCP\IURLGenerator; use OCP\Settings\IIconSection; -class LarpingAppAdmin implements IIconSection { +class LarpingAppAdmin implements IIconSection +{ private IL10N $l; private IURLGenerator $urlGenerator; - public function __construct(IL10N $l, IURLGenerator $urlGenerator) { + public function __construct(IL10N $l, IURLGenerator $urlGenerator) + { $this->l = $l; $this->urlGenerator = $urlGenerator; } - public function getIcon(): string { + public function getIcon(): string + { return $this->urlGenerator->imagePath('core', 'actions/settings-dark.svg'); } - public function getID(): string { + public function getID(): string + { return 'larpingapp'; } - public function getName(): string { + public function getName(): string + { return $this->l->t('Larping App'); } - public function getPriority(): int { + public function getPriority(): int + { return 97; } } \ No newline at end of file diff --git a/lib/Service/CharacterService.php b/lib/Service/CharacterService.php index 122c823..2390b98 100644 --- a/lib/Service/CharacterService.php +++ b/lib/Service/CharacterService.php @@ -23,6 +23,7 @@ use OCA\LarpingApp\Service\ObjectService; use Mpdf\Mpdf; +use Mpdf\MpdfException; use Twig\Environment; use Twig\Loader\FilesystemLoader; @@ -39,14 +40,14 @@ class CharacterService private array $allAbilities = []; public function __construct( - private readonly CharacterMapper $characterMapper, - private readonly AbilityMapper $abilityMapper, - private readonly SkillMapper $skillMapper, - private readonly ItemMapper $itemMapper, - private readonly ConditionMapper $conditionMapper, - private readonly EventMapper $eventMapper, - private readonly EffectMapper $effectMapper, - private readonly ObjectService $objectService + private readonly CharacterMapper $characterMapper, + private readonly AbilityMapper $abilityMapper, + private readonly SkillMapper $skillMapper, + private readonly ItemMapper $itemMapper, + private readonly ConditionMapper $conditionMapper, + private readonly EventMapper $eventMapper, + private readonly EffectMapper $effectMapper, + private readonly ObjectService $objectService ) { $this->loadAllEntities(); } @@ -55,45 +56,57 @@ private function loadAllEntities(): void { // Get all skills and index them by ID $skills = $this->objectService->getObjects('skill'); - $this->allSkills = array_reduce($skills, function($carry, $skill) { - $carry[$skill['id']] = $skill; - return $carry; - }, []); + $this->allSkills = array_reduce( + $skills, function ($carry, $skill) { + $carry[$skill['id']] = $skill; + return $carry; + }, [] + ); // Get all items and index them by ID $items = $this->objectService->getObjects('item'); - $this->allItems = array_reduce($items, function($carry, $item) { - $carry[$item['id']] = $item; - return $carry; - }, []); + $this->allItems = array_reduce( + $items, function ($carry, $item) { + $carry[$item['id']] = $item; + return $carry; + }, [] + ); // Get all conditions and index them by ID $conditions = $this->objectService->getObjects('condition'); - $this->allConditions = array_reduce($conditions, function($carry, $condition) { - $carry[$condition['id']] = $condition; - return $carry; - }, []); + $this->allConditions = array_reduce( + $conditions, function ($carry, $condition) { + $carry[$condition['id']] = $condition; + return $carry; + }, [] + ); // Get all events and index them by ID $events = $this->objectService->getObjects('event'); - $this->allEvents = array_reduce($events, function($carry, $event) { - $carry[$event['id']] = $event; - return $carry; - }, []); + $this->allEvents = array_reduce( + $events, function ($carry, $event) { + $carry[$event['id']] = $event; + return $carry; + }, [] + ); // Get all effects and index them by ID $effects = $this->objectService->getObjects('effect'); - $this->allEffects = array_reduce($effects, function($carry, $effect) { - $carry[$effect['id']] = $effect; - return $carry; - }, []); + $this->allEffects = array_reduce( + $effects, function ($carry, $effect) { + $carry[$effect['id']] = $effect; + return $carry; + }, [] + ); // Get all abilities and index them by ID $abilities = $this->objectService->getObjects('ability'); - $this->allAbilities = array_reduce($abilities, function($carry, $ability) { - $carry[$ability['id']] = $ability; - return $carry; - }, []); + $this->allAbilities = array_reduce( + $abilities, function ($carry, $ability) { + $carry[$ability['id']] = $ability; + return $carry; + }, [] + ); } /** @@ -114,7 +127,7 @@ public function calculateAllCharacters(): array /** * Calculate stats for a single character array * - * @param array $character Character data array + * @param array $character Character data array * @return array Updated character data array with calculated stats */ public function calculateCharacter(array $character): array @@ -181,8 +194,8 @@ public function calculateCharacter(array $character): array /** * Apply effects to abilities * - * @param array $abilities Reference to the abilities array - * @param array|null $effects Array of effect IDs + * @param array $abilities Reference to the abilities array + * @param array|null $effects Array of effect IDs */ private function applyEffects(array &$abilities, ?array $effects): void { @@ -208,7 +221,7 @@ private function applyEffects(array &$abilities, ?array $effects): void * Calculate and apply a single effect * * @param array $abilities Reference to the abilities array - * @param array $effect Effect array containing stat_id, modifier and modification + * @param array $effect Effect array containing stat_id, modifier and modification */ private function calculateEffect(array &$abilities, array $effect): void { @@ -265,10 +278,10 @@ private function calculateEffect(array &$abilities, array $effect): void /** * Create a PDF from a character using a specified template * - * @param array $character Character data array containing character information - * @param array $template Template data array containing PDF layout configuration - * @return string Generated PDF content as string - * @throws \Exception If PDF generation fails + * @param array $character Character data array containing character information + * @param array $template Template data array containing PDF layout configuration + * @return string Generated PDF content as string + * @throws \Exception If PDF generation fails * @psalm-param array{name: string, stats: array, skills?: array, items?: array, conditions?: array, events?: array} $character * @psalm-param array{name: string, orientation?: string, format?: string, sections?: array} $template */ @@ -281,18 +294,18 @@ public function createCharacterPdf(array $character, array $template): Mpdf $html = $template->render(['character' => $character, 'template' => $template]); // Check if the directory exists, if not, create it - if (file_exists(filename: '/tmp/mpdf') === false) { - mkdir(directory: '/tmp/mpdf', recursive: true); - } + if (file_exists(filename: '/tmp/mpdf') === false) { + mkdir(directory: '/tmp/mpdf', recursive: true); + } - // Set permissions for the directory (ensure it's writable) - chmod(filename: '/tmp/mpdf', permissions: 0777); + // Set permissions for the directory (ensure it's writable) + chmod(filename: '/tmp/mpdf', permissions: 0777); - // Initialize mPDF - $mpdf = new Mpdf(config: ['tempDir' => '/tmp/mpdf']); + // Initialize mPDF + $mpdf = new Mpdf(config: ['tempDir' => '/tmp/mpdf']); - // Write HTML to PDF - $mpdf->WriteHTML(html: $html); + // Write HTML to PDF + $mpdf->WriteHTML(html: $html); return $mpdf; } diff --git a/lib/Service/ObjectService.php b/lib/Service/ObjectService.php index 7583314..547926a 100644 --- a/lib/Service/ObjectService.php +++ b/lib/Service/ObjectService.php @@ -37,500 +37,506 @@ */ class ObjectService { - /** @var string $appName The name of the app */ - private string $appName; - - /** - * Constructor for ObjectService. - */ - public function __construct( - private AbilityMapper $abilityMapper, - private CharacterMapper $characterMapper, - private ConditionMapper $conditionMapper, - private EffectMapper $effectMapper, - private EventMapper $eventMapper, - private ItemMapper $itemMapper, - private PlayerMapper $playerMapper, - private SettingMapper $settingMapper, - private SkillMapper $skillMapper, - private TemplateMapper $templateMapper, - private ContainerInterface $container, - private readonly IAppManager $appManager, - private readonly IAppConfig $config, - ) { - $this->appName = 'larpingapp'; - } - - /** - * Gets the appropriate mapper based on the object type. - * - * @param string $objectType The type of object to retrieve the mapper for. - * - * @return mixed The appropriate mapper. - * @throws InvalidArgumentException If an unknown object type is provided. - * @throws NotFoundExceptionInterface|ContainerExceptionInterface If OpenRegister service is not available or if register/schema is not configured. - * @throws Exception - */ - private function getMapper(string $objectType): mixed - { - $objectTypeLower = strtolower($objectType); - - // Get the source for the object type from the configuration - $source = $this->config->getValueString($this->appName, $objectTypeLower . '_source', 'internal'); - - // If the source is 'open_registers', use the OpenRegister service - if ($source === 'openregister') { - $openRegister = $this->getOpenRegisters(); - if ($openRegister === null) { - throw new Exception("OpenRegister service not available"); - } - $register = $this->config->getValueString($this->appName, $objectTypeLower . '_register', ''); - if (empty($register)) { - throw new Exception("Register not configured for $objectType"); - } - $schema = $this->config->getValueString($this->appName, $objectTypeLower . '_schema', ''); - if (empty($schema)) { - throw new Exception("Schema not configured for $objectType"); - } - return $openRegister->getMapper(register: $register, schema: $schema); - } - - // If the source is internal, return the appropriate mapper based on the object type - return match ($objectType) { - 'ability' => $this->abilityMapper, - 'character' => $this->characterMapper, - 'condition' => $this->conditionMapper, - 'effect' => $this->effectMapper, - 'event' => $this->eventMapper, - 'item' => $this->itemMapper, - 'player' => $this->playerMapper, - 'setting' => $this->settingMapper, - 'skill' => $this->skillMapper, - 'template' => $this->templateMapper, - default => throw new InvalidArgumentException("Unknown object type: $objectType"), - }; - } - - /** - * Gets an object based on the object type and id. - * - * @param string $objectType The type of object to retrieve. - * @param string $id The id of the object to retrieve. - * - * @return mixed The retrieved object. - * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface - * @throws InvalidArgumentException If extend is requested for non-OpenRegister objects - */ - public function getObject(string $objectType, string $id, array $extend = []): mixed - { - // Clean up the id if it's a URI by getting only the last path part - if (filter_var($id, FILTER_VALIDATE_URL)) { - $parts = explode('/', rtrim($id, '/')); - $id = end($parts); - } - - // Get the appropriate mapper for the object type - $mapper = $this->getMapper($objectType); - - // Check if extend is requested for non-OpenRegister objects - if (!empty($extend) && !($mapper instanceof \OCA\OpenRegister\Service\ObjectService)) { - throw new InvalidArgumentException('Extend functionality is only available for OpenRegister objects'); - } - - // Use the mapper to find and return the object - $object = $mapper->find($id); - - // Convert the object to an array if it is not already an array - if (is_object($object) && method_exists($object, 'jsonSerialize')) { - return $object->jsonSerialize(); - } - - return is_array($object) ? $object : (array)$object; - } - - /** - * Gets objects based on the object type and various parameters. - * - * @param string $objectType The type of objects to retrieve. - * @param int|null $limit The maximum number of objects to retrieve. - * @param int|null $offset The offset from which to start retrieving objects. - * @param array|null $filters Filters to apply to the query. - * @param array|null $sort Sorting parameters for the query. - * @param array|null $extend Additional parameters for extending the query. - * - * @return array The retrieved objects as arrays. - * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface - * @throws InvalidArgumentException If extend is requested for non-OpenRegister objects - */ - public function getObjects( - string $objectType, - ?int $limit = null, - ?int $offset = null, - ?array $filters = [], - ?array $sort = [], - ?string $search = null, - ?array $extend = [] - ): array - { - // Get the appropriate mapper for the object type - $mapper = $this->getMapper($objectType); - - // Check if extend is requested for non-OpenRegister objects - if (!empty($extend) && !($mapper instanceof \OCA\OpenRegister\Service\ObjectService)) { - throw new InvalidArgumentException('Extend functionality is only available for OpenRegister objects'); - } - - // Use the mapper to find and return the objects based on the provided parameters - $objects = $mapper->findAll( - limit: $limit, - offset: $offset, - filters: $filters, - sort: $sort, - search: $search, - extend: $extend - ); - - // Convert entity objects to arrays using jsonSerialize - return array_map(function($object) { - // If object is already an array, return it directly - if (is_array($object)) { - return $object; - } - // Otherwise serialize the object - return $object->jsonSerialize(); - }, $objects); - } - - /** - * Gets objects based on the object type, filters, search conditions, and other parameters. - * - * @param string $objectType The type of objects to retrieve. - * @param int|null $limit The maximum number of objects to retrieve. - * @param int|null $offset The offset from which to start retrieving objects. - * @param array|null $filters Filters to apply to the query. - * @param array|null $searchConditions Search conditions to apply to the query. - * @param array|null $searchParams Search parameters for the query. - * @param array|null $sort Sorting parameters for the query. - * @param array|null $extend Additional parameters for extending the query. - * - * @return array The retrieved objects as arrays. - * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface - */ - public function getFacets( - string $objectType, - array $filters = [], - ): array - { - // Get the appropriate mapper for the object type - $mapper = $this->getMapper($objectType); - - // Use the mapper to find and return the objects based on the provided parameters - if ($mapper instanceof \OCA\OpenRegister\Service\ObjectService === true) { - return $mapper->getAggregations($filters); - } - - return []; - } - - /** - * Gets multiple objects based on the object type and ids. - * - * @param string $objectType The type of objects to retrieve. - * @param array $ids The ids of the objects to retrieve. - * - * @return array The retrieved objects. - * @throws ContainerExceptionInterface|NotFoundExceptionInterface If an unknown object type is provided. - */ - public function getMultipleObjects(string $objectType, array $ids): array - { - // Process the ids - $processedIds = array_map(function($id) { - if (is_object($id) && method_exists($id, 'getId')) { - return $id->getId(); - } elseif (is_array($id) && isset($id['id'])) { - return $id['id']; - } else { - return $id; - } - }, $ids); - - // Clean up the ids if they are URIs - $cleanedIds = array_map(function($id) { - // If the id is a URI, get only the last part of the path - if (filter_var($id, FILTER_VALIDATE_URL)) { - $parts = explode('/', rtrim($id, '/')); - return end($parts); - } - return $id; - }, $processedIds); - - // Get the appropriate mapper for the object type - $mapper = $this->getMapper($objectType); - - // Use the mapper to find and return multiple objects based on the provided cleaned ids - return $mapper->findMultiple($cleanedIds); - } - - /** - * Gets all objects of a specific type. - * - * @param string $objectType The type of objects to retrieve. - * @param int|null $limit The maximum number of objects to retrieve. - * @param int|null $offset The offset from which to start retrieving objects. - * - * @return array The retrieved objects. - * @throws ContainerExceptionInterface|NotFoundExceptionInterface If an unknown object type is provided. - */ - public function getAllObjects(string $objectType, ?int $limit = null, ?int $offset = null): array - { - // Get the appropriate mapper for the object type - $mapper = $this->getMapper($objectType); - - // Use the mapper to find and return all objects of the specified type - return $mapper->findAll($limit, $offset); - } - - /** - * Creates a new object or updates an existing one from an array of data. - * - * @param string $objectType The type of object to create or update. - * @param array $object The data to create or update the object from. - * @param bool $updateVersion If we should update the version or not, default = true. - * - * @return mixed The created or updated object. - * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface - */ - public function saveObject(string $objectType, array $object, array $extend = [], bool $updateVersion = true): mixed - { - // Get the appropriate mapper for the object type - $mapper = $this->getMapper($objectType); - // If the object has an id, update it; otherwise, create a new object - if (isset($object['id']) === true) { - return $mapper->updateFromArray(id: $object['id'], object: $object, updateVersion: $updateVersion, extend: $extend); - } - else { - return $mapper->createFromArray(object: $object, extend: $extend); - } - } - - /** - * Deletes an object based on the object type and id. - * - * @param string $objectType The type of object to delete. - * @param string|int $id The id of the object to delete. - * - * @return bool True if the object was successfully deleted, false otherwise. - * @throws ContainerExceptionInterface|NotFoundExceptionInterface|\OCP\DB\Exception If an unknown object type is provided. - */ - public function deleteObject(string $objectType, string|int $id): bool - { - // Get the appropriate mapper for the object type - $mapper = $this->getMapper($objectType); - - // Use the mapper to get and delete the object - try { - $object = $mapper->find($id); - $mapper->delete($object); - } catch (Exception $e) { - return false; - } - - return true; - } - - /** - * Attempts to retrieve the OpenRegister service from the container. - * - * @return mixed|null The OpenRegister service if available, null otherwise. - * @throws ContainerExceptionInterface|NotFoundExceptionInterface - */ - public function getOpenRegisters(): ?\OCA\OpenRegister\Service\ObjectService - { - if (in_array(needle: 'openregister', haystack: $this->appManager->getInstalledApps()) === true) { - try { - // Attempt to get the OpenRegister service from the container - return $this->container->get('OCA\OpenRegister\Service\ObjectService'); - } catch (Exception $e) { - // If the service is not available, return null - return null; - } - } - - return null; - } - - private function getCount(string $objectType, array $filters = []): int - { - $mapper = $this->getMapper($objectType); - if($mapper instanceof \OCA\OpenRegister\Service\ObjectService === true) { - return $mapper->count(filters: $filters); - } - - return 0; - } - - /** - * Get a result array for a request based on the request and the object type. - * - * @param string $objectType The type of object to retrieve - * @param array $requestParams The request parameters - * - * @return array The result array containing objects and total count - * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface - * @throws InvalidArgumentException If extend is requested for non-OpenRegister objects - */ - public function getResultArrayForRequest(string $objectType, array $requestParams): array - { - // Extract specific parameters - $limit = $requestParams['limit'] ?? $requestParams['_limit'] ?? null; - $offset = $requestParams['offset'] ?? $requestParams['_offset'] ?? null; - $order = $requestParams['order'] ?? $requestParams['_order'] ?? []; - $extend = $requestParams['extend'] ?? $requestParams['_extend'] ?? null; - $page = $requestParams['page'] ?? $requestParams['_page'] ?? null; - $search = $requestParams['search'] ?? $requestParams['_search'] ?? null; - // If page is set, calculate the offset - if ($page !== null && isset($limit)) { - $offset = $limit * ($page - 1); - } - - // Ensure order and extend are arrays - if (is_string($order)) { - $order = array_map('trim', explode(',', $order)); - } - if (is_string($extend)) { - $extend = array_map('trim', explode(',', $extend)); - } - - // Remove unnecessary parameters from filters - $filters = $requestParams; - unset($filters['_route']); // Nextcloud automatically adds this - unset($filters['_extend'], $filters['_limit'], $filters['_offset'], $filters['_order'], $filters['_page']); - unset($filters['extend'], $filters['limit'], $filters['offset'], $filters['order'], $filters['page']); - // Fetch objects based on filters and order - - $objects = $this->getObjects( - objectType: $objectType, - limit: $limit, - offset: $offset, - filters: $filters, - sort: $order, - extend: $extend, - search: $search - ); - - $facets = $this->getFacets($objectType, $filters); - - return [ - 'results' => $objects, - 'facets' => $facets, - 'total' => $this->getCount(objectType: $objectType, filters: $filters), - ]; - } - - /** - * Extends an entity with related objects based on the extend array. - * - * @param mixed $entity The entity to extend - * @param array $extend An array of properties to extend - * - * @return array The extended entity as an array - * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface If a property is not present on the entity - */ - public function extendEntity(mixed $entity, array $extend): array - { - $surpressMapperError = false; - // Convert the entity to an array if it's not already one - $result = is_array($entity) ? $entity : $entity->jsonSerialize(); - - if (in_array(needle: 'all', haystack: $extend) === true) { - $extend = array_keys($entity); - $surpressMapperError = true; - } - - // Iterate through each property to be extended - foreach ($extend as $property) { - // Create a singular property name - $singularProperty = rtrim($property, 's'); - - // Check if property or singular property are keys in the array - if (array_key_exists($property, $result)) { - $value = $result[$property]; - if (empty($value)) { - continue; - } - } elseif (array_key_exists($singularProperty, $result)) { - $value = $result[$singularProperty]; - } else { - throw new Exception("Property '$property' or '$singularProperty' is not present in the entity."); - } - - // Get a mapper for the property - $propertyObject = $property; - try { - $mapper = $this->getMapper($property); - $propertyObject = $singularProperty; - } catch (Exception $e) { - try { - $mapper = $this->getMapper($singularProperty); - $propertyObject = $singularProperty; - } catch (Exception $e) { - // If still no mapper, throw a no mapper available error - if ($surpressMapperError === true) { - continue; - } - throw new Exception("No mapper available for property '$property'."); - } - } - - // Update the values - if (is_array($value)) { - // If the value is an array, get multiple related objects - $result[$property] = $this->getMultipleObjects($propertyObject, $value); - } else { - // If the value is not an array, get a single related object - $objectId = is_object($value) ? $value->getId() : $value; - $result[$property] = $this->getObject($propertyObject, $objectId); - } - } - - // Return the extended entity as an array - return $result; - } - - /** - * Get all relations for a specific object - * - * @param string $objectType The type of object to get relations for - * @param string $id The id of the object to get relations for - * - * @return array The relations for the object - * @throws Exception If OpenRegister service is not available - */ - public function getRelations(string $objectType, string $id): array - { - // Get the mapper first - $mapper = $this->getMapper($objectType); - - // Get audit trails from OpenRegister - $auditTrails = $mapper->getRelations($id); - - return $auditTrails; - } - - /** - * Get all the useses that an specific object has - * - * @param string $objectType The type of object to get uses for - * @param string $id The id of the object to get uses for - * - * @return array The uses for the object - */ - public function getUses(string $objectType, string $id): array - { - $mapper = $this->getMapper($objectType); - $uses = $mapper->getUses($id); - return $uses; - } + /** + * @var string $appName The name of the app + */ + private string $appName; + + /** + * Constructor for ObjectService. + */ + public function __construct( + private AbilityMapper $abilityMapper, + private CharacterMapper $characterMapper, + private ConditionMapper $conditionMapper, + private EffectMapper $effectMapper, + private EventMapper $eventMapper, + private ItemMapper $itemMapper, + private PlayerMapper $playerMapper, + private SettingMapper $settingMapper, + private SkillMapper $skillMapper, + private TemplateMapper $templateMapper, + private ContainerInterface $container, + private readonly IAppManager $appManager, + private readonly IAppConfig $config, + ) { + $this->appName = 'larpingapp'; + } + + /** + * Gets the appropriate mapper based on the object type. + * + * @param string $objectType The type of object to retrieve the mapper for. + * + * @return mixed The appropriate mapper. + * @throws InvalidArgumentException If an unknown object type is provided. + * @throws NotFoundExceptionInterface|ContainerExceptionInterface If OpenRegister service is not available or if register/schema is not configured. + * @throws Exception + */ + private function getMapper(string $objectType): mixed + { + $objectTypeLower = strtolower($objectType); + + // Get the source for the object type from the configuration + $source = $this->config->getValueString($this->appName, $objectTypeLower . '_source', 'internal'); + + // If the source is 'open_registers', use the OpenRegister service + if ($source === 'openregister') { + $openRegister = $this->getOpenRegisters(); + if ($openRegister === null) { + throw new Exception("OpenRegister service not available"); + } + $register = $this->config->getValueString($this->appName, $objectTypeLower . '_register', ''); + if (empty($register)) { + throw new Exception("Register not configured for $objectType"); + } + $schema = $this->config->getValueString($this->appName, $objectTypeLower . '_schema', ''); + if (empty($schema)) { + throw new Exception("Schema not configured for $objectType"); + } + return $openRegister->getMapper(register: $register, schema: $schema); + } + + // If the source is internal, return the appropriate mapper based on the object type + return match ($objectType) { + 'ability' => $this->abilityMapper, + 'character' => $this->characterMapper, + 'condition' => $this->conditionMapper, + 'effect' => $this->effectMapper, + 'event' => $this->eventMapper, + 'item' => $this->itemMapper, + 'player' => $this->playerMapper, + 'setting' => $this->settingMapper, + 'skill' => $this->skillMapper, + 'template' => $this->templateMapper, + default => throw new InvalidArgumentException("Unknown object type: $objectType"), + }; + } + + /** + * Gets an object based on the object type and id. + * + * @param string $objectType The type of object to retrieve. + * @param string $id The id of the object to retrieve. + * + * @return mixed The retrieved object. + * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface + * @throws InvalidArgumentException If extend is requested for non-OpenRegister objects + */ + public function getObject(string $objectType, string $id, array $extend = []): mixed + { + // Clean up the id if it's a URI by getting only the last path part + if (filter_var($id, FILTER_VALIDATE_URL)) { + $parts = explode('/', rtrim($id, '/')); + $id = end($parts); + } + + // Get the appropriate mapper for the object type + $mapper = $this->getMapper($objectType); + + // Check if extend is requested for non-OpenRegister objects + if (!empty($extend) && !($mapper instanceof \OCA\OpenRegister\Service\ObjectService)) { + throw new InvalidArgumentException('Extend functionality is only available for OpenRegister objects'); + } + + // Use the mapper to find and return the object + $object = $mapper->find($id); + + // Convert the object to an array if it is not already an array + if (is_object($object) && method_exists($object, 'jsonSerialize')) { + return $object->jsonSerialize(); + } + + return is_array($object) ? $object : (array)$object; + } + + /** + * Gets objects based on the object type and various parameters. + * + * @param string $objectType The type of objects to retrieve. + * @param int|null $limit The maximum number of objects to retrieve. + * @param int|null $offset The offset from which to start retrieving objects. + * @param array|null $filters Filters to apply to the query. + * @param array|null $sort Sorting parameters for the query. + * @param array|null $extend Additional parameters for extending the query. + * + * @return array The retrieved objects as arrays. + * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface + * @throws InvalidArgumentException If extend is requested for non-OpenRegister objects + */ + public function getObjects( + string $objectType, + ?int $limit = null, + ?int $offset = null, + ?array $filters = [], + ?array $sort = [], + ?string $search = null, + ?array $extend = [] + ): array { + // Get the appropriate mapper for the object type + $mapper = $this->getMapper($objectType); + + // Check if extend is requested for non-OpenRegister objects + if (!empty($extend) && !($mapper instanceof \OCA\OpenRegister\Service\ObjectService)) { + throw new InvalidArgumentException('Extend functionality is only available for OpenRegister objects'); + } + + // Use the mapper to find and return the objects based on the provided parameters + $objects = $mapper->findAll( + limit: $limit, + offset: $offset, + filters: $filters, + sort: $sort, + search: $search, + extend: $extend + ); + + // Convert entity objects to arrays using jsonSerialize + return array_map( + function ($object) { + // If object is already an array, return it directly + if (is_array($object)) { + return $object; + } + // Otherwise serialize the object + return $object->jsonSerialize(); + }, $objects + ); + } + + /** + * Gets objects based on the object type, filters, search conditions, and other parameters. + * + * @param string $objectType The type of objects to retrieve. + * @param int|null $limit The maximum number of objects to retrieve. + * @param int|null $offset The offset from which to start retrieving objects. + * @param array|null $filters Filters to apply to the query. + * @param array|null $searchConditions Search conditions to apply to the query. + * @param array|null $searchParams Search parameters for the query. + * @param array|null $sort Sorting parameters for the query. + * @param array|null $extend Additional parameters for extending the query. + * + * @return array The retrieved objects as arrays. + * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface + */ + public function getFacets( + string $objectType, + array $filters = [], + ): array { + // Get the appropriate mapper for the object type + $mapper = $this->getMapper($objectType); + + // Use the mapper to find and return the objects based on the provided parameters + if ($mapper instanceof \OCA\OpenRegister\Service\ObjectService === true) { + return $mapper->getAggregations($filters); + } + + return []; + } + + /** + * Gets multiple objects based on the object type and ids. + * + * @param string $objectType The type of objects to retrieve. + * @param array $ids The ids of the objects to retrieve. + * + * @return array The retrieved objects. + * @throws ContainerExceptionInterface|NotFoundExceptionInterface If an unknown object type is provided. + */ + public function getMultipleObjects(string $objectType, array $ids): array + { + // Process the ids + $processedIds = array_map( + function ($id) { + if (is_object($id) && method_exists($id, 'getId')) { + return $id->getId(); + } elseif (is_array($id) && isset($id['id'])) { + return $id['id']; + } else { + return $id; + } + }, $ids + ); + + // Clean up the ids if they are URIs + $cleanedIds = array_map( + function ($id) { + // If the id is a URI, get only the last part of the path + if (filter_var($id, FILTER_VALIDATE_URL)) { + $parts = explode('/', rtrim($id, '/')); + return end($parts); + } + return $id; + }, $processedIds + ); + + // Get the appropriate mapper for the object type + $mapper = $this->getMapper($objectType); + + // Use the mapper to find and return multiple objects based on the provided cleaned ids + return $mapper->findMultiple($cleanedIds); + } + + /** + * Gets all objects of a specific type. + * + * @param string $objectType The type of objects to retrieve. + * @param int|null $limit The maximum number of objects to retrieve. + * @param int|null $offset The offset from which to start retrieving objects. + * + * @return array The retrieved objects. + * @throws ContainerExceptionInterface|NotFoundExceptionInterface If an unknown object type is provided. + */ + public function getAllObjects(string $objectType, ?int $limit = null, ?int $offset = null): array + { + // Get the appropriate mapper for the object type + $mapper = $this->getMapper($objectType); + + // Use the mapper to find and return all objects of the specified type + return $mapper->findAll($limit, $offset); + } + + /** + * Creates a new object or updates an existing one from an array of data. + * + * @param string $objectType The type of object to create or update. + * @param array $object The data to create or update the object from. + * @param bool $updateVersion If we should update the version or not, default = true. + * + * @return mixed The created or updated object. + * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface + */ + public function saveObject(string $objectType, array $object, array $extend = [], bool $updateVersion = true): mixed + { + // Get the appropriate mapper for the object type + $mapper = $this->getMapper($objectType); + // If the object has an id, update it; otherwise, create a new object + if (isset($object['id']) === true) { + return $mapper->updateFromArray(id: $object['id'], object: $object, updateVersion: $updateVersion, extend: $extend); + } + else { + return $mapper->createFromArray(object: $object, extend: $extend); + } + } + + /** + * Deletes an object based on the object type and id. + * + * @param string $objectType The type of object to delete. + * @param string|int $id The id of the object to delete. + * + * @return bool True if the object was successfully deleted, false otherwise. + * @throws ContainerExceptionInterface|NotFoundExceptionInterface|\OCP\DB\Exception If an unknown object type is provided. + */ + public function deleteObject(string $objectType, string|int $id): bool + { + // Get the appropriate mapper for the object type + $mapper = $this->getMapper($objectType); + + // Use the mapper to get and delete the object + try { + $object = $mapper->find($id); + $mapper->delete($object); + } catch (Exception $e) { + return false; + } + + return true; + } + + /** + * Attempts to retrieve the OpenRegister service from the container. + * + * @return mixed|null The OpenRegister service if available, null otherwise. + * @throws ContainerExceptionInterface|NotFoundExceptionInterface + */ + public function getOpenRegisters(): ?\OCA\OpenRegister\Service\ObjectService + { + if (in_array(needle: 'openregister', haystack: $this->appManager->getInstalledApps()) === true) { + try { + // Attempt to get the OpenRegister service from the container + return $this->container->get('OCA\OpenRegister\Service\ObjectService'); + } catch (Exception $e) { + // If the service is not available, return null + return null; + } + } + + return null; + } + + private function getCount(string $objectType, array $filters = []): int + { + $mapper = $this->getMapper($objectType); + if($mapper instanceof \OCA\OpenRegister\Service\ObjectService === true) { + return $mapper->count(filters: $filters); + } + + return 0; + } + + /** + * Get a result array for a request based on the request and the object type. + * + * @param string $objectType The type of object to retrieve + * @param array $requestParams The request parameters + * + * @return array The result array containing objects and total count + * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface + * @throws InvalidArgumentException If extend is requested for non-OpenRegister objects + */ + public function getResultArrayForRequest(string $objectType, array $requestParams): array + { + // Extract specific parameters + $limit = $requestParams['limit'] ?? $requestParams['_limit'] ?? null; + $offset = $requestParams['offset'] ?? $requestParams['_offset'] ?? null; + $order = $requestParams['order'] ?? $requestParams['_order'] ?? []; + $extend = $requestParams['extend'] ?? $requestParams['_extend'] ?? null; + $page = $requestParams['page'] ?? $requestParams['_page'] ?? null; + $search = $requestParams['search'] ?? $requestParams['_search'] ?? null; + // If page is set, calculate the offset + if ($page !== null && isset($limit)) { + $offset = $limit * ($page - 1); + } + + // Ensure order and extend are arrays + if (is_string($order)) { + $order = array_map('trim', explode(',', $order)); + } + if (is_string($extend)) { + $extend = array_map('trim', explode(',', $extend)); + } + + // Remove unnecessary parameters from filters + $filters = $requestParams; + unset($filters['_route']); // Nextcloud automatically adds this + unset($filters['_extend'], $filters['_limit'], $filters['_offset'], $filters['_order'], $filters['_page']); + unset($filters['extend'], $filters['limit'], $filters['offset'], $filters['order'], $filters['page']); + // Fetch objects based on filters and order + + $objects = $this->getObjects( + objectType: $objectType, + limit: $limit, + offset: $offset, + filters: $filters, + sort: $order, + extend: $extend, + search: $search + ); + + $facets = $this->getFacets($objectType, $filters); + + return [ + 'results' => $objects, + 'facets' => $facets, + 'total' => $this->getCount(objectType: $objectType, filters: $filters), + ]; + } + + /** + * Extends an entity with related objects based on the extend array. + * + * @param mixed $entity The entity to extend + * @param array $extend An array of properties to extend + * + * @return array The extended entity as an array + * @throws ContainerExceptionInterface|DoesNotExistException|MultipleObjectsReturnedException|NotFoundExceptionInterface If a property is not present on the entity + */ + public function extendEntity(mixed $entity, array $extend): array + { + $surpressMapperError = false; + // Convert the entity to an array if it's not already one + $result = is_array($entity) ? $entity : $entity->jsonSerialize(); + + if (in_array(needle: 'all', haystack: $extend) === true) { + $extend = array_keys($entity); + $surpressMapperError = true; + } + + // Iterate through each property to be extended + foreach ($extend as $property) { + // Create a singular property name + $singularProperty = rtrim($property, 's'); + + // Check if property or singular property are keys in the array + if (array_key_exists($property, $result)) { + $value = $result[$property]; + if (empty($value)) { + continue; + } + } elseif (array_key_exists($singularProperty, $result)) { + $value = $result[$singularProperty]; + } else { + throw new Exception("Property '$property' or '$singularProperty' is not present in the entity."); + } + + // Get a mapper for the property + $propertyObject = $property; + try { + $mapper = $this->getMapper($property); + $propertyObject = $singularProperty; + } catch (Exception $e) { + try { + $mapper = $this->getMapper($singularProperty); + $propertyObject = $singularProperty; + } catch (Exception $e) { + // If still no mapper, throw a no mapper available error + if ($surpressMapperError === true) { + continue; + } + throw new Exception("No mapper available for property '$property'."); + } + } + + // Update the values + if (is_array($value)) { + // If the value is an array, get multiple related objects + $result[$property] = $this->getMultipleObjects($propertyObject, $value); + } else { + // If the value is not an array, get a single related object + $objectId = is_object($value) ? $value->getId() : $value; + $result[$property] = $this->getObject($propertyObject, $objectId); + } + } + + // Return the extended entity as an array + return $result; + } + + /** + * Get all relations for a specific object + * + * @param string $objectType The type of object to get relations for + * @param string $id The id of the object to get relations for + * + * @return array The relations for the object + * @throws Exception If OpenRegister service is not available + */ + public function getRelations(string $objectType, string $id): array + { + // Get the mapper first + $mapper = $this->getMapper($objectType); + + // Get audit trails from OpenRegister + $auditTrails = $mapper->getRelations($id); + + return $auditTrails; + } + + /** + * Get all the useses that an specific object has + * + * @param string $objectType The type of object to get uses for + * @param string $id The id of the object to get uses for + * + * @return array The uses for the object + */ + public function getUses(string $objectType, string $id): array + { + $mapper = $this->getMapper($objectType); + $uses = $mapper->getUses($id); + return $uses; + } /** * Get all files associated with a specific object @@ -542,78 +548,81 @@ public function getUses(string $objectType, string $id): array */ public function getFiles(string $objectType, string $id): array { - // Get the mapper first - $mapper = $this->getMapper($objectType); + // Get the mapper first + $mapper = $this->getMapper($objectType); return $mapper->formatFiles($mapper->getFiles($id)); } - /** - * Get all audit trails for a specific object - * - * @param string $objectType The type of object to get audit trails for - * @param string $id The id of the object to get audit trails for - * - * @return array The audit trails for the object - */ - public function getAuditTrail(string $objectType, string $id): array - { - // Get the mapper first - $mapper = $this->getMapper($objectType); - - // Get audit trails from OpenRegister - $auditTrails = $mapper->getAuditTrail($id); - - return $auditTrails; - } - - /** - * Lock an object - * - * @param string $objectType The type of object to lock - * @param string|int $id The id of the object to lock - * @param string|null $process Optional process identifier - * @param int|null $duration Lock duration in seconds (default: 1 hour) - * @return mixed The locked object - */ - public function lockObject(string $objectType, string|int $id, ?string $process = null, ?int $duration = 3600): mixed - { - $mapper = $this->getMapper($objectType); - return $mapper->lockObject($id, $process, $duration); - } - - /** - * Unlock an object - * - * @param string $objectType The type of object to unlock - * @param string|int $id The id of the object to unlock - * @return mixed The unlocked object - */ - public function unlockObject(string $objectType, string|int $id): mixed { - return $this->getMapper($objectType)->unlockObject($id); - } - - /** - * Check if an object is locked - * - * @param string $objectType The type of object to check - * @param string|int $id The id of the object to check - * @return bool True if object is locked, false otherwise - */ - public function isLocked(string $objectType, string|int $id): bool { - return $this->getMapper($objectType)->isLocked($id); - } - - /** - * Revert an object to a previous state - * - * @param string $objectType The type of object to revert - * @param string|int $id The id of the object to revert - * @param DateTime|string|null $until DateTime or AuditTrail ID to revert to - * @param bool $overwriteVersion Whether to overwrite the version or increment it - * @return mixed The reverted object - */ - public function revertObject(string $objectType, string|int $id, $until = null, bool $overwriteVersion = false): mixed { - return $this->getMapper($objectType)->revertObject($id, $until, $overwriteVersion); - } + /** + * Get all audit trails for a specific object + * + * @param string $objectType The type of object to get audit trails for + * @param string $id The id of the object to get audit trails for + * + * @return array The audit trails for the object + */ + public function getAuditTrail(string $objectType, string $id): array + { + // Get the mapper first + $mapper = $this->getMapper($objectType); + + // Get audit trails from OpenRegister + $auditTrails = $mapper->getAuditTrail($id); + + return $auditTrails; + } + + /** + * Lock an object + * + * @param string $objectType The type of object to lock + * @param string|int $id The id of the object to lock + * @param string|null $process Optional process identifier + * @param int|null $duration Lock duration in seconds (default: 1 hour) + * @return mixed The locked object + */ + public function lockObject(string $objectType, string|int $id, ?string $process = null, ?int $duration = 3600): mixed + { + $mapper = $this->getMapper($objectType); + return $mapper->lockObject($id, $process, $duration); + } + + /** + * Unlock an object + * + * @param string $objectType The type of object to unlock + * @param string|int $id The id of the object to unlock + * @return mixed The unlocked object + */ + public function unlockObject(string $objectType, string|int $id): mixed + { + return $this->getMapper($objectType)->unlockObject($id); + } + + /** + * Check if an object is locked + * + * @param string $objectType The type of object to check + * @param string|int $id The id of the object to check + * @return bool True if object is locked, false otherwise + */ + public function isLocked(string $objectType, string|int $id): bool + { + return $this->getMapper($objectType)->isLocked($id); + } + + /** + * Revert an object to a previous state + * + * @param string $objectType The type of object to revert + * @param string|int $id The id of the object to revert + * @param DateTime|string|null $until DateTime or AuditTrail ID to revert to + * @param bool $overwriteVersion Whether to overwrite the version or increment it + * @return mixed The reverted object + */ + public function revertObject(string $objectType, string|int $id, $until = null, bool $overwriteVersion = false): mixed + { + return $this->getMapper($objectType)->revertObject($id, $until, $overwriteVersion); + } } diff --git a/lib/Service/SearchService.php b/lib/Service/SearchService.php index aff06d5..29a86ba 100644 --- a/lib/Service/SearchService.php +++ b/lib/Service/SearchService.php @@ -11,376 +11,375 @@ class SearchService { public $client; - public const BASE_OBJECT = [ - 'database' => 'objects', - 'collection' => 'json', - ]; - - public function __construct( - private readonly IURLGenerator $urlGenerator, - ) { - $this->client = new Client(); - } - - public function mergeFacets(array $existingAggregation, array $newAggregation): array - { - $results = []; - $existingAggregationMapped = []; - $newAggregationMapped = []; - - foreach($existingAggregation as $value) { - $existingAggregationMapped[$value['_id']] = $value['count']; - } - - - foreach($newAggregation as $value) { - if(isset ($existingAggregationMapped[$value['_id']]) === true) { - $newAggregationMapped[$value['_id']] = $existingAggregationMapped[$value['_id']] + $value['count']; - } else { - $newAggregationMapped[$value['_id']] = $value['count']; - } - - } - - - foreach (array_merge(array_diff($existingAggregationMapped, $newAggregationMapped), array_diff($newAggregationMapped, $existingAggregationMapped)) as $key => $value) { - $results[] = ['_id' => $key, 'count' => $value]; - } - - return $results; - } - - private function mergeAggregations(?array $existingAggregations, ?array $newAggregations): array - { - if($newAggregations === null) { - return []; - } - + public const BASE_OBJECT = [ + 'database' => 'objects', + 'collection' => 'json', + ]; + + public function __construct( + private readonly IURLGenerator $urlGenerator, + ) { + $this->client = new Client(); + } + + public function mergeFacets(array $existingAggregation, array $newAggregation): array + { + $results = []; + $existingAggregationMapped = []; + $newAggregationMapped = []; + + foreach($existingAggregation as $value) { + $existingAggregationMapped[$value['_id']] = $value['count']; + } + + + foreach($newAggregation as $value) { + if(isset($existingAggregationMapped[$value['_id']]) === true) { + $newAggregationMapped[$value['_id']] = $existingAggregationMapped[$value['_id']] + $value['count']; + } else { + $newAggregationMapped[$value['_id']] = $value['count']; + } + + } + + + foreach (array_merge(array_diff($existingAggregationMapped, $newAggregationMapped), array_diff($newAggregationMapped, $existingAggregationMapped)) as $key => $value) { + $results[] = ['_id' => $key, 'count' => $value]; + } + + return $results; + } + + private function mergeAggregations(?array $existingAggregations, ?array $newAggregations): array + { + if($newAggregations === null) { + return []; + } + + + foreach($newAggregations as $key => $aggregation) { + if(isset($existingAggregations[$key]) === false) { + $existingAggregations[$key] = $aggregation; + } else { + $existingAggregations[$key] = $this->mergeFacets($existingAggregations[$key], $aggregation); + } + } + return $existingAggregations; + } + + public function sortResultArray(array $a, array $b): int + { + return $a['_score'] <=> $b['_score']; + } + + + /** + * + */ + public function search(array $parameters, array $elasticConfig, array $dbConfig, array $catalogi = []): array + { + + $localResults['results'] = []; + $localResults['facets'] = []; + + $totalResults = 0; + $limit = isset($parameters['.limit']) === true ? $parameters['.limit'] : 30; + $page = isset($parameters['.page']) === true ? $parameters['.page'] : 1; - foreach($newAggregations as $key => $aggregation) { - if(isset($existingAggregations[$key]) === false) { - $existingAggregations[$key] = $aggregation; - } else { - $existingAggregations[$key] = $this->mergeFacets($existingAggregations[$key], $aggregation); - } - } - return $existingAggregations; - } - - public function sortResultArray(array $a, array $b): int - { - return $a['_score'] <=> $b['_score']; - } - - - /** - * - */ - public function search(array $parameters, array $elasticConfig, array $dbConfig, array $catalogi = []): array - { - - $localResults['results'] = []; - $localResults['facets'] = []; - - $totalResults = 0; - $limit = isset($parameters['.limit']) === true ? $parameters['.limit'] : 30; - $page = isset($parameters['.page']) === true ? $parameters['.page'] : 1; - - if($elasticConfig['location'] !== '') { - $localResults = $this->elasticService->searchObject(filters: $parameters, config: $elasticConfig, totalResults: $totalResults,); - } - - $directory = $this->directoryService->listDirectory(limit: 1000); - -// $directory = $this->objectService->findObjects(filters: ['_schema' => 'directory'], config: $dbConfig); - - if(count($directory) === 0) { - $pages = (int) ceil($totalResults / $limit); - return [ - 'results' => $localResults['results'], - 'facets' => $localResults['facets'], - 'count' => count($localResults['results']), - 'limit' => $limit, - 'page' => $page, - 'pages' => $pages === 0 ? 1 : $pages, - 'total' => $totalResults - ]; - } - - $results = $localResults['results']; - $aggregations = $localResults['facets']; - - $searchEndpoints = []; - - - $promises = []; - foreach($directory as $instance) { - if( - $instance['default'] === false - || isset($parameters['.catalogi']) === true - && in_array($instance['catalogId'], $parameters['.catalogi']) === false - || $instance['search'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute(routeName:"opencatalogi.directory.index")) - ) { - continue; - } - $searchEndpoints[$instance['search']][] = $instance['catalogId']; - } - - unset($parameters['.catalogi']); - - foreach($searchEndpoints as $searchEndpoint => $catalogi) { - $parameters['_catalogi'] = $catalogi; - - - $promises[] = $this->client->getAsync($searchEndpoint, ['query' => $parameters]); - } - - $responses = Utils::settle($promises)->wait(); - - foreach($responses as $response) { - if($response['state'] === 'fulfilled') { - $responseData = json_decode( - json: $response['value']->getBody()->getContents(), - associative: true - ); - - $results = array_merge( - $results, - $responseData['results'] - ); - - usort($results, [$this, 'sortResultArray']); - - $aggregations = $this->mergeAggregations($aggregations, $responseData['facets']); - } - } - - $pages = (int) ceil($totalResults / $limit); - - return [ - 'results' => $results, - 'facets' => $aggregations, - 'count' => count($results), - 'limit' => $limit, - 'page' => $page, - 'pages' => $pages === 0 ? 1 : $pages, - 'total' => $totalResults - ]; - } - - /** - * This function adds a single query param to the given $vars array. ?$name=$value - * Will check if request query $name has [...] inside the parameter, like this: ?queryParam[$nameKey]=$value. - * Works recursive, so in case we have ?queryParam[$nameKey][$anotherNameKey][etc][etc]=$value. - * Also checks for queryParams ending on [] like: ?queryParam[$nameKey][] (or just ?queryParam[]), if this is the case - * this function will add given value to an array of [queryParam][$nameKey][] = $value or [queryParam][] = $value. - * If none of the above this function will just add [queryParam] = $value to $vars. - * - * @param array $vars The vars array we are going to store the query parameter in - * @param string $name The full $name of the query param, like this: ?$name=$value - * @param string $nameKey The full $name of the query param, unless it contains [] like: ?queryParam[$nameKey]=$value - * @param string $value The full $value of the query param, like this: ?$name=$value - * - * @return void - */ - private function recursiveRequestQueryKey(array &$vars, string $name, string $nameKey, string $value): void - { - $matchesCount = preg_match(pattern: '/(\[[^[\]]*])/', subject: $name, matches:$matches); - if ($matchesCount > 0) { - $key = $matches[0]; - $name = str_replace(search: $key, replace:'', subject: $name); - $key = trim(string: $key, characters: '[]'); - if (empty($key) === false) { - $vars[$nameKey] = ($vars[$nameKey] ?? []); - $this->recursiveRequestQueryKey( - vars: $vars[$nameKey], - name: $name, - nameKey: $key, - value: $value - ); - } else { - $vars[$nameKey][] = $value; - } - } else { - $vars[$nameKey] = $value; - } - - }//end recursiveRequestQueryKey() - - /** - * This function creates a mongodb filter array. - * - * Also unsets _search in filters ! - * - * @param array $filters Query parameters from request. - * @param array $fieldsToSearch Database field names to filter/search on. - * - * @return array $filters - */ - public function createMongoDBSearchFilter(array $filters, array $fieldsToSearch): array - { + if($elasticConfig['location'] !== '') { + $localResults = $this->elasticService->searchObject(filters: $parameters, config: $elasticConfig, totalResults: $totalResults, ); + } + + $directory = $this->directoryService->listDirectory(limit: 1000); + + // $directory = $this->objectService->findObjects(filters: ['_schema' => 'directory'], config: $dbConfig); + + if(count($directory) === 0) { + $pages = (int) ceil($totalResults / $limit); + return [ + 'results' => $localResults['results'], + 'facets' => $localResults['facets'], + 'count' => count($localResults['results']), + 'limit' => $limit, + 'page' => $page, + 'pages' => $pages === 0 ? 1 : $pages, + 'total' => $totalResults + ]; + } + + $results = $localResults['results']; + $aggregations = $localResults['facets']; + + $searchEndpoints = []; + + + $promises = []; + foreach($directory as $instance) { + if($instance['default'] === false + || isset($parameters['.catalogi']) === true + && in_array($instance['catalogId'], $parameters['.catalogi']) === false + || $instance['search'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute(routeName:"opencatalogi.directory.index")) + ) { + continue; + } + $searchEndpoints[$instance['search']][] = $instance['catalogId']; + } + + unset($parameters['.catalogi']); + + foreach($searchEndpoints as $searchEndpoint => $catalogi) { + $parameters['_catalogi'] = $catalogi; + + + $promises[] = $this->client->getAsync($searchEndpoint, ['query' => $parameters]); + } + + $responses = Utils::settle($promises)->wait(); + + foreach($responses as $response) { + if($response['state'] === 'fulfilled') { + $responseData = json_decode( + json: $response['value']->getBody()->getContents(), + associative: true + ); + + $results = array_merge( + $results, + $responseData['results'] + ); + + usort($results, [$this, 'sortResultArray']); + + $aggregations = $this->mergeAggregations($aggregations, $responseData['facets']); + } + } + + $pages = (int) ceil($totalResults / $limit); + + return [ + 'results' => $results, + 'facets' => $aggregations, + 'count' => count($results), + 'limit' => $limit, + 'page' => $page, + 'pages' => $pages === 0 ? 1 : $pages, + 'total' => $totalResults + ]; + } + + /** + * This function adds a single query param to the given $vars array. ?$name=$value + * Will check if request query $name has [...] inside the parameter, like this: ?queryParam[$nameKey]=$value. + * Works recursive, so in case we have ?queryParam[$nameKey][$anotherNameKey][etc][etc]=$value. + * Also checks for queryParams ending on [] like: ?queryParam[$nameKey][] (or just ?queryParam[]), if this is the case + * this function will add given value to an array of [queryParam][$nameKey][] = $value or [queryParam][] = $value. + * If none of the above this function will just add [queryParam] = $value to $vars. + * + * @param array $vars The vars array we are going to store the query parameter in + * @param string $name The full $name of the query param, like this: ?$name=$value + * @param string $nameKey The full $name of the query param, unless it contains [] like: ?queryParam[$nameKey]=$value + * @param string $value The full $value of the query param, like this: ?$name=$value + * + * @return void + */ + private function recursiveRequestQueryKey(array &$vars, string $name, string $nameKey, string $value): void + { + $matchesCount = preg_match(pattern: '/(\[[^[\]]*])/', subject: $name, matches:$matches); + if ($matchesCount > 0) { + $key = $matches[0]; + $name = str_replace(search: $key, replace:'', subject: $name); + $key = trim(string: $key, characters: '[]'); + if (empty($key) === false) { + $vars[$nameKey] = ($vars[$nameKey] ?? []); + $this->recursiveRequestQueryKey( + vars: $vars[$nameKey], + name: $name, + nameKey: $key, + value: $value + ); + } else { + $vars[$nameKey][] = $value; + } + } else { + $vars[$nameKey] = $value; + } + + }//end recursiveRequestQueryKey() + + /** + * This function creates a mongodb filter array. + * + * Also unsets _search in filters ! + * + * @param array $filters Query parameters from request. + * @param array $fieldsToSearch Database field names to filter/search on. + * + * @return array $filters + */ + public function createMongoDBSearchFilter(array $filters, array $fieldsToSearch): array + { + if (isset($filters['_search']) === true) { + $searchRegex = ['$regex' => $filters['_search'], '$options' => 'i']; + $filters['$or'] = []; + + foreach ($fieldsToSearch as $field) { + $filters['$or'][] = [$field => $searchRegex]; + } + + unset($filters['_search']); + } + + foreach ($filters as $field => $value) { + if ($value === 'IS NOT NULL') { + $filters[$field] = ['$ne' => null]; + } + if ($value === 'IS NULL') { + $filters[$field] = ['$eq' => null]; + } + } + + return $filters; + + }//end createMongoDBSearchFilter() + + /** + * This function creates mysql search conditions based on given filters from request. + * + * @param array $filters Query parameters from request. + * @param array $fieldsToSearch Fields to search on in sql. + * + * @return array $searchConditions + */ + public function createMySQLSearchConditions(array $filters, array $fieldsToSearch): array + { + $searchConditions = []; if (isset($filters['_search']) === true) { - $searchRegex = ['$regex' => $filters['_search'], '$options' => 'i']; - $filters['$or'] = []; - - foreach ($fieldsToSearch as $field) { - $filters['$or'][] = [$field => $searchRegex]; - } - - unset($filters['_search']); - } - - foreach ($filters as $field => $value) { - if ($value === 'IS NOT NULL') { - $filters[$field] = ['$ne' => null]; - } - if ($value === 'IS NULL') { - $filters[$field] = ['$eq' => null]; - } - } - - return $filters; - - }//end createMongoDBSearchFilter() - - /** - * This function creates mysql search conditions based on given filters from request. - * - * @param array $filters Query parameters from request. - * @param array $fieldsToSearch Fields to search on in sql. - * - * @return array $searchConditions - */ - public function createMySQLSearchConditions(array $filters, array $fieldsToSearch): array - { - $searchConditions = []; - if (isset($filters['_search']) === true) { - foreach ($fieldsToSearch as $field) { - $searchConditions[] = "LOWER($field) LIKE :search"; - } - } - - return $searchConditions; - - }//end createMongoDBSearchFilter() - - /** - * This function unsets all keys starting with _ from filters. - * - * @param array $filters Query parameters from request. - * - * @return array $filters - */ - public function unsetSpecialQueryParams(array $filters): array - { + foreach ($fieldsToSearch as $field) { + $searchConditions[] = "LOWER($field) LIKE :search"; + } + } + + return $searchConditions; + + }//end createMongoDBSearchFilter() + + /** + * This function unsets all keys starting with _ from filters. + * + * @param array $filters Query parameters from request. + * + * @return array $filters + */ + public function unsetSpecialQueryParams(array $filters): array + { foreach ($filters as $key => $value) { if (str_starts_with($key, '_')) { unset($filters[$key]); } } - return $filters; - - }//end createMongoDBSearchFilter() - - /** - * This function creates mysql search parameters based on given filters from request. - * - * @param array $filters Query parameters from request. - * - * @return array $searchParams - */ - public function createMySQLSearchParams(array $filters): array - { - $searchParams = []; - if (isset($filters['_search']) === true) { - $searchParams['search'] = '%' . strtolower($filters['_search']) . '%'; - } - - return $searchParams; - - }//end createMongoDBSearchFilter() - - /** - * This function creates an sort array based on given order param from request. - * - * @param array $filters Query parameters from request. - * - * @return array $sort - */ - public function createSortForMySQL(array $filters): array - { - $sort = []; - if (isset($filters['_order']) && is_array($filters['_order'])) { - foreach ($filters['_order'] as $field => $direction) { - $direction = strtoupper($direction) === 'DESC' ? 'DESC' : 'ASC'; - $sort[$field] = $direction; - } - } - - return $sort; - - }//end createSortArrayFromParams() - - /** - * This function creates an sort array based on given order param from request. - * - * @todo Not functional yet. Needs to be fixed (see PublicationsController->index). - * - * @param array $filters Query parameters from request. - * - * @return array $sort - */ - public function createSortForMongoDB(array $filters): array - { - $sort = []; - if (isset($filters['_order']) && is_array($filters['_order'])) { - foreach ($filters['_order'] as $field => $direction) { - $sort[$field] = strtoupper($direction) === 'DESC' ? -1 : 1; - } - } - - return $sort; - - }//end createSortForMongoDB() - - /** - * Parses the request query string and returns it as an array of queries. - * - * @param string $queryString The input query string from the request. - * - * @return array The resulting array of query parameters. - */ - public function parseQueryString (string $queryString = ''): array - { - $pairs = explode(separator: '&', string: $queryString); - - foreach($pairs as $pair) { - $kvpair = explode(separator: '=', string: $pair); - - $key = urldecode(string: $kvpair[0]); - $value = ''; - if(count(value: $kvpair) === 2) { - $value = urldecode(string: $kvpair[1]); - } - - $this->recursiveRequestQueryKey( - vars: $vars, - name: $key, - nameKey: substr( - string: $key, - offset: 0, - length: strpos( - haystack: $key, - needle: '[' - ) - ), - value: $value - ); - } - - - return $vars; - } + return $filters; + + }//end createMongoDBSearchFilter() + + /** + * This function creates mysql search parameters based on given filters from request. + * + * @param array $filters Query parameters from request. + * + * @return array $searchParams + */ + public function createMySQLSearchParams(array $filters): array + { + $searchParams = []; + if (isset($filters['_search']) === true) { + $searchParams['search'] = '%' . strtolower($filters['_search']) . '%'; + } + + return $searchParams; + + }//end createMongoDBSearchFilter() + + /** + * This function creates an sort array based on given order param from request. + * + * @param array $filters Query parameters from request. + * + * @return array $sort + */ + public function createSortForMySQL(array $filters): array + { + $sort = []; + if (isset($filters['_order']) && is_array($filters['_order'])) { + foreach ($filters['_order'] as $field => $direction) { + $direction = strtoupper($direction) === 'DESC' ? 'DESC' : 'ASC'; + $sort[$field] = $direction; + } + } + + return $sort; + + }//end createSortArrayFromParams() + + /** + * This function creates an sort array based on given order param from request. + * + * @todo Not functional yet. Needs to be fixed (see PublicationsController->index). + * + * @param array $filters Query parameters from request. + * + * @return array $sort + */ + public function createSortForMongoDB(array $filters): array + { + $sort = []; + if (isset($filters['_order']) && is_array($filters['_order'])) { + foreach ($filters['_order'] as $field => $direction) { + $sort[$field] = strtoupper($direction) === 'DESC' ? -1 : 1; + } + } + + return $sort; + + }//end createSortForMongoDB() + + /** + * Parses the request query string and returns it as an array of queries. + * + * @param string $queryString The input query string from the request. + * + * @return array The resulting array of query parameters. + */ + public function parseQueryString(string $queryString = ''): array + { + $pairs = explode(separator: '&', string: $queryString); + + foreach($pairs as $pair) { + $kvpair = explode(separator: '=', string: $pair); + + $key = urldecode(string: $kvpair[0]); + $value = ''; + if(count(value: $kvpair) === 2) { + $value = urldecode(string: $kvpair[1]); + } + + $this->recursiveRequestQueryKey( + vars: $vars, + name: $key, + nameKey: substr( + string: $key, + offset: 0, + length: strpos( + haystack: $key, + needle: '[' + ) + ), + value: $value + ); + } + + + return $vars; + } } diff --git a/lib/Settings/LarpingAppAdmin.php b/lib/Settings/LarpingAppAdmin.php index 645f886..50554bb 100644 --- a/lib/Settings/LarpingAppAdmin.php +++ b/lib/Settings/LarpingAppAdmin.php @@ -6,11 +6,13 @@ use OCP\IL10N; use OCP\Settings\ISettings; -class LarpingAppAdmin implements ISettings { +class LarpingAppAdmin implements ISettings +{ private IL10N $l; private IConfig $config; - public function __construct(IConfig $config, IL10N $l) { + public function __construct(IConfig $config, IL10N $l) + { $this->config = $config; $this->l = $l; } @@ -18,7 +20,8 @@ public function __construct(IConfig $config, IL10N $l) { /** * @return TemplateResponse */ - public function getForm() { + public function getForm() + { $parameters = [ 'mySetting' => $this->config->getSystemValue('larpingapp_setting', true), ]; @@ -26,7 +29,8 @@ public function getForm() { return new TemplateResponse('larpingapp', 'settings/admin', $parameters, 'admin'); } - public function getSection() { + public function getSection() + { return 'larpingapp'; } @@ -37,7 +41,8 @@ public function getSection() { * * E.g.: 70 */ - public function getPriority() { + public function getPriority() + { return 10; } } \ No newline at end of file From f840b1194ec84acbb3a626296ae456ee2f3c3a3d Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Mon, 17 Feb 2025 14:53:35 +0100 Subject: [PATCH 02/17] Style fixes --- lib/Db/Ability.php | 105 ++++++----- lib/Db/AbilityMapper.php | 105 ++++++----- lib/Db/Character.php | 140 ++++++-------- lib/Db/CharacterMapper.php | 98 ++++++---- lib/Db/Condition.php | 95 ++++++---- lib/Db/ConditionMapper.php | 98 ++++++---- lib/Db/Effect.php | 98 +++++----- lib/Db/EffectMapper.php | 98 ++++++---- lib/Db/Event.php | 101 +++++----- lib/Db/Item.php | 96 ++++++---- lib/Db/ItemMapper.php | 98 ++++++---- lib/Db/Player.php | 122 ++++++------ lib/Db/PlayerMapper.php | 98 ++++++---- lib/Db/Setting.php | 123 ++++++------ lib/Db/SettingMapper.php | 98 ++++++---- lib/Db/Skill.php | 107 +++++------ lib/Db/Template.php | 90 +++++---- lib/Db/TemplateMapper.php | 61 +++++- lib/Migration/Version0Date20240826193657.php | 185 +++++-------------- lib/Migration/Version0Date20241015141612.php | 65 +++++-- lib/Sections/LarpingAppAdmin.php | 72 +++++++- lib/Settings/LarpingAppAdmin.php | 88 ++++++--- 22 files changed, 1250 insertions(+), 991 deletions(-) diff --git a/lib/Db/Ability.php b/lib/Db/Ability.php index 95a20a5..ff25c58 100644 --- a/lib/Db/Ability.php +++ b/lib/Db/Ability.php @@ -1,77 +1,84 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getDescription() + * @method void setDescription(string $description) + */ class Ability extends Entity implements JsonSerializable { + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $description; - protected ?string $name = null; - protected ?string $description = null; - protected ?int $base = 0; - protected ?bool $allowedNegative = false; + /** + * Constructor to set the defaults + */ public function __construct() { - $this->addType(fieldName: 'name', type: 'string'); - $this->addType(fieldName: 'description', type: 'string'); - $this->addType(fieldName: 'base', type: 'string'); - $this->addType(fieldName: 'allowedNegative', type: 'boolean'); - + $this->addType('name', 'string'); + $this->addType('description', 'string'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'description' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - $array = [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'base' => $this->base, - 'allowedNegative' => $this->allowedNegative, - ]; - - $jsonFields = $this->getJsonFields(); - - foreach ($array as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === null) { - $array[$key] = []; - } + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; } - - return $array; + return $data; } } diff --git a/lib/Db/AbilityMapper.php b/lib/Db/AbilityMapper.php index a3c25aa..58d513a 100644 --- a/lib/Db/AbilityMapper.php +++ b/lib/Db/AbilityMapper.php @@ -1,83 +1,94 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; -use OCA\LarpingApp\Db\Ability; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\QBMapper; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + * @package OCA\LarpingApp\Db + */ class AbilityMapper extends QBMapper { /** - * The name of the database table for abilities - * - * @var string - * @psalm-var string - * @phpstan-var string + * @param IDBConnection $db Database connection */ - private const TABLE_NAME = 'larpingapp_abilities'; - public function __construct(IDBConnection $db) { - parent::__construct($db, 'larpingapp_abilities'); + parent::__construct($db, 'larpingapp_abilities', Ability::class); } + /** + * Find an ability by ID + * + * @param int $id The ability ID + * @return Ability + * @throws \OCP\AppFramework\Db\DoesNotExistException + * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException + */ public function find(int $id): Ability { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_abilities') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); - - return $this->findEntity(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); + return $this->findEntity($qb); } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + /** + * Find all abilities for a user + * + * @param string $userId The user ID + * @return Ability[] + */ + public function findAll(string $userId): array { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_abilities') - ->setMaxResults($limit) - ->setFirstResult($offset); - - foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } - } - - if (!empty($searchConditions)) { - $qb->andWhere('(' . implode(' OR ', $searchConditions) . ')'); - foreach ($searchParams as $param => $value) { - $qb->setParameter($param, $value); - } - } - - return $this->findEntities(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId))); + + return $this->findEntities($qb); } - public function createFromArray(array $object): Ability + /** + * Create a new ability from array data + * + * @param array $data The ability data + * @return Ability + */ + public function createFromArray(array $data): Ability { $ability = new Ability(); - $ability->hydrate(object: $object); - return $this->insert(entity: $ability); + foreach ($data as $key => $value) { + $ability->$key = $value; + } + return $this->insert($ability); } - public function updateFromArray(int $id, array $object): Ability + /** + * Update an ability from array data + * + * @param int $id The ability ID + * @param array $data The updated ability data + * @return Ability + */ + public function updateFromArray(int $id, array $data): Ability { $ability = $this->find($id); - $ability->hydrate($object); - + foreach ($data as $key => $value) { + $ability->$key = $value; + } return $this->update($ability); } } diff --git a/lib/Db/Character.php b/lib/Db/Character.php index 3b3e079..a33d328 100644 --- a/lib/Db/Character.php +++ b/lib/Db/Character.php @@ -1,114 +1,84 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getDescription() + * @method void setDescription(string $description) + */ class Character extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $ocName = null; - protected ?string $description = null; - protected ?string $background = null; - protected ?string $itemsAndMoney = null; - protected ?string $notice = null; - protected ?string $faith = null; - protected ?string $slNotesPublic = null; - protected ?string $slNotesPrivate = null; - protected ?string $card = null; - protected ?array $stats = []; - protected ?int $gold = null; - protected ?int $silver = null; - protected ?int $copper = null; - protected ?array $events = []; - protected ?array $skills = []; - protected ?array $items = []; - protected ?array $conditions = null; - protected ?string $type = 'player'; - protected ?string $approved = 'no'; + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $description; + /** + * Constructor to set the defaults + */ public function __construct() { $this->addType('name', 'string'); - $this->addType('ocName', 'string'); $this->addType('description', 'string'); - $this->addType('background', 'string'); - $this->addType('itemsAndMoney', 'string'); - $this->addType('notice', 'string'); - $this->addType('faith', 'string'); - $this->addType('slNotesPublic', 'string'); - $this->addType('slNotesPrivate', 'string'); - $this->addType('card', 'string'); - $this->addType('stats', 'json'); - $this->addType('gold', 'integer'); - $this->addType('silver', 'integer'); - $this->addType('copper', 'integer'); - $this->addType('events', 'json'); - $this->addType('skills', 'json'); - $this->addType('items', 'json'); - $this->addType('conditions', 'json'); - $this->addType('type', 'string'); - $this->addType('approved', 'string'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'description' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'ocName' => $this->ocName, - 'description' => $this->description, - 'background' => $this->background, - 'itemsAndMoney' => $this->itemsAndMoney, - 'notice' => $this->notice, - 'faith' => $this->faith, - 'slNotesPublic' => $this->slNotesPublic, - 'slNotesPrivate' => $this->slNotesPrivate, - 'card' => $this->card, - 'stats' => $this->stats, - 'gold' => $this->gold, - 'silver' => $this->silver, - 'copper' => $this->copper, - 'events' => $this->events, - 'skills' => $this->skills, - 'items' => $this->items, - 'conditions' => $this->conditions, - 'type' => $this->type, - 'approved' => $this->approved, - ]; + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; + } + return $data; } } diff --git a/lib/Db/CharacterMapper.php b/lib/Db/CharacterMapper.php index 8a5a8e4..19395ba 100644 --- a/lib/Db/CharacterMapper.php +++ b/lib/Db/CharacterMapper.php @@ -1,5 +1,13 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use OCA\LarpingApp\Db\Character; @@ -8,67 +16,81 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + * @package OCA\LarpingApp\Db + */ class CharacterMapper extends QBMapper { + /** + * @param IDBConnection $db Database connection + */ public function __construct(IDBConnection $db) { - parent::__construct($db, 'larpingapp_characters'); + parent::__construct($db, 'larpingapp_characters', Character::class); } + /** + * Find a character by ID + * + * @param int $id The character ID + * @return Character + * @throws \OCP\AppFramework\Db\DoesNotExistException + * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException + */ public function find(int $id): Character { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_characters') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); - - return $this->findEntity(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); + return $this->findEntity($qb); } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + /** + * Find all characters for a user + * + * @param string $userId The user ID + * @return Character[] + */ + public function findAll(string $userId): array { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_characters') - ->setMaxResults($limit) - ->setFirstResult($offset); - - foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } - } - - if (!empty($searchConditions)) { - $qb->andWhere('(' . implode(' OR ', $searchConditions) . ')'); - foreach ($searchParams as $param => $value) { - $qb->setParameter($param, $value); - } - } - - return $this->findEntities(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId))); + + return $this->findEntities($qb); } - public function createFromArray(array $object): Character + /** + * Create a new character from array data + * + * @param array $data The character data + * @return Character + */ + public function createFromArray(array $data): Character { $character = new Character(); - $character->hydrate(object: $object); - return $this->insert(entity: $character); + foreach ($data as $key => $value) { + $character->$key = $value; + } + return $this->insert($character); } - public function updateFromArray(int $id, array $object): Character + /** + * Update a character from array data + * + * @param int $id The character ID + * @param array $data The updated character data + * @return Character + */ + public function updateFromArray(int $id, array $data): Character { $character = $this->find($id); - $character->hydrate($object); - + foreach ($data as $key => $value) { + $character->$key = $value; + } return $this->update($character); } } diff --git a/lib/Db/Condition.php b/lib/Db/Condition.php index 5156b73..011f0fc 100644 --- a/lib/Db/Condition.php +++ b/lib/Db/Condition.php @@ -1,69 +1,84 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getDescription() + * @method void setDescription(string $description) + */ class Condition extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?string $effect = null; - protected ?array $effects = []; - protected ?bool $unique = false; + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $description; + /** + * Constructor to set the defaults + */ public function __construct() { $this->addType('name', 'string'); $this->addType('description', 'string'); - $this->addType('effect', 'string'); - $this->addType('effects', 'array'); - $this->addType('unique', 'boolean'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'description' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'effect' => $this->effect, - 'effects' => $this->effects, - 'unique' => $this->unique, - ]; + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; + } + return $data; } } \ No newline at end of file diff --git a/lib/Db/ConditionMapper.php b/lib/Db/ConditionMapper.php index 99f4251..757493b 100644 --- a/lib/Db/ConditionMapper.php +++ b/lib/Db/ConditionMapper.php @@ -1,5 +1,13 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use OCA\LarpingApp\Db\Condition; @@ -8,67 +16,81 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + * @package OCA\LarpingApp\Db + */ class ConditionMapper extends QBMapper { + /** + * @param IDBConnection $db Database connection + */ public function __construct(IDBConnection $db) { - parent::__construct($db, 'larpingapp_conditions'); + parent::__construct($db, 'larpingapp_conditions', Condition::class); } + /** + * Find a condition by ID + * + * @param int $id The condition ID + * @return Condition + * @throws \OCP\AppFramework\Db\DoesNotExistException + * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException + */ public function find(int $id): Condition { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_conditions') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); - - return $this->findEntity(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); + return $this->findEntity($qb); } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + /** + * Find all conditions for a user + * + * @param string $userId The user ID + * @return Condition[] + */ + public function findAll(string $userId): array { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_conditions') - ->setMaxResults($limit) - ->setFirstResult($offset); - - foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } - } - - if (!empty($searchConditions)) { - $qb->andWhere('(' . implode(' OR ', $searchConditions) . ')'); - foreach ($searchParams as $param => $value) { - $qb->setParameter($param, $value); - } - } - - return $this->findEntities(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId))); + + return $this->findEntities($qb); } - public function createFromArray(array $object): Condition + /** + * Create a new condition from array data + * + * @param array $data The condition data + * @return Condition + */ + public function createFromArray(array $data): Condition { $condition = new Condition(); - $condition->hydrate(object: $object); - return $this->insert(entity: $condition); + foreach ($data as $key => $value) { + $condition->$key = $value; + } + return $this->insert($condition); } - public function updateFromArray(int $id, array $object): Condition + /** + * Update a condition from array data + * + * @param int $id The condition ID + * @param array $data The updated condition data + * @return Condition + */ + public function updateFromArray(int $id, array $data): Condition { $condition = $this->find($id); - $condition->hydrate($object); - + foreach ($data as $key => $value) { + $condition->$key = $value; + } return $this->update($condition); } } diff --git a/lib/Db/Effect.php b/lib/Db/Effect.php index bf68f13..1face37 100644 --- a/lib/Db/Effect.php +++ b/lib/Db/Effect.php @@ -1,72 +1,84 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getDescription() + * @method void setDescription(string $description) + */ class Effect extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?string $statId = null; - protected ?int $modifier = null; - protected ?string $modification = 'positive'; - protected ?string $cumulative = 'non-cumulative'; + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $description; + /** + * Constructor to set the defaults + */ public function __construct() { $this->addType('name', 'string'); $this->addType('description', 'string'); - $this->addType('statId', 'string'); - $this->addType('modifier', 'integer'); - $this->addType('modification', 'string'); - $this->addType('cumulative', 'string'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'description' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'statId' => $this->statId, - 'modifier' => $this->modifier, - 'modification' => $this->modification, - 'cumulative' => $this->cumulative, - ]; + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; + } + return $data; } } \ No newline at end of file diff --git a/lib/Db/EffectMapper.php b/lib/Db/EffectMapper.php index beca6c0..6ce0416 100644 --- a/lib/Db/EffectMapper.php +++ b/lib/Db/EffectMapper.php @@ -1,5 +1,13 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use OCA\LarpingApp\Db\Effect; @@ -8,67 +16,81 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + * @package OCA\LarpingApp\Db + */ class EffectMapper extends QBMapper { + /** + * @param IDBConnection $db Database connection + */ public function __construct(IDBConnection $db) { - parent::__construct($db, 'larpingapp_effects'); + parent::__construct($db, 'larpingapp_effects', Effect::class); } + /** + * Find an effect by ID + * + * @param int $id The effect ID + * @return Effect + * @throws \OCP\AppFramework\Db\DoesNotExistException + * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException + */ public function find(int $id): Effect { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_effects') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); - - return $this->findEntity(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); + return $this->findEntity($qb); } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + /** + * Find all effects for a user + * + * @param string $userId The user ID + * @return Effect[] + */ + public function findAll(string $userId): array { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_effects') - ->setMaxResults($limit) - ->setFirstResult($offset); - - foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } - } - - if (!empty($searchConditions)) { - $qb->andWhere('(' . implode(' OR ', $searchConditions) . ')'); - foreach ($searchParams as $param => $value) { - $qb->setParameter($param, $value); - } - } - - return $this->findEntities(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId))); + + return $this->findEntities($qb); } - public function createFromArray(array $object): Effect + /** + * Create a new effect from array data + * + * @param array $data The effect data + * @return Effect + */ + public function createFromArray(array $data): Effect { $effect = new Effect(); - $effect->hydrate(object: $object); - return $this->insert(entity: $effect); + foreach ($data as $key => $value) { + $effect->$key = $value; + } + return $this->insert($effect); } - public function updateFromArray(int $id, array $object): Effect + /** + * Update an effect from array data + * + * @param int $id The effect ID + * @param array $data The updated effect data + * @return Effect + */ + public function updateFromArray(int $id, array $data): Effect { $effect = $this->find($id); - $effect->hydrate($object); - + foreach ($data as $key => $value) { + $effect->$key = $value; + } return $this->update($effect); } } diff --git a/lib/Db/Event.php b/lib/Db/Event.php index 0f8fe2a..8534f82 100644 --- a/lib/Db/Event.php +++ b/lib/Db/Event.php @@ -1,75 +1,84 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getDescription() + * @method void setDescription(string $description) + */ class Event extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?array $players = []; - protected ?array $effects = []; - protected ?string $startDate = null; - protected ?string $endDate = null; - protected ?string $location = null; + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $description; + /** + * Constructor to set the defaults + */ public function __construct() { $this->addType('name', 'string'); $this->addType('description', 'string'); - $this->addType('players', 'array'); - $this->addType('effects', 'json'); - $this->addType('startDate', 'string'); - $this->addType('endDate', 'string'); - $this->addType('location', 'string'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'description' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'players' => $this->players, - 'effects' => $this->effects, - 'startDate' => $this->startDate, - 'endDate' => $this->endDate, - 'location' => $this->location, - ]; + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; + } + return $data; } } \ No newline at end of file diff --git a/lib/Db/Item.php b/lib/Db/Item.php index fede777..ed9c340 100644 --- a/lib/Db/Item.php +++ b/lib/Db/Item.php @@ -1,69 +1,83 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; -use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getDescription() + * @method void setDescription(string $description) + */ class Item extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?string $effect = null; - protected ?array $effects = null; - protected ?bool $unique = true; + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $description; + /** + * Constructor to set the defaults + */ public function __construct() { $this->addType('name', 'string'); $this->addType('description', 'string'); - $this->addType('effect', 'string'); - $this->addType('effects', 'json'); - $this->addType('unique', 'boolean'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'description' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'effect' => $this->effect, - 'effects' => $this->effects, - 'unique' => $this->unique, - ]; + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; + } + return $data; } } \ No newline at end of file diff --git a/lib/Db/ItemMapper.php b/lib/Db/ItemMapper.php index e7f0b90..d089091 100644 --- a/lib/Db/ItemMapper.php +++ b/lib/Db/ItemMapper.php @@ -1,5 +1,13 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use OCA\LarpingApp\Db\Item; @@ -8,67 +16,81 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + * @package OCA\LarpingApp\Db + */ class ItemMapper extends QBMapper { + /** + * @param IDBConnection $db Database connection + */ public function __construct(IDBConnection $db) { - parent::__construct($db, 'larpingapp_items'); + parent::__construct($db, 'larpingapp_items', Item::class); } + /** + * Find an item by ID + * + * @param int $id The item ID + * @return Item + * @throws \OCP\AppFramework\Db\DoesNotExistException + * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException + */ public function find(int $id): Item { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_items') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); - - return $this->findEntity(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); + return $this->findEntity($qb); } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + /** + * Find all items for a user + * + * @param string $userId The user ID + * @return Item[] + */ + public function findAll(string $userId): array { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_items') - ->setMaxResults($limit) - ->setFirstResult($offset); - - foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } - } - - if (!empty($searchConditions)) { - $qb->andWhere('(' . implode(' OR ', $searchConditions) . ')'); - foreach ($searchParams as $param => $value) { - $qb->setParameter($param, $value); - } - } - - return $this->findEntities(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId))); + + return $this->findEntities($qb); } - public function createFromArray(array $object): Item + /** + * Create a new item from array data + * + * @param array $data The item data + * @return Item + */ + public function createFromArray(array $data): Item { $item = new Item(); - $item->hydrate(object: $object); - return $this->insert(entity: $item); + foreach ($data as $key => $value) { + $item->$key = $value; + } + return $this->insert($item); } - public function updateFromArray(int $id, array $object): Item + /** + * Update an item from array data + * + * @param int $id The item ID + * @param array $data The updated item data + * @return Item + */ + public function updateFromArray(int $id, array $data): Item { $item = $this->find($id); - $item->hydrate($object); - + foreach ($data as $key => $value) { + $item->$key = $value; + } return $this->update($item); } } diff --git a/lib/Db/Player.php b/lib/Db/Player.php index 43de612..0f57d03 100644 --- a/lib/Db/Player.php +++ b/lib/Db/Player.php @@ -1,92 +1,84 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getDescription() + * @method void setDescription(string $description) + */ class Player extends Entity implements JsonSerializable { - - protected ?string $name = null; - protected ?string $summary = null; - protected ?string $description = null; - protected ?string $image = null; - protected ?string $search = null; - - protected bool $listed = false; - protected ?string $organisation = null; - protected ?array $metadata = null; - + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $description; + + /** + * Constructor to set the defaults + */ public function __construct() { - $this->addType(fieldName: 'name', type: 'string'); - $this->addType(fieldName: 'summary', type: 'string'); - $this->addType(fieldName: 'description', type: 'string'); - $this->addType(fieldName: 'image', type: 'string'); - $this->addType(fieldName: 'search', type: 'string'); - $this->addType(fieldName: 'listed', type: 'boolean'); - $this->addType(fieldName: 'organisation', type: 'string'); - $this->addType(fieldName: 'metadata', type: 'json'); - + $this->addType('name', 'string'); + $this->addType('description', 'string'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'description' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - $array = [ - 'id' => $this->id, - 'name' => $this->name, - 'summary' => $this->summary, - 'description' => $this->description, - 'image' => $this->image, - 'search' => $this->search, - 'listed' => $this->listed, - 'metadata' => $this->metadata, - 'organisation'=> $this->organisation, - - ]; - - $jsonFields = $this->getJsonFields(); - - foreach ($array as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === null) { - $array[$key] = []; - } + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; } - - return $array; + return $data; } } diff --git a/lib/Db/PlayerMapper.php b/lib/Db/PlayerMapper.php index 7855e64..6e2cc38 100644 --- a/lib/Db/PlayerMapper.php +++ b/lib/Db/PlayerMapper.php @@ -1,5 +1,13 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use OCA\LarpingApp\Db\Player; @@ -8,67 +16,81 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + * @package OCA\LarpingApp\Db + */ class PlayerMapper extends QBMapper { + /** + * @param IDBConnection $db Database connection + */ public function __construct(IDBConnection $db) { - parent::__construct($db, 'larpingapp_players'); + parent::__construct($db, 'larpingapp_players', Player::class); } + /** + * Find a player by ID + * + * @param int $id The player ID + * @return Player + * @throws \OCP\AppFramework\Db\DoesNotExistException + * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException + */ public function find(int $id): Player { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_players') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); - - return $this->findEntity(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); + return $this->findEntity($qb); } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + /** + * Find all players for a user + * + * @param string $userId The user ID + * @return Player[] + */ + public function findAll(string $userId): array { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_players') - ->setMaxResults($limit) - ->setFirstResult($offset); - - foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } - } - - if (!empty($searchConditions)) { - $qb->andWhere('(' . implode(' OR ', $searchConditions) . ')'); - foreach ($searchParams as $param => $value) { - $qb->setParameter($param, $value); - } - } - - return $this->findEntities(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId))); + + return $this->findEntities($qb); } - public function createFromArray(array $object): Player + /** + * Create a new player from array data + * + * @param array $data The player data + * @return Player + */ + public function createFromArray(array $data): Player { $player = new Player(); - $player->hydrate(object: $object); - return $this->insert(entity: $player); + foreach ($data as $key => $value) { + $player->$key = $value; + } + return $this->insert($player); } - public function updateFromArray(int $id, array $object): Player + /** + * Update a player from array data + * + * @param int $id The player ID + * @param array $data The updated player data + * @return Player + */ + public function updateFromArray(int $id, array $data): Player { $player = $this->find($id); - $player->hydrate($object); - + foreach ($data as $key => $value) { + $player->$key = $value; + } return $this->update($player); } } diff --git a/lib/Db/Setting.php b/lib/Db/Setting.php index 48bec93..0af5a07 100644 --- a/lib/Db/Setting.php +++ b/lib/Db/Setting.php @@ -1,92 +1,83 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; -use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getValue() + * @method void setValue(string $value) + */ class Setting extends Entity implements JsonSerializable { - - protected ?string $title = null; - protected ?string $summary = null; - protected ?string $description = null; - protected ?string $image = null; - protected ?string $search = null; - - protected bool $listed = false; - protected ?string $organisation = null; - protected ?array $metadata = null; - + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $value; + + /** + * Constructor to set the defaults + */ public function __construct() { - $this->addType(fieldName: 'title', type: 'string'); - $this->addType(fieldName: 'summary', type: 'string'); - $this->addType(fieldName: 'description', type: 'string'); - $this->addType(fieldName: 'image', type: 'string'); - $this->addType(fieldName: 'search', type: 'string'); - $this->addType(fieldName: 'listed', type: 'boolean'); - $this->addType(fieldName: 'organisation', type: 'string'); - $this->addType(fieldName: 'metadata', type: 'json'); - + $this->addType('name', 'string'); + $this->addType('value', 'string'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'value' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - $array = [ - 'id' => $this->id, - 'title' => $this->title, - 'summary' => $this->summary, - 'description' => $this->description, - 'image' => $this->image, - 'search' => $this->search, - 'listed' => $this->listed, - 'metadata' => $this->metadata, - 'organisation'=> $this->organisation, - - ]; - - $jsonFields = $this->getJsonFields(); - - foreach ($array as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === null) { - $array[$key] = []; - } + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; } - - return $array; + return $data; } } diff --git a/lib/Db/SettingMapper.php b/lib/Db/SettingMapper.php index f6aafc0..b748397 100644 --- a/lib/Db/SettingMapper.php +++ b/lib/Db/SettingMapper.php @@ -1,5 +1,13 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use OCA\LarpingApp\Db\Setting; @@ -8,67 +16,81 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + * @package OCA\LarpingApp\Db + */ class SettingMapper extends QBMapper { + /** + * @param IDBConnection $db Database connection + */ public function __construct(IDBConnection $db) { - parent::__construct($db, 'larpingapp_settings'); + parent::__construct($db, 'larpingapp_settings', Setting::class); } + /** + * Find a setting by ID + * + * @param int $id The setting ID + * @return Setting + * @throws \OCP\AppFramework\Db\DoesNotExistException + * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException + */ public function find(int $id): Setting { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_settings') - ->where( - $qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)) - ); - - return $this->findEntity(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); + return $this->findEntity($qb); } - public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array + /** + * Find all settings for a user + * + * @param string $userId The user ID + * @return Setting[] + */ + public function findAll(string $userId): array { $qb = $this->db->getQueryBuilder(); - $qb->select('*') - ->from('larpingapp_settings') - ->setMaxResults($limit) - ->setFirstResult($offset); - - foreach($filters as $filter => $value) { - if ($value === 'IS NOT NULL') { - $qb->andWhere($qb->expr()->isNotNull($filter)); - } elseif ($value === 'IS NULL') { - $qb->andWhere($qb->expr()->isNull($filter)); - } else { - $qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value))); - } - } - - if (!empty($searchConditions)) { - $qb->andWhere('(' . implode(' OR ', $searchConditions) . ')'); - foreach ($searchParams as $param => $value) { - $qb->setParameter($param, $value); - } - } - - return $this->findEntities(query: $qb); + ->from($this->getTableName()) + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId))); + + return $this->findEntities($qb); } - public function createFromArray(array $object): Setting + /** + * Create a new setting from array data + * + * @param array $data The setting data + * @return Setting + */ + public function createFromArray(array $data): Setting { $setting = new Setting(); - $setting->hydrate(object: $object); - return $this->insert(entity: $setting); + foreach ($data as $key => $value) { + $setting->$key = $value; + } + return $this->insert($setting); } - public function updateFromArray(int $id, array $object): Setting + /** + * Update a setting from array data + * + * @param int $id The setting ID + * @param array $data The updated setting data + * @return Setting + */ + public function updateFromArray(int $id, array $data): Setting { $setting = $this->find($id); - $setting->hydrate($object); - + foreach ($data as $key => $value) { + $setting->$key = $value; + } return $this->update($setting); } } diff --git a/lib/Db/Skill.php b/lib/Db/Skill.php index 848d27a..0a7e6e6 100644 --- a/lib/Db/Skill.php +++ b/lib/Db/Skill.php @@ -1,81 +1,84 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getDescription() + * @method void setDescription(string $description) + */ class Skill extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?string $effect = null; - protected ?array $effects = null; - protected ?array $requiredSkills = []; - protected ?array $requiredStats = []; - protected ?array $requiredConditions = []; - protected ?array $requiredEffects = []; - protected ?int $requiredScore = null; + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $description; + /** + * Constructor to set the defaults + */ public function __construct() { $this->addType('name', 'string'); $this->addType('description', 'string'); - $this->addType('effect', 'string'); - $this->addType('effects', 'json'); - $this->addType('requiredSkills', 'json'); - $this->addType('requiredStats', 'json'); - $this->addType('requiredConditions', 'json'); - $this->addType('requiredEffects', 'json'); - $this->addType('requiredScore', 'integer'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'description' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'effect' => $this->effect, - 'effects' => $this->effects, - 'requiredSkills' => $this->requiredSkills, - 'requiredStats' => $this->requiredStats, - 'requiredConditions' => $this->requiredConditions, - 'requiredEffects' => $this->requiredEffects, - 'requiredScore' => $this->requiredScore, - ]; + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; + } + return $data; } } \ No newline at end of file diff --git a/lib/Db/Template.php b/lib/Db/Template.php index 97cb28e..246ed8f 100644 --- a/lib/Db/Template.php +++ b/lib/Db/Template.php @@ -1,63 +1,83 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + */ + namespace OCA\LarpingApp\Db; -use DateTime; use JsonSerializable; use OCP\AppFramework\Db\Entity; +/** + * @method string getName() + * @method void setName(string $name) + * @method string getDescription() + * @method void setDescription(string $description) + */ class Template extends Entity implements JsonSerializable { - protected ?string $name = null; - protected ?string $description = null; - protected ?string $template = null; + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $description; + /** + * Constructor to set the defaults + */ public function __construct() { $this->addType('name', 'string'); $this->addType('description', 'string'); - $this->addType('template', 'string'); } + /** + * Get the fields that should be serialized to JSON + * + * @return array + */ public function getJsonFields(): array { - return array_keys( - array_filter( - $this->getFieldTypes(), function ($field) { - return $field === 'json'; - } - ) - ); + return [ + 'id', + 'name', + 'description' + ]; } - public function hydrate(array $object): self + /** + * Hydrate the entity from an array of data + * + * @param array $data + * @return void + */ + public function hydrate(array $data): void { - $jsonFields = $this->getJsonFields(); - - foreach($object as $key => $value) { - if (in_array($key, $jsonFields) === true && $value === []) { - $value = []; - } - - $method = 'set'.ucfirst($key); - - try { - $this->$method($value); - } catch (\Exception $exception) { - // ("Error writing $key"); - } + foreach ($data as $key => $value) { + $this->$key = $value; } - - return $this; } + /** + * Serialize the entity to JSON + * + * @return array + */ public function jsonSerialize(): array { - return [ - 'id' => $this->id, - 'name' => $this->name, - 'description' => $this->description, - 'template' => $this->template, - ]; + $data = []; + foreach ($this->getJsonFields() as $field) { + $data[$field] = $this->$field; + } + return $data; } } \ No newline at end of file diff --git a/lib/Db/TemplateMapper.php b/lib/Db/TemplateMapper.php index bf1ea4e..b72f3d9 100644 --- a/lib/Db/TemplateMapper.php +++ b/lib/Db/TemplateMapper.php @@ -1,5 +1,18 @@ + * @author Ruben Linde + * @license AGPL-3.0-or-later + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + */ + namespace OCA\LarpingApp\Db; use OCA\LarpingApp\Db\Template; @@ -8,19 +21,34 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper