Skip to content

refactor: turn columnSettings data from loose array to value object #1845

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
10 changes: 4 additions & 6 deletions lib/BackgroundJob/ConvertViewColumnsFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/
namespace OCA\Tables\BackgroundJob;

use OCA\Tables\Service\ValueObject\ViewColumnInformation;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\TimedJob;
Expand All @@ -26,14 +27,14 @@ public function __construct(

public function run($argument) {
$qb = $this->connection->getQueryBuilder();

// Get all views that need processing
$qb->select('id', 'columns')
->from('tables_views')
->where($qb->expr()->isNotNull('columns'));

$result = $qb->executeQuery();

// Predefine update query
$updateQb = $this->connection->getQueryBuilder();
$updateQb->update('tables_views')
Expand Down Expand Up @@ -77,10 +78,7 @@ private function processView(array $view, \OCP\DB\QueryBuilder\IQueryBuilder $up
// Create new columns structure
$newColumns = [];
foreach ($columns as $order => $columnId) {
$newColumns[] = [
'columnId' => (int)$columnId,
'order' => $order,
];
$newColumns[] = new ViewColumnInformation((int)$columnId, order: $order);
}

// Execute update query
Expand Down
29 changes: 12 additions & 17 deletions lib/Db/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use JsonSerializable;
use OCA\Tables\Model\Permissions;
use OCA\Tables\ResponseDefinitions;
use OCA\Tables\Service\ValueObject\ViewColumnInformation;
use OCP\AppFramework\Db\Entity;

/**
Expand Down Expand Up @@ -86,33 +87,30 @@ public function __construct() {
* @return int[]
*/
public function getColumnsArray(): array {

$columnSettings = $this->getColumnsSettingsArray();
usort($columnSettings, function ($a, $b) {
return $a['order'] - $b['order'];
usort($columnSettings, function (ViewColumnInformation $a, ViewColumnInformation $b) {
return $a[ViewColumnInformation::KEY_ORDER] - $b[ViewColumnInformation::KEY_ORDER];
});
return array_column($columnSettings, 'columnId');
return array_column($columnSettings, ViewColumnInformation::KEY_ID);
}

/**
* @return array<array{columnId: int, order: int}>
* @return array<ViewColumnInformation>
*/
public function getColumnsSettingsArray(): array {
$columns = $this->getArray($this->getColumns());
if (empty($columns)) {
return [];
}

if (is_array(reset($columns))) {
return $columns;
return array_map(static fn (array $a): ViewColumnInformation => ViewColumnInformation::fromArray($a), $columns);
}

$result = [];
foreach ($columns as $index => $columnId) {
$result[] = [
'columnId' => $columnId,
'order' => (int)$index + 1
];
$result[] = new ViewColumnInformation($columnId, order: (int)$index + 1);
}
return $result;
}
Expand Down Expand Up @@ -155,10 +153,6 @@ public function setColumnsArray(array $array):void {
$this->setColumns(\json_encode($array));
}

public function setColumnsSettingsArray(array $array): void {
$this->setColumnSettings(\json_encode($array));
}

public function setSortArray(array $array):void {
$this->setSort(\json_encode($array));
}
Expand Down Expand Up @@ -214,6 +208,7 @@ public function jsonSerialize(): array {
* @return int[]
*/
public function getColumnIds(): array {
return array_column($this->getColumnsSettingsArray(), 'columnId');
$columns = $this->getColumnsSettingsArray();
return array_map(static fn (ViewColumnInformation $column): int => $column[ViewColumnInformation::KEY_ID], $columns);
}
}
38 changes: 17 additions & 21 deletions lib/Service/TableTemplateService.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use OCA\Tables\Errors\InternalError;
use OCA\Tables\Errors\NotFoundError;
use OCA\Tables\Errors\PermissionError;
use OCA\Tables\Service\ValueObject\ViewColumnInformation;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\DB\Exception;
Expand Down Expand Up @@ -466,11 +467,8 @@ private function makeVacationRequests(Table $table):void {
[
'title' => $this->l->t('Create Vacation Request'),
'emoji' => '️➕',
'columnSettings' => json_encode(array_map(function ($columnId, $index) {
return [
'columnId' => $columnId,
'order' => $index
];
'columnSettings' => json_encode(array_map(function (int $columnId, int $index): ViewColumnInformation {
return new ViewColumnInformation($columnId, $index);
}, [$columns['employee']->getId(), $columns['from']->getId(), $columns['to']->getId(), $columns['workingDays']->getId(), $columns['dateRequest']->getId()], array_keys([$columns['employee']->getId(), $columns['from']->getId(), $columns['to']->getId(), $columns['workingDays']->getId(), $columns['dateRequest']->getId()]))),
'sort' => json_encode([['columnId' => Column::TYPE_META_UPDATED_AT, 'mode' => 'ASC']]),
'filter' => json_encode([[['columnId' => Column::TYPE_META_CREATED_BY, 'operator' => 'is-equal', 'value' => '@my-name'], ['columnId' => $columns['approved']->getId(), 'operator' => 'is-empty', 'value' => '']]]),
Expand All @@ -480,11 +478,8 @@ private function makeVacationRequests(Table $table):void {
[
'title' => $this->l->t('Open Request'),
'emoji' => '️📝',
'columnSettings' => json_encode(array_map(function ($column, $index) {
return [
'columnId' => $column->getId(),
'order' => $index
];
'columnSettings' => json_encode(array_map(function (Column $column, int $index): ViewColumnInformation {
return new ViewColumnInformation($column->getId(), $index);
}, array_values($columns), array_keys(array_values($columns)))),
'sort' => json_encode([['columnId' => $columns['from']->getId(), 'mode' => 'ASC']]),
'filter' => json_encode([[['columnId' => $columns['approved']->getId(), 'operator' => 'is-empty', 'value' => '']]]),
Expand All @@ -494,11 +489,8 @@ private function makeVacationRequests(Table $table):void {
[
'title' => $this->l->t('Request Status'),
'emoji' => '️❓',
'columnSettings' => json_encode(array_map(function ($column, $index) {
return [
'columnId' => $column->getId(),
'order' => $index
];
'columnSettings' => json_encode(array_map(function (Column $column, int $index): ViewColumnInformation {
return new ViewColumnInformation($column->getId(), $index);
}, array_values($columns), array_keys(array_values($columns)))),
'sort' => json_encode([['columnId' => Column::TYPE_META_UPDATED_BY, 'mode' => 'ASC']]),
'filter' => json_encode([[['columnId' => Column::TYPE_META_CREATED_BY, 'operator' => 'is-equal', 'value' => '@my-name']]]),
Expand All @@ -508,11 +500,8 @@ private function makeVacationRequests(Table $table):void {
[
'title' => $this->l->t('Closed requests'),
'emoji' => '️✅',
'columnSettings' => json_encode(array_map(function ($column, $index) {
return [
'columnId' => $column->getId(),
'order' => $index
];
'columnSettings' => json_encode(array_map(function (Column $column, int $index): ViewColumnInformation {
return new ViewColumnInformation($column->getId(), $index);
}, array_values($columns), array_keys(array_values($columns)))),
'sort' => json_encode([['columnId' => Column::TYPE_META_UPDATED_BY, 'mode' => 'ASC']]),
'filter' => json_encode([[['columnId' => $columns['approved']->getId(), 'operator' => 'is-equal', 'value' => '@checked']], [['columnId' => $columns['approved']->getId(), 'operator' => 'is-equal', 'value' => '@unchecked']]]),
Expand Down Expand Up @@ -797,7 +786,14 @@ private function makeStartupTable(Table $table):void {
$this->createView($table, [
'title' => $this->l->t('Check yourself!'),
'emoji' => '🏁',
'columnSettings' => json_encode([['columnId' => $columns['what']->getId(), 'order' => 0], ['columnId' => $columns['how']->getId(), 'order' => 1], ['columnId' => $columns['ease']->getId(), 'order' => 2], ['columnId' => $columns['done']->getId(), 'order' => 3]]),
'columnSettings' => json_encode(
[
new ViewColumnInformation($columns['what']->getId(), order: 0),
new ViewColumnInformation($columns['how']->getId(), order: 1),
new ViewColumnInformation($columns['ease']->getId(), order: 2),
new ViewColumnInformation($columns['done']->getId(), order: 3),
]
),
'filter' => json_encode([[['columnId' => $columns['done']->getId(), 'operator' => 'is-equal', 'value' => '@unchecked']]]),
]);
}
Expand Down
69 changes: 69 additions & 0 deletions lib/Service/ValueObject/ViewColumnInformation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Tables\Service\ValueObject;

use ArrayAccess;
use JsonSerializable;

/**
* @template-implements ArrayAccess<string, mixed>
*/
class ViewColumnInformation implements ArrayAccess, JSONSerializable {
public const KEY_ID = 'columnId';
public const KEY_ORDER = 'order';

/** @var array{columndId?: int, order?: int} */
protected array $data = [];
protected const KEYS = [
self::KEY_ID,
self::KEY_ORDER,
];

public function __construct(
int $columnId,
int $order,
) {
$this->offsetSet(self::KEY_ID, $columnId);
$this->offsetSet(self::KEY_ORDER, $order);
}

public static function fromArray(array $data): static {
$vci = new static($data[self::KEY_ID], $data[self::KEY_ORDER]);
foreach ($data as $key => $value) {
$vci[$key] = $value;
}
return $vci;
}

public function offsetExists(mixed $offset): bool {
return in_array((string)$offset, self::KEYS);
}

public function offsetGet(mixed $offset): mixed {
return $this->data[$offset] ?? null;
}

public function offsetSet(mixed $offset, mixed $value): void {
if (!$this->offsetExists($offset)) {
return;
}
$this->data[(string)$offset] = $value;
}

public function offsetUnset(mixed $offset): void {
if (!$this->offsetExists($offset)) {
return;
}
unset($this->data[(string)$offset]);
}

public function jsonSerialize(): array {
return $this->data;
}
}
32 changes: 18 additions & 14 deletions lib/Service/ViewService.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use OCA\Tables\Helper\UserHelper;
use OCA\Tables\Model\Permissions;
use OCA\Tables\ResponseDefinitions;
use OCA\Tables\Service\ValueObject\ViewColumnInformation;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\EventDispatcher\IEventDispatcher;
Expand Down Expand Up @@ -272,11 +273,8 @@ public function update(int $id, array $data, ?string $userId = null, bool $skipT
$this->logger->info('The old columns format is deprecated. Please use the new format with columnId and order properties.');
$decodedValue = \json_decode($value, true);
$value = [];
foreach ($decodedValue as $order => $id) {
$value[] = [
'columnId' => $id,
'order' => $order
];
foreach ($decodedValue as $order => $columnId) {
$value[] = new ViewColumnInformation($columnId, order: $order);
}

$value = \json_encode($value);
Expand All @@ -285,8 +283,9 @@ public function update(int $id, array $data, ?string $userId = null, bool $skipT
if ($key === 'columnSettings' || $key === 'columns') {
// we have to fetch the service here as ColumnService already depends on the ViewService, i.e. no DI
$columnService = \OCP\Server::get(ColumnService::class);
$columnIds = array_column(\json_decode($value, true), 'columnId');

$rawColumnsArray = \json_decode($value, true);
$columnIds = array_column($rawColumnsArray, ViewColumnInformation::KEY_ID);

$availableColumns = $columnService->findAllByTable($view->getTableId(), $view->getId(), $this->userId);
$availableColumns = array_map(static fn (Column $column) => $column->getId(), $availableColumns);
foreach ($columnIds as $columnId) {
Expand All @@ -295,6 +294,14 @@ public function update(int $id, array $data, ?string $userId = null, bool $skipT
}
}

// ensure we have the correct format and expected values
try {
$columnsArray = array_map(static fn (array $a): ViewColumnInformation => ViewColumnInformation::fromArray($a), $rawColumnsArray);
$value = \json_encode($columnsArray);
} catch (\Throwable $t) {
throw new \InvalidArgumentException('Invalid column data provided', 400, $t);
}

$key = 'columns';
}

Expand Down Expand Up @@ -543,8 +550,8 @@ function (array $filter) use ($columnId) {
);

$columnSettings = $view->getColumnsSettingsArray();
$columnSettings = array_filter($columnSettings, function (array $setting) use ($columnId): bool {
return $setting['columnId'] !== $columnId;
$columnSettings = array_filter($columnSettings, static function (ViewColumnInformation $setting) use ($columnId): bool {
return $setting[ViewColumnInformation::KEY_ID] !== $columnId;
});
$columnSettings = array_values($columnSettings);

Expand Down Expand Up @@ -592,11 +599,8 @@ public function search(string $term, int $limit = 100, int $offset = 0, ?string
public function addColumnToView(View $view, Column $column, ?string $userId = null): void {
try {
$columnsSettings = $view->getColumnsSettingsArray();
$nextOrder = empty($columnsSettings) ? 0 : max(array_column($columnsSettings, 'order')) + 1;
$columnsSettings[] = [
'columnId' => $column->getId(),
'order' => $nextOrder
];
$nextOrder = empty($columnsSettings) ? 0 : max(array_column($columnsSettings, ViewColumnInformation::KEY_ORDER)) + 1;
$columnsSettings[] = new ViewColumnInformation($column->getId(), $nextOrder);
$this->update($view->getId(), ['columnSettings' => json_encode($columnsSettings)], $userId, true);
} catch (Exception $e) {
$this->logger->error($e->getMessage(), ['exception' => $e]);
Expand Down
5 changes: 4 additions & 1 deletion tests/integration/features/bootstrap/FeatureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -900,7 +900,10 @@ public function applyColumnsToView(string $user, string $columnList, string $vie
$columns = explode(',', $columnList);
$columnSettings = array_map(function (string $columnAlias, int $index) {
if (is_numeric($columnAlias)) {
return (int)$columnAlias;
return [
'columnId' => (int)$columnAlias,
'order' => $index
];
}

$col = $this->collectionManager->getByAlias('column', $columnAlias);
Expand Down
Loading