Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions lib/Db/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
* @method setNodes(array $value): void
* @method getPages(): array
* @method setPages(array $value): void
* @method getMenuItems(): array
* @method setMenuItems(array $value): void
*/
class Context extends EntitySuper implements JsonSerializable {
protected ?string $name = null;
Expand All @@ -40,8 +42,9 @@ class Context extends EntitySuper implements JsonSerializable {
protected ?array $sharing = null;
protected ?array $nodes = null;
protected ?array $pages = null;
protected ?array $menuItems = null;

protected const VIRTUAL_PROPERTIES = ['sharing', 'nodes', 'pages'];
protected const VIRTUAL_PROPERTIES = ['sharing', 'nodes', 'pages', 'menuItems'];

public function __construct() {
$this->addType('id', 'integer');
Expand All @@ -56,7 +59,8 @@ public function jsonSerialize(): array {
'iconName' => $this->getIcon(),
'description' => $this->getDescription(),
'owner' => $this->getOwnerId(),
'ownerType' => $this->getOwnerType()
'ownerType' => $this->getOwnerType(),
'menuItems' => array_values($this->menuItems ?? []),
];

// extended data
Expand Down
85 changes: 31 additions & 54 deletions lib/Db/ContextMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public function __construct(
IDBConnection $db,
protected UserHelper $userHelper,
protected GroupHelper $groupHelper,
protected MenuItemMapper $menuItemMapper,
) {
parent::__construct($db, $this->table, Context::class);
}
Expand Down Expand Up @@ -76,7 +77,10 @@ protected function getFindContextBaseQuery(?string $userId): IQueryBuilder {
return $qb;
}

protected function formatResultRows(array $rows, ?string $userId) {
/**
* @param array<int, list<MenuItem>> $menuItemsByContext
*/
protected function formatResultRows(array $rows, ?string $userId, array $menuItemsByContext = []) {
$formatted = [
'id' => $rows[0]['id'],
'name' => $rows[0]['name'],
Expand Down Expand Up @@ -141,6 +145,11 @@ protected function formatResultRows(array $rows, ?string $userId) {
return $carry;
}, []);

$formatted['menu_items'] = array_map(
static fn (MenuItem $menuItem): array => $menuItem->jsonSerialize(),
$menuItemsByContext[(int)$rows[0]['id']] ?? [],
);

return $this->mapRowToEntity($formatted);
}

Expand All @@ -154,26 +163,9 @@ public function findAll(?string $userId = null): array {
$result = $qb->executeQuery();
$r = $result->fetchAllAssociative();

$contextIds = [];
foreach ($r as $row) {
$contextIds[$row['id']] = 1;
}
$contextIds = array_keys($contextIds);
unset($row);

$resultEntities = [];
foreach ($contextIds as $contextId) {
$workArray = [];
foreach ($r as $row) {
if ((int)$row['id'] === $contextId) {
$workArray[] = $row;
}
}
$resultEntities[] = $this->formatResultRows($workArray, $userId);
}

return $resultEntities;
return $this->formatResultSet($r, $userId, true);
}

public function findForNavBar(string $userId): array {
$qb = $this->getFindContextBaseQuery($userId);
$groupIDs = $this->userHelper->getGroupIdsForUser($userId);
Expand Down Expand Up @@ -204,24 +196,27 @@ public function findForNavBar(string $userId): array {
$result = $qb->executeQuery();
$r = $result->fetchAllAssociative();

$contextIds = [];
foreach ($r as $row) {
$contextIds[$row['id']] = 1;
// the navigation bar shows the applications only, not their menus
return $this->formatResultSet($r, $userId, false);
}

/**
* Groups the joined rows per context, loading the menus of all contexts in one query.
*
* @return Context[]
* @throws Exception
*/
private function formatResultSet(array $rows, ?string $userId, bool $withMenuItems): array {
$rowsByContext = [];
foreach ($rows as $row) {
$rowsByContext[(int)$row['id']][] = $row;
}
$contextIds = array_keys($contextIds);
unset($row);
$menuItemsByContext = $withMenuItems ? $this->menuItemMapper->findByContextIds(array_keys($rowsByContext)) : [];

$resultEntities = [];
foreach ($contextIds as $contextId) {
$workArray = [];
foreach ($r as $row) {
if ((int)$row['id'] === $contextId) {
$workArray[] = $row;
}
}
$resultEntities[] = $this->formatResultRows($workArray, $userId);
foreach ($rowsByContext as $contextRows) {
$resultEntities[] = $this->formatResultRows($contextRows, $userId, $menuItemsByContext);
}

return $resultEntities;
}

Expand All @@ -240,7 +235,7 @@ public function findById(int $contextId, ?string $userId = null): Context {
throw new NotFoundError('Context does not exist');
}

return $this->formatResultRows($r, $userId);
return $this->formatResultRows($r, $userId, $this->menuItemMapper->findByContextIds([$contextId]));
}

/**
Expand All @@ -256,25 +251,7 @@ public function findAllContainingNode(int $nodeType, int $nodeId, string $userId
$result = $qb->executeQuery();
$r = $result->fetchAllAssociative();

$contextIds = [];
foreach ($r as $row) {
$contextIds[$row['id']] = 1;
}
$contextIds = array_keys($contextIds);
unset($row);

$resultEntities = [];
foreach ($contextIds as $contextId) {
$workArray = [];
foreach ($r as $row) {
if ($row['id'] === $contextId) {
$workArray[] = $row;
}
}
$resultEntities[] = $this->formatResultRows($workArray, $userId);
}

return $resultEntities;
return $this->formatResultSet($r, $userId, true);
}

/**
Expand Down
83 changes: 83 additions & 0 deletions lib/Db/MenuItem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Tables\Db;

use JsonSerializable;

/**
* @method getContextId(): int
* @method setContextId(int $contextId): void
* @method getLabel(): string
* @method setLabel(string $label): void
* @method getIcon(): ?string
* @method setIcon(?string $icon): void
* @method getTargetType(): string
* @method setTargetType(string $targetType): void
* @method getTargetId(): ?int
* @method setTargetId(?int $targetId): void
* @method getUrl(): ?string
* @method setUrl(?string $url): void
* @method getTechnicalName(): string
* @method setTechnicalName(string $technicalName): void
* @method getOrder(): int
* @method setOrder(int $order): void
* @method isBroken(): bool
* @method setBroken(bool $broken): void
*/
class MenuItem extends EntitySuper implements JsonSerializable {
public const TARGET_VIEW = 'view';
public const TARGET_TABLE = 'table';
public const TARGET_URL = 'url';
public const TARGET_TYPES = [self::TARGET_VIEW, self::TARGET_TABLE, self::TARGET_URL];

protected ?int $contextId = null;
protected ?string $label = null;
protected ?string $icon = null;
protected ?string $targetType = null;
protected ?int $targetId = null;
protected ?string $url = null;
protected ?string $technicalName = null;
protected ?int $order = null;

// virtual: true when the view or table the item points at no longer exists
protected bool $broken = false;

protected const VIRTUAL_PROPERTIES = ['broken'];

public function __construct() {
$this->addType('id', 'integer');
$this->addType('contextId', 'integer');
$this->addType('targetId', 'integer');
$this->addType('order', 'integer');
$this->addType('broken', 'boolean');
}

/**
* @return array{id: int, contextId: int, label: string, icon: string|null, targetType: 'view'|'table'|'url', targetId: int|null, url: string|null, technicalName: string, order: int, broken: bool}
*/
public function jsonSerialize(): array {
return [
'id' => $this->getId(),
'contextId' => $this->getContextId(),
'label' => $this->getLabel() ?? '',
'icon' => $this->getIcon(),
'targetType' => match ($this->targetType) {
self::TARGET_VIEW => self::TARGET_VIEW,
self::TARGET_TABLE => self::TARGET_TABLE,
default => self::TARGET_URL,
},
'targetId' => $this->getTargetId(),
'url' => $this->getUrl(),
'technicalName' => $this->technicalName ?? '',
'order' => $this->getOrder() ?? 0,
'broken' => $this->broken,
];
}
}
89 changes: 89 additions & 0 deletions lib/Db/MenuItemMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Tables\Db;

use OCP\AppFramework\Db\QBMapper;
use OCP\DB\Exception;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;

/** @template-extends QBMapper<MenuItem> */
class MenuItemMapper extends QBMapper {
private const DB_CHUNK_SIZE = 1_000;

protected string $table = 'tables_contexts_menu_item';

public function __construct(IDBConnection $db) {
parent::__construct($db, $this->table, MenuItem::class);
}

/**
* @return MenuItem[] ordered by their position in the menu
* @throws Exception
*/
public function findByContextId(int $contextId): array {
return $this->findByContextIds([$contextId])[$contextId] ?? [];
}

/**
* The menu items of the given contexts, each list ordered by position. An item whose
* view or table no longer exists is marked broken.
*
* @param int[] $contextIds
* @return array<int, list<MenuItem>> keyed by context id
* @throws Exception
*/
public function findByContextIds(array $contextIds): array {
if ($contextIds === []) {
return [];
}

$qb = $this->db->getQueryBuilder();
$brokenExpression = sprintf(
'CASE WHEN (m.target_type = %s AND v.id IS NULL) OR (m.target_type = %s AND t.id IS NULL) THEN 1 ELSE 0 END',
$qb->createNamedParameter(MenuItem::TARGET_VIEW),
$qb->createNamedParameter(MenuItem::TARGET_TABLE),
);
$qb->select('m.*')
->selectAlias($qb->createFunction($brokenExpression), 'broken')
->from($this->table, 'm')
->leftJoin('m', 'tables_views', 'v', $qb->expr()->andX(
$qb->expr()->eq('v.id', 'm.target_id'),
$qb->expr()->eq('m.target_type', $qb->createNamedParameter(MenuItem::TARGET_VIEW)),
))
->leftJoin('m', 'tables_tables', 't', $qb->expr()->andX(
$qb->expr()->eq('t.id', 'm.target_id'),
$qb->expr()->eq('m.target_type', $qb->createNamedParameter(MenuItem::TARGET_TABLE)),
))
->where($qb->expr()->in('m.context_id', $qb->createParameter('contextIds')))
->orderBy('m.context_id', 'ASC')
->addOrderBy('m.order', 'ASC')
->addOrderBy('m.id', 'ASC');

$byContext = [];
foreach (array_chunk(array_values(array_unique($contextIds)), self::DB_CHUNK_SIZE) as $chunk) {
$qb->setParameter('contextIds', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
foreach ($this->findEntities($qb) as $menuItem) {
$byContext[$menuItem->getContextId()][] = $menuItem;
}
}
return $byContext;
}

/**
* @throws Exception
*/
public function deleteAllByContextId(int $contextId): void {
$qb = $this->db->getQueryBuilder();
$qb->delete($this->table)
->where($qb->expr()->eq('context_id', $qb->createNamedParameter($contextId, IQueryBuilder::PARAM_INT)));
$qb->executeStatement();
}
}
50 changes: 50 additions & 0 deletions lib/Migration/Version2400Date20261012020000.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Tables\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
use Override;

/**
* Applications (contexts) get a menu. A menu item's technical name names its page and is
* unique within the application; the index keeps it so when two saves run at once.
*/
class Version2400Date20261012020000 extends SimpleMigrationStep {
#[Override]
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();

if (!$schema->hasTable('tables_contexts_menu_item')) {
$table = $schema->createTable('tables_contexts_menu_item');
$table->addColumn('id', Types::INTEGER, ['autoincrement' => true, 'notnull' => true]);
$table->addColumn('context_id', Types::INTEGER, ['notnull' => true]);
$table->addColumn('label', Types::STRING, ['notnull' => true, 'length' => 200]);
$table->addColumn('icon', Types::STRING, ['notnull' => false, 'length' => 64]);
$table->addColumn('target_type', Types::STRING, ['notnull' => true, 'length' => 16]);
$table->addColumn('target_id', Types::INTEGER, ['notnull' => false]);
$table->addColumn('url', Types::STRING, ['notnull' => false, 'length' => 2000]);
$table->addColumn('technical_name', Types::STRING, ['notnull' => true, 'length' => 200]);
$table->addColumn('order', Types::INTEGER, ['notnull' => true, 'default' => 0]);
$table->setPrimaryKey(['id']);
}

$table = $schema->getTable('tables_contexts_menu_item');
if (!$table->hasIndex('tables_ctx_menu_name_uq')) {
$table->addUniqueIndex(['context_id', 'technical_name'], 'tables_ctx_menu_name_uq');
}

return $schema;
}
}
Loading
Loading