From fc490d92c293120cc241b552ec2304c139b6ce58 Mon Sep 17 00:00:00 2001 From: Robert Zondervan Date: Thu, 19 Nov 2026 14:01:41 +0100 Subject: [PATCH 1/8] feat(rows): return the object shape as XML The object shape of api/2 was refused for any response that is not JSON, because the OCS XML writer turns the @self key into an attribute and fails on its array. RowObjectXmlShaper now maps the JSON shape to data the OCS writer renders: with the metadata as attributes, an element per column named by its technical name, for a name that is not an NCName (or is element or self), nil="true" for null, true/false for booleans and items for lists. getRows, getRow, createRow and updateRow apply it for every response OCS renders as XML, as does the validation error of an object-shape write. JSON responses are unchanged. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Robert Zondervan --- lib/Controller/RowOCSController.php | 70 +++++++++----- lib/Service/RowObjectXmlShaper.php | 145 ++++++++++++++++++++++++++++ openapi.json | 14 +-- src/types/openapi/openapi.ts | 14 +-- 4 files changed, 204 insertions(+), 39 deletions(-) create mode 100644 lib/Service/RowObjectXmlShaper.php diff --git a/lib/Controller/RowOCSController.php b/lib/Controller/RowOCSController.php index 72b884b19c..016689cb89 100644 --- a/lib/Controller/RowOCSController.php +++ b/lib/Controller/RowOCSController.php @@ -23,6 +23,7 @@ use OCA\Tables\ResponseDefinitions; use OCA\Tables\Service\FederationService; use OCA\Tables\Service\RowObjectSerializer; +use OCA\Tables\Service\RowObjectXmlShaper; use OCA\Tables\Service\RowService; use OCA\Tables\Service\TableService; use OCA\Tables\Service\ViewService; @@ -53,6 +54,7 @@ public function __construct( private readonly ViewService $viewService, private readonly FederationService $federationService, private readonly RowObjectSerializer $rowObjectSerializer, + private readonly RowObjectXmlShaper $rowObjectXmlShaper, ) { parent::__construct($request, $logger, $n, $userId); } @@ -63,11 +65,11 @@ public function __construct( * @param 'tables'|'views' $nodeCollection Indicates whether to create a row on a table or view * @param int $nodeId The identifier of the targeted table or view * @param string|array $data The values of the row: keyed by column id, or with shape "object" keyed by technical name - * @param 'cells'|'object'|null $shape The shape of the data and of the returned row, defaults to "cells"; the object shape is only available as JSON + * @param 'cells'|'object'|null $shape The shape of the data and of the returned row, defaults to "cells". The data is sent as JSON or form data; in an XML response a row in the object shape has an element per column, see the shape of getRow * @return DataResponse|DataResponse|DataResponse * * 200: Row returned - * 400: Invalid request parameters, an unknown shape or the object shape for a response that is not JSON (nothing is written then), or with shape "object" the values that cannot be stored, per technical name + * 400: Invalid request parameters or an unknown shape (nothing is written then), or with shape "object" the values that cannot be stored, per technical name; in XML errors has an element per technical name, by the rules of the object shape * 403: No permissions * 404: Not found * 500: Internal error @@ -77,7 +79,7 @@ public function __construct( #[ApiRoute(verb: 'POST', url: '/api/2/{nodeCollection}/{nodeId}/rows', requirements: ['nodeCollection' => '(tables|views)', 'nodeId' => '(\d+)'])] public function createRow(string $nodeCollection, int $nodeId, mixed $data, ?string $shape = null): DataResponse { try { - $rowShape = $this->rowShapeFromRequest($shape); + $rowShape = RowShape::fromRequest($shape); } catch (\InvalidArgumentException $e) { return $this->handleBadRequestError(new BadRequestError($e->getMessage())); } @@ -122,7 +124,7 @@ public function createRow(string $nodeCollection, int $nodeId, mixed $data, ?str } return new DataResponse($this->shapeRow($this->rowService->create($tableId, $viewId, $newRowData), $rowShape)); } catch (RowValidationError $e) { - return $this->handleRowValidationError($e); + return $this->rowValidationError($e); } catch (BadRequestError $e) { return $this->handleBadRequestError($e); } catch (NotFoundError $e) { @@ -151,7 +153,7 @@ public function createRow(string $nodeCollection, int $nodeId, mixed $data, ?str * @param string|null $search Text to look for in the text cells and the selection labels * @param string|null $fields Comma separated technical names or column ids of the columns to return, the metadata of a row is always returned * @param array>|null $filter Filters as filter[field]=value or filter[field][operator]=value, all of which must match. A deep object in the query string (for example filter[age][is-greater-than]=30&filter[name]=jane), shown as a string because the API description cannot express nested query parameters. field is a technical name, a column id or a meta field; operator is one of the view filter operators that fit the field's type (without one: is-equal, or contains-item on multi-value columns; long and rich text need an operator such as contains); a value is compared as given and written as the column stores it: a decimal number; a row id for relations and id; YYYY-MM-DD HH:MM for date and time columns, YYYY-MM-DD for date columns, HH:MM for time columns; YYYY-MM-DD with an optional HH:MM or HH:MM:SS, after a space or a T, for createdAt and updatedAt, in UTC unless the time ends in Z or an offset such as +02:00 (written %2B02:00 in the query string, where + means a space), an exact moment, so compare those with is-greater-than and is-lower-than rather than is-equal; an option id for selections; true or false for checkboxes; a user, group or team id for usergroup columns - * @param 'cells'|'object'|null $shape The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC; only available as JSON + * @param 'cells'|'object'|null $shape The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules * @return DataResponse|DataResponse * * 200: Rows returned @@ -182,7 +184,7 @@ public function getRows( } try { $query = RowListQuery::createFromRequest($page, $offset, $limit, $sort, $search, $fields, $filter); - $rowShape = $this->rowShapeFromRequest($shape); + $rowShape = RowShape::fromRequest($shape); } catch (\InvalidArgumentException $e) { throw new BadRequestError($e->getMessage()); } @@ -190,7 +192,7 @@ public function getRows( $found = $this->rowService->findPage($query, $tableId, $viewId, $this->userId); return new DataResponse([ 'results' => $rowShape === RowShape::Object - ? $this->rowObjectSerializer->serializeAll(array_values($found['rows'])) + ? $this->rowObjects($found['rows']) : array_values(array_map(static fn ($row) => $row->jsonSerialize(), $found['rows'])), 'total' => $found['total'], 'limit' => $query->limit, @@ -214,11 +216,11 @@ public function getRows( * @param 'tables'|'views' $nodeCollection Indicates whether to get a row from a table or view * @param int $nodeId The identifier of the targeted table or view * @param string $rowId The identifier of the row, either its integer id or its uuid - * @param 'cells'|'object'|null $shape The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC; only available as JSON + * @param 'cells'|'object'|null $shape The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules * @return DataResponse|DataResponse * * 200: Row returned - * 400: Invalid row identifier, an unknown shape or the object shape for a response that is not JSON, or the table or view is federated + * 400: Invalid row identifier, an unknown shape, or the table or view is federated * 403: No permissions * 404: Not found * 500: Internal error @@ -230,7 +232,7 @@ public function getRow(string $nodeCollection, int $nodeId, string $rowId, ?stri [$tableId, $viewId] = $this->splitNode($nodeCollection, $nodeId); try { try { - $rowShape = $this->rowShapeFromRequest($shape); + $rowShape = RowShape::fromRequest($shape); } catch (\InvalidArgumentException $e) { throw new BadRequestError($e->getMessage()); } @@ -257,11 +259,11 @@ public function getRow(string $nodeCollection, int $nodeId, string $rowId, ?stri * @param int $nodeId The identifier of the targeted table or view * @param string $rowId The identifier of the row to update, either its integer id or its uuid * @param string|array $data The values to change: keyed by column id, or with shape "object" keyed by technical name - * @param 'cells'|'object'|null $shape The shape of the data and of the returned row, defaults to "cells"; the object shape is only available as JSON + * @param 'cells'|'object'|null $shape The shape of the data and of the returned row, defaults to "cells". The data is sent as JSON or form data; in an XML response a row in the object shape has an element per column, see the shape of getRow * @return DataResponse|DataResponse|DataResponse * * 200: Row updated - * 400: Invalid request parameters, an unknown shape or the object shape for a response that is not JSON (nothing is written then), or with shape "object" the values that cannot be stored, per technical name + * 400: Invalid request parameters or an unknown shape (nothing is written then), or with shape "object" the values that cannot be stored, per technical name; in XML errors has an element per technical name, by the rules of the object shape * 403: No permissions * 404: Not found * 500: Internal error @@ -271,7 +273,7 @@ public function getRow(string $nodeCollection, int $nodeId, string $rowId, ?stri #[ApiRoute(verb: 'PUT', url: '/api/2/{nodeCollection}/{nodeId}/rows/{rowId}', requirements: ['nodeCollection' => '(tables|views)', 'nodeId' => '(\d+)'])] public function updateRow(string $nodeCollection, int $nodeId, string $rowId, mixed $data, ?string $shape = null): DataResponse { try { - $rowShape = $this->rowShapeFromRequest($shape); + $rowShape = RowShape::fromRequest($shape); } catch (\InvalidArgumentException $e) { return $this->handleBadRequestError(new BadRequestError($e->getMessage())); } @@ -301,7 +303,7 @@ public function updateRow(string $nodeCollection, int $nodeId, string $rowId, mi $resolvedRowId = $this->rowService->resolveRowId($rowId, $tableId, $viewId); return new DataResponse($this->shapeRow($this->rowService->updateSet($resolvedRowId, $viewId, $values, $this->userId, $tableId), $rowShape)); } catch (RowValidationError $e) { - return $this->handleRowValidationError($e); + return $this->rowValidationError($e); } catch (BadRequestError $e) { return $this->handleBadRequestError($e); } catch (NotFoundError $e) { @@ -355,17 +357,10 @@ public function deleteRow(string $nodeCollection, int $nodeId, string $rowId): D } /** - * The shape a request asks for. The object shape is refused for an XML response, which - * OCS gives unless the format parameter or else the Accept header asks for JSON. - * - * @throws \InvalidArgumentException + * OCS answers in XML unless the format parameter or else the Accept header asks for JSON. */ - private function rowShapeFromRequest(?string $shape): RowShape { - $rowShape = RowShape::fromRequest($shape); - if ($rowShape === RowShape::Object && $this->request->getFormat() !== 'json') { - throw new \InvalidArgumentException('The object shape is only available as JSON.'); - } - return $rowShape; + private function isXmlResponse(): bool { + return $this->request->getFormat() !== 'json'; } /** @@ -373,7 +368,32 @@ private function rowShapeFromRequest(?string $shape): RowShape { * @throws InternalError */ private function shapeRow(Row2 $row, RowShape $rowShape): array { - return $rowShape === RowShape::Object ? $this->rowObjectSerializer->serialize($row) : $row->jsonSerialize(); + if ($rowShape === RowShape::Cells) { + return $row->jsonSerialize(); + } + $object = $this->rowObjectSerializer->serialize($row); + return $this->isXmlResponse() ? $this->rowObjectXmlShaper->shapeRow($object) : $object; + } + + /** + * @param Row2[] $rows + * @return list + * @throws InternalError + */ + private function rowObjects(array $rows): array { + $objects = $this->rowObjectSerializer->serializeAll(array_values($rows)); + return $this->isXmlResponse() ? $this->rowObjectXmlShaper->shapeRows($objects) : $objects; + } + + /** + * @return DataResponse + */ + private function rowValidationError(RowValidationError $e): DataResponse { + $response = $this->handleRowValidationError($e); + if ($this->isXmlResponse()) { + $response->setData($this->rowObjectXmlShaper->shapeValidationError($response->getData())); + } + return $response; } /** diff --git a/lib/Service/RowObjectXmlShaper.php b/lib/Service/RowObjectXmlShaper.php new file mode 100644 index 0000000000..8642b226a6 --- /dev/null +++ b/lib/Service/RowObjectXmlShaper.php @@ -0,0 +1,145 @@ +` with a member per attribute, an attribute + * whose value is null is left out; + * - a property becomes an element named by its key; a key that is not an XML NCName, or + * that is `element` (or `self` for a row), becomes ``, with the + * value in `` when it is not a list or an object, because an OCS element cannot + * have attributes and text; + * - null becomes an empty element with `nil="true"`, unprefixed because an undeclared + * prefix such as `xsi:` is not namespace-well-formed; an empty string or an empty list + * becomes an empty element without it; + * - booleans become `true` and `false`, numbers are written as JSON writes them; + * - a list becomes `` children, an object child elements by key, both by the + * same rules. + * + * @psalm-import-type TablesRowObject from ResponseDefinitions + * @psalm-import-type TablesRowValidationError from ResponseDefinitions + */ +class RowObjectXmlShaper { + private const NCNAME = '/^[\p{L}_][\p{L}\p{N}_.\-]*$/u'; + private const LIST_ITEM = 'element'; + private const SELF = 'self'; + + /** + * @param list $objects + * @return list> + */ + public function shapeRows(array $objects): array { + return array_map($this->shapeRow(...), $objects); + } + + /** + * @param TablesRowObject $object + * @return array + */ + public function shapeRow(array $object): array { + $shaped = []; + foreach ($object as $key => $value) { + if ($key === '@self' && is_array($value)) { + $shaped[self::SELF] = ['@attributes' => $this->attributes($value)]; + continue; + } + $this->addProperty($shaped, $key, $value, [self::LIST_ITEM, self::SELF]); + } + return $shaped; + } + + /** + * @param TablesRowValidationError $error + * @return array{message: string, errors: array} + */ + public function shapeValidationError(array $error): array { + return [ + 'message' => $error['message'], + 'errors' => $this->shapeObject($error['errors']), + ]; + } + + /** + * @param array $members + * @return array + */ + private function attributes(array $members): array { + $attributes = []; + foreach ($members as $name => $value) { + if (is_scalar($value)) { + $attributes[(string)$name] = $this->text($value); + } + } + return $attributes; + } + + /** + * @param array $object + * @return array + */ + private function shapeObject(array $object): array { + $shaped = []; + foreach ($object as $key => $value) { + $this->addProperty($shaped, $key, $value, [self::LIST_ITEM]); + } + return $shaped; + } + + /** + * @param array $shaped + * @param list $reservedNames names that also take the fallback element + */ + private function addProperty(array &$shaped, int|string $key, mixed $value, array $reservedNames): void { + $name = (string)$key; + if (preg_match(self::NCNAME, $name) === 1 && !in_array($name, $reservedNames, true)) { + $shaped[$name] = $this->shapeValue($value); + return; + } + $fallback = ['@attributes' => ['name' => $name]]; + if (is_array($value)) { + $shaped[] = $fallback + $this->shapeArray($value); + return; + } + $fallback['value'] = $this->shapeValue($value); + $shaped[] = $fallback; + } + + /** + * @return string|array + */ + private function shapeValue(mixed $value): string|array { + if ($value === null) { + return ['@attributes' => ['nil' => 'true']]; + } + return is_array($value) ? $this->shapeArray($value) : $this->text($value); + } + + /** + * @param array $value + * @return array + */ + private function shapeArray(array $value): array { + return array_is_list($value) ? array_map($this->shapeValue(...), $value) : $this->shapeObject($value); + } + + private function text(mixed $value): string { + return match (true) { + is_bool($value) => $value ? 'true' : 'false', + is_float($value) => json_encode($value, JSON_THROW_ON_ERROR), + is_scalar($value) => (string)$value, + default => json_encode($value, JSON_THROW_ON_ERROR), + }; + } +} diff --git a/openapi.json b/openapi.json index ae13b69717..6bd0dbd97d 100644 --- a/openapi.json +++ b/openapi.json @@ -16478,7 +16478,7 @@ "cells", "object" ], - "description": "The shape of the data and of the returned row, defaults to \"cells\"; the object shape is only available as JSON" + "description": "The shape of the data and of the returned row, defaults to \"cells\". The data is sent as JSON or form data; in an XML response a row in the object shape has an element per column, see the shape of getRow" } } } @@ -16560,7 +16560,7 @@ } }, "400": { - "description": "Invalid request parameters, an unknown shape or the object shape for a response that is not JSON (nothing is written then), or with shape \"object\" the values that cannot be stored, per technical name", + "description": "Invalid request parameters or an unknown shape (nothing is written then), or with shape \"object\" the values that cannot be stored, per technical name; in XML errors has an element per technical name, by the rules of the object shape", "content": { "application/json": { "schema": { @@ -16860,7 +16860,7 @@ { "name": "shape", "in": "query", - "description": "The shape of the returned rows, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC; only available as JSON", + "description": "The shape of the returned rows, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", "schema": { "type": "string", "nullable": true, @@ -17155,7 +17155,7 @@ { "name": "shape", "in": "query", - "description": "The shape of the returned row, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC; only available as JSON", + "description": "The shape of the returned row, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", "schema": { "type": "string", "nullable": true, @@ -17254,7 +17254,7 @@ } }, "400": { - "description": "Invalid row identifier, an unknown shape or the object shape for a response that is not JSON, or the table or view is federated", + "description": "Invalid row identifier, an unknown shape, or the table or view is federated", "content": { "application/json": { "schema": { @@ -17443,7 +17443,7 @@ "cells", "object" ], - "description": "The shape of the data and of the returned row, defaults to \"cells\"; the object shape is only available as JSON" + "description": "The shape of the data and of the returned row, defaults to \"cells\". The data is sent as JSON or form data; in an XML response a row in the object shape has an element per column, see the shape of getRow" } } } @@ -17534,7 +17534,7 @@ } }, "400": { - "description": "Invalid request parameters, an unknown shape or the object shape for a response that is not JSON (nothing is written then), or with shape \"object\" the values that cannot be stored, per technical name", + "description": "Invalid request parameters or an unknown shape (nothing is written then), or with shape \"object\" the values that cannot be stored, per technical name; in XML errors has an element per technical name, by the rules of the object shape", "content": { "application/json": { "schema": { diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 05aaa9a533..9b774118f7 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -8827,7 +8827,7 @@ export interface operations { readonly fields?: string | null; /** @description Filters as filter[field]=value or filter[field][operator]=value, all of which must match. A deep object in the query string (for example filter[age][is-greater-than]=30&filter[name]=jane), shown as a string because the API description cannot express nested query parameters. field is a technical name, a column id or a meta field; operator is one of the view filter operators that fit the field's type (without one: is-equal, or contains-item on multi-value columns; long and rich text need an operator such as contains); a value is compared as given and written as the column stores it: a decimal number; a row id for relations and id; YYYY-MM-DD HH:MM for date and time columns, YYYY-MM-DD for date columns, HH:MM for time columns; YYYY-MM-DD with an optional HH:MM or HH:MM:SS, after a space or a T, for createdAt and updatedAt, in UTC unless the time ends in Z or an offset such as +02:00 (written %2B02:00 in the query string, where + means a space), an exact moment, so compare those with is-greater-than and is-lower-than rather than is-equal; an option id for selections; true or false for checkboxes; a user, group or team id for usergroup columns */ readonly filter?: string | null; - /** @description The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC; only available as JSON */ + /** @description The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ readonly shape?: "cells" | "object" | null; }; readonly header: { @@ -8961,7 +8961,7 @@ export interface operations { readonly [key: string]: Record; }; /** - * @description The shape of the data and of the returned row, defaults to "cells"; the object shape is only available as JSON + * @description The shape of the data and of the returned row, defaults to "cells". The data is sent as JSON or form data; in an XML response a row in the object shape has an element per column, see the shape of getRow * @default null * @enum {string|null} */ @@ -8984,7 +8984,7 @@ export interface operations { }; }; }; - /** @description Invalid request parameters, an unknown shape or the object shape for a response that is not JSON (nothing is written then), or with shape "object" the values that cannot be stored, per technical name */ + /** @description Invalid request parameters or an unknown shape (nothing is written then), or with shape "object" the values that cannot be stored, per technical name; in XML errors has an element per technical name, by the rules of the object shape */ readonly 400: { headers: { readonly [name: string]: unknown; @@ -9067,7 +9067,7 @@ export interface operations { readonly "rowocs-get-row": { readonly parameters: { readonly query?: { - /** @description The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC; only available as JSON */ + /** @description The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ readonly shape?: "cells" | "object" | null; }; readonly header: { @@ -9100,7 +9100,7 @@ export interface operations { }; }; }; - /** @description Invalid row identifier, an unknown shape or the object shape for a response that is not JSON, or the table or view is federated */ + /** @description Invalid row identifier, an unknown shape, or the table or view is federated */ readonly 400: { headers: { readonly [name: string]: unknown; @@ -9205,7 +9205,7 @@ export interface operations { readonly [key: string]: Record; }; /** - * @description The shape of the data and of the returned row, defaults to "cells"; the object shape is only available as JSON + * @description The shape of the data and of the returned row, defaults to "cells". The data is sent as JSON or form data; in an XML response a row in the object shape has an element per column, see the shape of getRow * @default null * @enum {string|null} */ @@ -9228,7 +9228,7 @@ export interface operations { }; }; }; - /** @description Invalid request parameters, an unknown shape or the object shape for a response that is not JSON (nothing is written then), or with shape "object" the values that cannot be stored, per technical name */ + /** @description Invalid request parameters or an unknown shape (nothing is written then), or with shape "object" the values that cannot be stored, per technical name; in XML errors has an element per technical name, by the rules of the object shape */ readonly 400: { headers: { readonly [name: string]: unknown; From 71dbe2103c29cbc0d6c3ba89a5df0f4c3ccf411c Mon Sep 17 00:00:00 2001 From: Robert Zondervan Date: Thu, 19 Nov 2026 14:01:42 +0100 Subject: [PATCH 2/8] test(rows): cover the object shape as XML Unit tests for RowObjectXmlShaper, rendering through the OCS V1 and V2 XML writers, the controller answering the object shape and its validation errors in XML, and a Behat scenario that reads a row and a refused write with format=xml. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Robert Zondervan --- tests/integration/features/APIv2.feature | 47 ++++ .../features/bootstrap/FeatureContext.php | 97 +++++++ .../unit/Controller/RowOCSControllerTest.php | 83 +++++- tests/unit/Service/RowObjectXmlShaperTest.php | 257 ++++++++++++++++++ 4 files changed, 469 insertions(+), 15 deletions(-) create mode 100644 tests/unit/Service/RowObjectXmlShaperTest.php diff --git a/tests/integration/features/APIv2.feature b/tests/integration/features/APIv2.feature index cd6af96266..f0594c62c3 100644 --- a/tests/integration/features/APIv2.feature +++ b/tests/integration/features/APIv2.feature @@ -722,6 +722,53 @@ Feature: APIv2 | name | "AHA" | And the listed object of row "first" has the uuid of row "target" as "project" + @api2 @rows + Scenario: Read and write rows via v2 in the object shape as XML + Given table "Object targets" with emoji "🎯" exists for user "participant1-v2" as "xml-targets" via v2 + And column "label" exists with following properties + | type | text | + | subtype | line | + | mandatory | 0 | + And using table "xml-targets" + And user "participant1-v2" creates row "xml-target" with following values: + | label | Target | + And table "Object XML" with emoji "🧩" exists for user "participant1-v2" as "xml-shape" via v2 + And column "name" exists with following properties + | type | text | + | subtype | line | + | mandatory | 0 | + And column "amount" exists with following properties + | type | number | + | mandatory | 0 | + And column "done" exists with following properties + | type | selection | + | subtype | check | + | mandatory | 0 | + And column "website" exists with following properties + | type | text | + | subtype | link | + | textAllowedPattern | url | + | mandatory | 0 | + And relation column "project" exists on table "xml-shape" pointing to table "xml-targets" using label column "label" + And using table "xml-shape" + And user "participant1-v2" creates row "xml-first" relating "project" to row "xml-target" with following values: + | name | AHA | + | done | true | + | website | {"title":"Nextcloud","subline":"URL","providerId":"url","value":"https://nextcloud.com"} | + When user "participant1-v2" gets row "xml-first" of table "xml-shape" using v2 in the object shape as XML + Then the XML object is row "xml-first" with following values + | name | AHA | + | amount | nil | + | done | true | + | website | Nextcloudhttps://nextcloud.comurl | + And the XML object of row "xml-first" has the uuid of row "xml-target" as "project" + When user "participant1-v2" creates a row in table "xml-shape" using v2 in the object shape as XML with + | missing | "x" | + | 1st | "x" | + Then the XML validation error has following errors + | missing | There is no column with this technical name. | + | 1st | There is no column with this technical name. | + @api2 @rows Scenario: Try to create rows via v2 with permissions Given table "Rows check" with emoji "👨🏻‍💻" exists for user "participant1-v2" as "base1" via v2 diff --git a/tests/integration/features/bootstrap/FeatureContext.php b/tests/integration/features/bootstrap/FeatureContext.php index 5ecf9af82e..e54ddfbc16 100644 --- a/tests/integration/features/bootstrap/FeatureContext.php +++ b/tests/integration/features/bootstrap/FeatureContext.php @@ -74,6 +74,7 @@ class FeatureContext implements Context { private ?array $relationsData = null; /** @var list> */ private array $listedObjects = []; + private ?\SimpleXMLElement $xmlData = null; /** * FeatureContext constructor. @@ -1772,6 +1773,102 @@ public function userListsRowsV2InTheObjectShape(string $user, string $nodeType, $this->listedObjects = $this->getDataFromResponse($this->response)['ocs']['data']['results']; } + /** + * @When user :user gets row :rowAlias of :nodeType :nodeAlias using v2 in the object shape as XML + */ + public function userGetsRowV2InTheObjectShapeAsXml(string $user, string $rowAlias, string $nodeType, string $nodeAlias): void { + $this->setCurrentUser($user); + $node = $this->collectionManager->getByAlias($nodeType, $nodeAlias); + $row = $this->collectionManager->getByAlias('row', $rowAlias); + $this->sendOcsRequest('GET', sprintf('/apps/tables/api/2/%ss/%d/rows/%s?shape=object&format=xml', $nodeType, $node['id'], $row['uuid'])); + $this->xmlData = $this->xmlDataFromResponse(); + } + + /** + * @When user :user creates a row in :nodeType :nodeAlias using v2 in the object shape as XML with + * + * @param TableNode $properties property names and values as JSON + */ + public function userCreatesRowV2InTheObjectShapeAsXml(string $user, string $nodeType, string $nodeAlias, TableNode $properties): void { + $this->setCurrentUser($user); + $node = $this->collectionManager->getByAlias($nodeType, $nodeAlias); + $data = []; + foreach ($properties->getRows() as $row) { + $data[$row[0]] = json_decode($row[1], true, 512, JSON_THROW_ON_ERROR); + } + $this->sendOcsRequest('POST', sprintf('/apps/tables/api/2/%ss/%d/rows?format=xml', $nodeType, $node['id']), [ + 'data' => json_encode($data, JSON_THROW_ON_ERROR), + 'shape' => 'object', + ]); + $this->xmlData = $this->xmlDataFromResponse(); + } + + private function xmlDataFromResponse(): \SimpleXMLElement { + $body = (string)$this->response->getBody(); + Assert::assertStringStartsWith('application/xml', $this->response->getHeaderLine('Content-Type'), $body); + $document = simplexml_load_string($body); + Assert::assertNotFalse($document, $body); + return $document->data; + } + + /** + * @Then the XML object is row :rowAlias with following values + * + * @param TableNode $properties column aliases and the expected inner XML of their element, or nil + */ + public function theXmlObjectIsRowWithFollowingValues(string $rowAlias, TableNode $properties): void { + Assert::assertEquals(200, $this->response->getStatusCode()); + $row = $this->collectionManager->getByAlias('row', $rowAlias); + Assert::assertSame($row['uuid'], (string)$this->xmlData->self['id']); + Assert::assertSame((string)$row['id'], (string)$this->xmlData->self['rowId']); + foreach ($properties->getRows() as $property) { + $technicalName = $this->collectionManager->getByAlias('column', $property[0])['technicalName']; + $element = $this->xmlData->{$technicalName}; + Assert::assertCount(1, $element, $technicalName); + $this->assertXmlValue($property[1], $element, $technicalName); + } + } + + /** + * @Then the XML object of row :rowAlias has the uuid of row :targetRowAlias as :columnAlias + */ + public function theXmlObjectRelatesTo(string $rowAlias, string $targetRowAlias, string $columnAlias): void { + Assert::assertSame($this->collectionManager->getByAlias('row', $rowAlias)['uuid'], (string)$this->xmlData->self['id']); + $technicalName = $this->collectionManager->getByAlias('column', $columnAlias)['technicalName']; + Assert::assertSame($this->collectionManager->getByAlias('row', $targetRowAlias)['uuid'], (string)$this->xmlData->{$technicalName}); + } + + /** + * @Then the XML validation error has following errors + * + * @param TableNode $errors property names and the expected message + */ + public function theXmlValidationErrorHasFollowingErrors(TableNode $errors): void { + Assert::assertEquals(400, $this->response->getStatusCode()); + $actual = []; + foreach ($this->xmlData->errors->children() as $name => $element) { + $actual[$name === 'element' ? (string)$element['name'] : $name] = $name === 'element' ? (string)$element->value : (string)$element; + } + $expected = $errors->getRowsHash(); + ksort($expected); + ksort($actual); + Assert::assertSame($expected, $actual); + } + + private function assertXmlValue(string $expected, \SimpleXMLElement $element, string $name): void { + if ($expected === 'nil') { + Assert::assertSame('true', (string)$element['nil'], $name); + Assert::assertSame('', (string)$element, $name); + return; + } + Assert::assertNull($element['nil'], $name); + $inner = ''; + foreach ($element->children() as $child) { + $inner .= $child->asXML(); + } + Assert::assertSame($expected, $inner === '' ? (string)$element : $inner, $name); + } + /** * @Then the listed objects have exactly the properties :columnAliasList */ diff --git a/tests/unit/Controller/RowOCSControllerTest.php b/tests/unit/Controller/RowOCSControllerTest.php index 45f99c0fe4..11940e9b52 100644 --- a/tests/unit/Controller/RowOCSControllerTest.php +++ b/tests/unit/Controller/RowOCSControllerTest.php @@ -21,6 +21,7 @@ use OCA\Tables\Model\RowObjectInput; use OCA\Tables\Service\FederationService; use OCA\Tables\Service\RowObjectSerializer; +use OCA\Tables\Service\RowObjectXmlShaper; use OCA\Tables\Service\RowService; use OCA\Tables\Service\TableService; use OCA\Tables\Service\ViewService; @@ -60,6 +61,7 @@ protected function setUp(): void { $this->createMock(ViewService::class), $this->federationService, $this->rowObjectSerializer, + new RowObjectXmlShaper(), ); } @@ -281,37 +283,88 @@ public static function xmlResponseFormat(): array { /** * @dataProvider xmlResponseFormat */ - public function testObjectShapeIsRefusedForAnXmlResponse(?string $format): void { + public function testObjectShapeIsReadAsXmlForAnXmlResponse(?string $format): void { $this->responseFormat = $format; $this->rowService->method('resolveRowId')->willReturn(7); $this->rowService->method('findInNode')->willReturn($this->row(7)); $this->rowService->method('findPage')->willReturn(['rows' => [$this->row(7)], 'total' => 1]); - $this->rowObjectSerializer->method('serialize')->willReturn(['@self' => ['id' => self::UUID], 'name' => 'Alice']); - $this->rowObjectSerializer->method('serializeAll')->willReturn([['@self' => ['id' => self::UUID], 'name' => 'Alice']]); + $object = ['@self' => ['id' => self::UUID, 'rowId' => 7, 'updatedBy' => null], 'name' => 'Alice', 'age' => null]; + $this->rowObjectSerializer->method('serialize')->willReturn($object); + $this->rowObjectSerializer->method('serializeAll')->willReturn([$object]); + $shaped = ['self' => ['@attributes' => ['id' => self::UUID, 'rowId' => '7']], 'name' => 'Alice', 'age' => ['@attributes' => ['nil' => 'true']]]; - foreach ([$this->controller->getRow('tables', 3, self::UUID, 'object'), $this->controller->getRows('tables', 3, shape: 'object')] as $response) { - $this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus()); - $this->assertSame(['message' => 'The object shape is only available as JSON.'], $response->getData()); - $this->assertStringContainsString('The object shape is only available as JSON.', (new V2Response($response, 'xml'))->render()); + $row = $this->controller->getRow('tables', 3, self::UUID, 'object'); + $rows = $this->controller->getRows('tables', 3, shape: 'object'); + + $this->assertSame(Http::STATUS_OK, $row->getStatus()); + $this->assertSame($shaped, $row->getData()); + $this->assertSame(Http::STATUS_OK, $rows->getStatus()); + $this->assertSame([$shaped], $rows->getData()['results']); + $xml = simplexml_load_string((new V2Response($row, 'xml'))->render()); + $this->assertSame(self::UUID, (string)$xml->data->self['id']); + $this->assertSame('Alice', (string)$xml->data->name); + $this->assertSame('true', (string)$xml->data->age['nil']); + } + + /** + * @dataProvider xmlResponseFormat + */ + public function testAnObjectShapeWriteIsAnsweredAsXmlForAnXmlResponse(?string $format): void { + $this->responseFormat = $format; + $this->rowService->method('resolveRowId')->willReturn(7); + $this->rowService->expects($this->once())->method('create')->willReturn($this->row(7)); + $this->rowService->expects($this->once())->method('updateSet')->willReturn($this->row(7)); + $this->rowObjectSerializer->method('serialize')->willReturn(['@self' => ['rowId' => 7], 'done' => true]); + + foreach ([ + $this->controller->createRow('tables', 3, ['done' => true], 'object'), + $this->controller->updateRow('tables', 3, self::UUID, ['done' => true], 'object'), + ] as $response) { + $this->assertSame(Http::STATUS_OK, $response->getStatus()); + $this->assertSame(['self' => ['@attributes' => ['rowId' => '7']], 'done' => 'true'], $response->getData()); } - $this->assertSame(Http::STATUS_OK, $this->controller->getRow('tables', 3, self::UUID, 'cells')->getStatus()); - $this->assertSame(Http::STATUS_OK, $this->controller->getRows('tables', 3, shape: 'cells')->getStatus()); + } + + public function testTheObjectShapeIsNotShapedForXmlInAJsonResponse(): void { + $this->rowService->method('resolveRowId')->willReturn(7); + $this->rowService->method('findInNode')->willReturn($this->row(7)); + $object = ['@self' => ['id' => self::UUID, 'updatedBy' => null], 'done' => true, 'age' => null]; + $this->rowObjectSerializer->method('serialize')->willReturn($object); + + $this->assertSame($object, $this->controller->getRow('tables', 3, self::UUID, 'object')->getData()); } /** * @dataProvider xmlResponseFormat */ - public function testAnObjectShapeWriteIsRefusedForAnXmlResponseBeforeAnythingIsWritten(?string $format): void { + public function testTheCellsShapeIsNotShapedForXml(?string $format): void { $this->responseFormat = $format; - $this->rowService->expects($this->never())->method('create'); - $this->rowService->expects($this->never())->method('updateSet'); + $this->rowService->method('resolveRowId')->willReturn(7); + $this->rowService->method('findInNode')->willReturn($this->row(7)); + $this->rowObjectSerializer->expects($this->never())->method('serialize'); + + $this->assertSame($this->row(7)->jsonSerialize(), $this->controller->getRow('tables', 3, self::UUID, 'cells')->getData()); + } + + /** + * @dataProvider xmlResponseFormat + */ + public function testInvalidValuesAreNamedInTheXmlResponse(?string $format): void { + $this->responseFormat = $format; + $this->rowService->method('resolveRowId')->willReturn(7); + $this->rowService->method('create')->willThrowException(new RowValidationError(['age' => 'Expected a number.', 'first name' => 'There is no column with this technical name.'])); + $this->rowService->method('updateSet')->willThrowException(new RowValidationError(['age' => 'Expected a number.', 'first name' => 'There is no column with this technical name.'])); foreach ([ - $this->controller->createRow('tables', 3, ['name' => 'Alice'], 'object'), - $this->controller->updateRow('tables', 3, self::UUID, ['name' => 'Alice'], 'object'), + $this->controller->createRow('tables', 3, ['age' => 'many', 'first name' => 'x'], 'object'), + $this->controller->updateRow('tables', 3, '7', ['age' => 'many', 'first name' => 'x'], 'object'), ] as $response) { $this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus()); - $this->assertSame(['message' => 'The object shape is only available as JSON.'], $response->getData()); + $xml = simplexml_load_string((new V2Response($response, 'xml'))->render()); + $this->assertSame('The row has 2 invalid values.', (string)$xml->data->message); + $this->assertSame('Expected a number.', (string)$xml->data->errors->age); + $this->assertSame('first name', (string)$xml->data->errors->element['name']); + $this->assertSame('There is no column with this technical name.', (string)$xml->data->errors->element->value); } } diff --git a/tests/unit/Service/RowObjectXmlShaperTest.php b/tests/unit/Service/RowObjectXmlShaperTest.php new file mode 100644 index 0000000000..668d00c139 --- /dev/null +++ b/tests/unit/Service/RowObjectXmlShaperTest.php @@ -0,0 +1,257 @@ + ['nil' => 'true']]; + + private RowObjectXmlShaper $shaper; + + protected function setUp(): void { + $this->shaper = new RowObjectXmlShaper(); + } + + /** + * @return array{'@self': array{id: ?string, rowId: int, tableId: int, createdBy: ?string, createdAt: ?string, updatedBy: ?string, updatedAt: ?string}} + */ + private function self(?string $uuid = self::UUID): array { + return ['@self' => [ + 'id' => $uuid, + 'rowId' => 7, + 'tableId' => 3, + 'createdBy' => 'alice', + 'createdAt' => '2026-10-16T14:30:00+00:00', + 'updatedBy' => null, + 'updatedAt' => null, + ]]; + } + + public function testSelfBecomesAnElementWithAnAttributePerMember(): void { + $this->assertSame( + ['self' => ['@attributes' => [ + 'id' => self::UUID, + 'rowId' => '7', + 'tableId' => '3', + 'createdBy' => 'alice', + 'createdAt' => '2026-10-16T14:30:00+00:00', + ]]], + $this->shaper->shapeRow($this->self()), + ); + } + + public function testANullSelfMemberIsLeftOut(): void { + $attributes = $this->shaper->shapeRow($this->self(null))['self']['@attributes']; + + $this->assertArrayNotHasKey('id', $attributes); + $this->assertArrayNotHasKey('updatedBy', $attributes); + $this->assertArrayNotHasKey('updatedAt', $attributes); + $this->assertSame('7', $attributes['rowId']); + } + + public function testScalarsBecomeText(): void { + $shaped = $this->shaper->shapeRow($this->self() + [ + 'name' => 'Alice', + 'age' => 42, + 'height' => 1.75, + 'whole' => 2.0, + 'done' => true, + 'open' => false, + ]); + + $this->assertSame('Alice', $shaped['name']); + $this->assertSame('42', $shaped['age']); + $this->assertSame('1.75', $shaped['height']); + $this->assertSame(json_encode(2.0), $shaped['whole']); + $this->assertSame('true', $shaped['done']); + $this->assertSame('false', $shaped['open']); + } + + public function testNullIsNilAndAnEmptyStringIsNot(): void { + $shaped = $this->shaper->shapeRow($this->self() + ['missing' => null, 'blank' => '']); + + $this->assertSame(self::NIL, $shaped['missing']); + $this->assertSame('', $shaped['blank']); + } + + public function testAListHasAnElementPerItemAndAnEmptyListIsNotNil(): void { + $shaped = $this->shaper->shapeRow($this->self() + ['options' => [2, 5], 'tags' => [], 'mixed' => [true, null]]); + + $this->assertSame(['2', '5'], $shaped['options']); + $this->assertSame([], $shaped['tags']); + $this->assertSame(['true', self::NIL], $shaped['mixed']); + } + + public function testAnObjectHasAChildElementPerPropertyByTheSameRules(): void { + $shaped = $this->shaper->shapeRow($this->self() + [ + 'website' => ['title' => 'Nextcloud', 'url' => 'https://nextcloud.com', 'providerId' => 'url'], + 'people' => [ + ['id' => 'alice', 'type' => 0, 'displayName' => 'Alice'], + ['id' => 'team', 'type' => 1, 'displayName' => null], + ], + ]); + + $this->assertSame(['title' => 'Nextcloud', 'url' => 'https://nextcloud.com', 'providerId' => 'url'], $shaped['website']); + $this->assertSame([ + ['id' => 'alice', 'type' => '0', 'displayName' => 'Alice'], + ['id' => 'team', 'type' => '1', 'displayName' => self::NIL], + ], $shaped['people']); + } + + /** + * @return array + */ + public static function unsafeNames(): array { + return [ + 'a number' => [12], + 'a leading digit' => ['1st'], + 'a space' => ['first name'], + 'a colon' => ['a:b'], + 'an at sign, which OCS writes as an attribute' => ['@attributes'], + 'a dollar sign, which OCS writes as a comment' => ['$comment'], + 'the name of a list item' => ['element'], + 'the name of the metadata' => ['self'], + ]; + } + + /** + * @dataProvider unsafeNames + */ + public function testAnUnsafeNameFallsBackToANamedElement(int|string $name): void { + $shaped = $this->shaper->shapeRow($this->self() + [$name => 'Alice', 'next' => 'Bob']); + + $this->assertSame([ + 'self', + 0, + 'next', + ], array_keys($shaped)); + $this->assertSame(['@attributes' => ['name' => (string)$name], 'value' => 'Alice'], $shaped[0]); + } + + public function testTheFallbackHoldsNilListsAndObjectsByTheSameRules(): void { + $shaped = $this->shaper->shapeRow($this->self() + [ + '1' => null, + '2' => [4, 5], + '3' => ['title' => 'Nextcloud', '4' => true], + ]); + + $this->assertSame(['@attributes' => ['name' => '1'], 'value' => self::NIL], $shaped[0]); + $this->assertSame(['@attributes' => ['name' => '2'], '4', '5'], $shaped[1]); + $this->assertSame(['@attributes' => ['name' => '3'], 'title' => 'Nextcloud', ['@attributes' => ['name' => '4'], 'value' => 'true']], $shaped[2]); + } + + public function testUnicodeLettersAreSafeNames(): void { + $this->assertSame('Ja', $this->shaper->shapeRow($this->self() + ['größe' => 'Ja'])['größe']); + } + + public function testShapeRowsShapesEachRow(): void { + $this->assertSame( + [['self' => ['@attributes' => ['id' => 'a', 'rowId' => '1']], 'name' => 'Alice'], ['self' => ['@attributes' => ['rowId' => '2']], 'name' => self::NIL]], + $this->shaper->shapeRows([ + ['@self' => ['id' => 'a', 'rowId' => 1], 'name' => 'Alice'], + ['@self' => ['id' => null, 'rowId' => 2], 'name' => null], + ]), + ); + } + + public function testAValidationErrorHasAnElementPerName(): void { + $this->assertSame( + ['message' => 'The row has 3 invalid values.', 'errors' => [ + 'age' => 'Expected a number.', + ['@attributes' => ['name' => 'first name'], 'value' => 'There is no column with this technical name.'], + ['@attributes' => ['name' => '@self'], 'value' => 'There is no column with this technical name.'], + ]], + $this->shaper->shapeValidationError(['message' => 'The row has 3 invalid values.', 'errors' => [ + 'age' => 'Expected a number.', + 'first name' => 'There is no column with this technical name.', + '@self' => 'There is no column with this technical name.', + ]]), + ); + } + + private function renderXml(mixed $data, int $status = Http::STATUS_OK, bool $v1 = false): \SimpleXMLElement { + $response = new DataResponse($data, $status); + $xml = ($v1 ? new V1Response($response, 'xml') : new V2Response($response, 'xml'))->render(); + $document = simplexml_load_string($xml); + $this->assertNotFalse($document, $xml); + return $document; + } + + public function testAShapedPageRendersAsOcsXml(): void { + $object = $this->self() + [ + 'name' => 'Alice', + 'options' => [2, 5], + 'tags' => [], + 'website' => ['title' => 'Nextcloud', 'url' => 'https://nextcloud.com/?a=1&b=<2>', 'providerId' => 'url'], + 'starts' => null, + 'blank' => '', + 'done' => false, + '12' => 'imported', + ]; + + foreach ([false, true] as $v1) { + $document = $this->renderXml(['results' => $this->shaper->shapeRows([$object]), 'total' => 1], v1: $v1); + + $this->assertSame('1', (string)$document->data->total); + $row = $document->data->results->element[0]; + $this->assertCount(1, $document->data->results->element); + $this->assertSame(self::UUID, (string)$row->self['id']); + $this->assertSame('7', (string)$row->self['rowId']); + $this->assertSame('alice', (string)$row->self['createdBy']); + $this->assertNull($row->self['updatedBy']); + $this->assertSame('', (string)$row->self); + $this->assertSame('Alice', (string)$row->name); + $this->assertSame(['2', '5'], array_map(strval(...), iterator_to_array($row->options->element, false))); + $this->assertCount(0, $row->tags->children()); + $this->assertNull($row->tags['nil']); + $this->assertSame('https://nextcloud.com/?a=1&b=<2>', (string)$row->website->url); + $this->assertSame('Nextcloud', (string)$row->website->title); + $this->assertSame('true', (string)$row->starts['nil']); + $this->assertSame('', (string)$row->starts); + $this->assertNull($row->blank['nil']); + $this->assertSame('', (string)$row->blank); + $this->assertSame('false', (string)$row->done); + $this->assertSame('12', (string)$row->element['name']); + $this->assertSame('imported', (string)$row->element->value); + } + } + + public function testAShapedRowRendersAsOcsXmlAndTheUnshapedOneDoesNot(): void { + $object = $this->self() + ['name' => 'Alice']; + + $this->assertSame('Alice', (string)$this->renderXml($this->shaper->shapeRow($object))->data->name); + + $this->expectException(\TypeError::class); + (new V2Response(new DataResponse($object), 'xml'))->render(); + } + + public function testAShapedValidationErrorRendersAsOcsXml(): void { + $document = $this->renderXml( + $this->shaper->shapeValidationError(['message' => 'The row has 2 invalid values.', 'errors' => [ + 'age' => 'Expected a number.', + '@self' => 'There is no column with this technical name.', + ]]), + Http::STATUS_BAD_REQUEST, + ); + + $this->assertSame('400', (string)$document->meta->statuscode); + $this->assertSame('The row has 2 invalid values.', (string)$document->data->message); + $this->assertSame('Expected a number.', (string)$document->data->errors->age); + $this->assertSame('@self', (string)$document->data->errors->element['name']); + $this->assertSame('There is no column with this technical name.', (string)$document->data->errors->element->value); + } +} From b31cba6d56fe4b96556268fbedde9bca8cf2b780 Mon Sep 17 00:00:00 2001 From: Robert Zondervan Date: Thu, 19 Nov 2026 15:12:43 +0100 Subject: [PATCH 3/8] =?UTF-8?q?fix(review):=20#67=20f1=20=E2=80=94=20only?= =?UTF-8?q?=20ASCII=20names=20become=20XML=20elements?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit XMLWriter refuses some names that Unicode counts as letters (µ, Dž, 𝒜), so a row key or a validation-error key such as {"µ":1} threw a ValueError while OCS rendered the XML, a 500 after the controller returned. The direct element name is now ASCII only, anything else takes the fallback. The pattern also gets the D modifier, so a trailing newline no longer slips past `$`. The docblocks and the openapi parameter text describe the new rule; the test renders µ, Dž, ᐁ, 𝒜 and größe as row and error keys through V1 and V2 and fails without the fix. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Robert Zondervan --- lib/Controller/RowOCSController.php | 4 +- lib/Service/RowObjectXmlShaper.php | 18 ++++++--- openapi.json | 4 +- src/types/openapi/openapi.ts | 4 +- tests/unit/Service/RowObjectXmlShaperTest.php | 38 +++++++++++++++++-- 5 files changed, 52 insertions(+), 16 deletions(-) diff --git a/lib/Controller/RowOCSController.php b/lib/Controller/RowOCSController.php index 016689cb89..d4eabf3481 100644 --- a/lib/Controller/RowOCSController.php +++ b/lib/Controller/RowOCSController.php @@ -153,7 +153,7 @@ public function createRow(string $nodeCollection, int $nodeId, mixed $data, ?str * @param string|null $search Text to look for in the text cells and the selection labels * @param string|null $fields Comma separated technical names or column ids of the columns to return, the metadata of a row is always returned * @param array>|null $filter Filters as filter[field]=value or filter[field][operator]=value, all of which must match. A deep object in the query string (for example filter[age][is-greater-than]=30&filter[name]=jane), shown as a string because the API description cannot express nested query parameters. field is a technical name, a column id or a meta field; operator is one of the view filter operators that fit the field's type (without one: is-equal, or contains-item on multi-value columns; long and rich text need an operator such as contains); a value is compared as given and written as the column stores it: a decimal number; a row id for relations and id; YYYY-MM-DD HH:MM for date and time columns, YYYY-MM-DD for date columns, HH:MM for time columns; YYYY-MM-DD with an optional HH:MM or HH:MM:SS, after a space or a T, for createdAt and updatedAt, in UTC unless the time ends in Z or an offset such as +02:00 (written %2B02:00 in the query string, where + means a space), an exact moment, so compare those with is-greater-than and is-lower-than rather than is-equal; an option id for selections; true or false for checkboxes; a user, group or team id for usergroup columns - * @param 'cells'|'object'|null $shape The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules + * @param 'cells'|'object'|null $shape The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules * @return DataResponse|DataResponse * * 200: Rows returned @@ -216,7 +216,7 @@ public function getRows( * @param 'tables'|'views' $nodeCollection Indicates whether to get a row from a table or view * @param int $nodeId The identifier of the targeted table or view * @param string $rowId The identifier of the row, either its integer id or its uuid - * @param 'cells'|'object'|null $shape The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules + * @param 'cells'|'object'|null $shape The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules * @return DataResponse|DataResponse * * 200: Row returned diff --git a/lib/Service/RowObjectXmlShaper.php b/lib/Service/RowObjectXmlShaper.php index 8642b226a6..7022cb9701 100644 --- a/lib/Service/RowObjectXmlShaper.php +++ b/lib/Service/RowObjectXmlShaper.php @@ -17,10 +17,11 @@ * * - the metadata in `@self` becomes `` with a member per attribute, an attribute * whose value is null is left out; - * - a property becomes an element named by its key; a key that is not an XML NCName, or - * that is `element` (or `self` for a row), becomes ``, with the - * value in `` when it is not a list or an object, because an OCS element cannot - * have attributes and text; + * - a property becomes an element named by its key; a key that is not an ASCII XML name + * (a letter or `_`, then letters, digits, `_`, `.` or `-`), or that is `element` (or + * `self` for a row), becomes ``, with the value in `` when + * it is not a list or an object, because an OCS element cannot have attributes and + * text; * - null becomes an empty element with `nil="true"`, unprefixed because an undeclared * prefix such as `xsi:` is not namespace-well-formed; an empty string or an empty list * becomes an empty element without it; @@ -32,7 +33,12 @@ * @psalm-import-type TablesRowValidationError from ResponseDefinitions */ class RowObjectXmlShaper { - private const NCNAME = '/^[\p{L}_][\p{L}\p{N}_.\-]*$/u'; + /** + * ASCII only: XMLWriter, which renders OCS XML, refuses some names that Unicode counts + * as letters (such as `µ` or `Dž`), which would make a 500 after the controller returned. + * `D` keeps `$` from matching before a trailing newline. + */ + private const SAFE_NAME = '/^[A-Za-z_][A-Za-z0-9_.\-]*$/D'; private const LIST_ITEM = 'element'; private const SELF = 'self'; @@ -103,7 +109,7 @@ private function shapeObject(array $object): array { */ private function addProperty(array &$shaped, int|string $key, mixed $value, array $reservedNames): void { $name = (string)$key; - if (preg_match(self::NCNAME, $name) === 1 && !in_array($name, $reservedNames, true)) { + if (preg_match(self::SAFE_NAME, $name) === 1 && !in_array($name, $reservedNames, true)) { $shaped[$name] = $this->shapeValue($value); return; } diff --git a/openapi.json b/openapi.json index 6bd0dbd97d..f3a1483651 100644 --- a/openapi.json +++ b/openapi.json @@ -16860,7 +16860,7 @@ { "name": "shape", "in": "query", - "description": "The shape of the returned rows, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", + "description": "The shape of the returned rows, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", "schema": { "type": "string", "nullable": true, @@ -17155,7 +17155,7 @@ { "name": "shape", "in": "query", - "description": "The shape of the returned row, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", + "description": "The shape of the returned row, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", "schema": { "type": "string", "nullable": true, diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 9b774118f7..2a91b21aaf 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -8827,7 +8827,7 @@ export interface operations { readonly fields?: string | null; /** @description Filters as filter[field]=value or filter[field][operator]=value, all of which must match. A deep object in the query string (for example filter[age][is-greater-than]=30&filter[name]=jane), shown as a string because the API description cannot express nested query parameters. field is a technical name, a column id or a meta field; operator is one of the view filter operators that fit the field's type (without one: is-equal, or contains-item on multi-value columns; long and rich text need an operator such as contains); a value is compared as given and written as the column stores it: a decimal number; a row id for relations and id; YYYY-MM-DD HH:MM for date and time columns, YYYY-MM-DD for date columns, HH:MM for time columns; YYYY-MM-DD with an optional HH:MM or HH:MM:SS, after a space or a T, for createdAt and updatedAt, in UTC unless the time ends in Z or an offset such as +02:00 (written %2B02:00 in the query string, where + means a space), an exact moment, so compare those with is-greater-than and is-lower-than rather than is-equal; an option id for selections; true or false for checkboxes; a user, group or team id for usergroup columns */ readonly filter?: string | null; - /** @description The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ + /** @description The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ readonly shape?: "cells" | "object" | null; }; readonly header: { @@ -9067,7 +9067,7 @@ export interface operations { readonly "rowocs-get-row": { readonly parameters: { readonly query?: { - /** @description The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an XML NCName, or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ + /** @description The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ readonly shape?: "cells" | "object" | null; }; readonly header: { diff --git a/tests/unit/Service/RowObjectXmlShaperTest.php b/tests/unit/Service/RowObjectXmlShaperTest.php index 668d00c139..2abe4580ab 100644 --- a/tests/unit/Service/RowObjectXmlShaperTest.php +++ b/tests/unit/Service/RowObjectXmlShaperTest.php @@ -125,6 +125,8 @@ public static function unsafeNames(): array { 'a dollar sign, which OCS writes as a comment' => ['$comment'], 'the name of a list item' => ['element'], 'the name of the metadata' => ['self'], + 'a trailing newline' => ["name\n"], + 'a non-ASCII letter' => ['größe'], ]; } @@ -154,10 +156,6 @@ public function testTheFallbackHoldsNilListsAndObjectsByTheSameRules(): void { $this->assertSame(['@attributes' => ['name' => '3'], 'title' => 'Nextcloud', ['@attributes' => ['name' => '4'], 'value' => 'true']], $shaped[2]); } - public function testUnicodeLettersAreSafeNames(): void { - $this->assertSame('Ja', $this->shaper->shapeRow($this->self() + ['größe' => 'Ja'])['größe']); - } - public function testShapeRowsShapesEachRow(): void { $this->assertSame( [['self' => ['@attributes' => ['id' => 'a', 'rowId' => '1']], 'name' => 'Alice'], ['self' => ['@attributes' => ['rowId' => '2']], 'name' => self::NIL]], @@ -230,6 +228,38 @@ public function testAShapedPageRendersAsOcsXml(): void { } } + /** + * XMLWriter refuses some names that Unicode counts as letters, so only ASCII names + * become elements. + */ + public function testNonAsciiNamesRenderAsNamedElements(): void { + $names = ['µ', 'Dž', 'ᐁ', '𝒜', 'größe']; + $object = $this->self(); + $errors = []; + foreach ($names as $name) { + $object[$name] = 'value of ' . $name; + $errors[$name] = 'There is no column with this technical name.'; + } + + foreach ([false, true] as $v1) { + $row = $this->renderXml($this->shaper->shapeRow($object), v1: $v1)->data; + $error = $this->renderXml( + $this->shaper->shapeValidationError(['message' => 'The row has 5 invalid values.', 'errors' => $errors]), + Http::STATUS_BAD_REQUEST, + $v1, + )->data->errors; + + $this->assertCount(count($names), $row->element); + $this->assertCount(count($names), $error->element); + foreach ($names as $i => $name) { + $this->assertSame($name, (string)$row->element[$i]['name']); + $this->assertSame('value of ' . $name, (string)$row->element[$i]->value); + $this->assertSame($name, (string)$error->element[$i]['name']); + $this->assertSame('There is no column with this technical name.', (string)$error->element[$i]->value); + } + } + } + public function testAShapedRowRendersAsOcsXmlAndTheUnshapedOneDoesNot(): void { $object = $this->self() + ['name' => 'Alice']; From e8c2dcf386af648a6fafc65ae5fef02410cfd7e0 Mon Sep 17 00:00:00 2001 From: Robert Zondervan Date: Thu, 19 Nov 2026 15:16:16 +0100 Subject: [PATCH 4/8] =?UTF-8?q?fix(review):=20#67=20f2=20=E2=80=94=20repla?= =?UTF-8?q?ce=20characters=20XML=20does=20not=20allow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit XMLWriter writes control characters and invalid UTF-8 as they are, so an unknown key such as "a\u0001" or "\xff" in made a document that is not well-formed. The same held for text and for the @self attribute values, which go through text() as well. The fallback name and every string text() returns are now scrubbed: invalid UTF-8 and characters outside the XML 1.0 Char production become U+FFFD. The test renders such keys, a value and a @self member through V1 and V2, loads them with DOMDocument and fails without the fix. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Robert Zondervan --- lib/Service/RowObjectXmlShaper.php | 24 +++++++++++-- tests/unit/Service/RowObjectXmlShaperTest.php | 34 +++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/lib/Service/RowObjectXmlShaper.php b/lib/Service/RowObjectXmlShaper.php index 7022cb9701..71d6788ddc 100644 --- a/lib/Service/RowObjectXmlShaper.php +++ b/lib/Service/RowObjectXmlShaper.php @@ -26,6 +26,10 @@ * prefix such as `xsi:` is not namespace-well-formed; an empty string or an empty list * becomes an empty element without it; * - booleans become `true` and `false`, numbers are written as JSON writes them; + * - text, attribute values and the name in `` hold only characters + * XML 1.0 allows: invalid UTF-8 and other characters, such as control characters, + * become U+FFFD, because XMLWriter writes them as they are and the document would not + * be well-formed; * - a list becomes `` children, an object child elements by key, both by the * same rules. * @@ -39,6 +43,9 @@ class RowObjectXmlShaper { * `D` keeps `$` from matching before a trailing newline. */ private const SAFE_NAME = '/^[A-Za-z_][A-Za-z0-9_.\-]*$/D'; + /** A character XML 1.0 does not allow. */ + private const NOT_XML_CHAR = '/[^\x{9}\x{A}\x{D}\x{20}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]/u'; + private const REPLACEMENT_CHARACTER = "\u{FFFD}"; private const LIST_ITEM = 'element'; private const SELF = 'self'; @@ -113,7 +120,7 @@ private function addProperty(array &$shaped, int|string $key, mixed $value, arra $shaped[$name] = $this->shapeValue($value); return; } - $fallback = ['@attributes' => ['name' => $name]]; + $fallback = ['@attributes' => ['name' => $this->xmlString($name)]]; if (is_array($value)) { $shaped[] = $fallback + $this->shapeArray($value); return; @@ -144,8 +151,21 @@ private function text(mixed $value): string { return match (true) { is_bool($value) => $value ? 'true' : 'false', is_float($value) => json_encode($value, JSON_THROW_ON_ERROR), - is_scalar($value) => (string)$value, + is_scalar($value) => $this->xmlString((string)$value), default => json_encode($value, JSON_THROW_ON_ERROR), }; } + + private function xmlString(string $value): string { + if (!mb_check_encoding($value, 'UTF-8')) { + $substitute = mb_substitute_character(); + mb_substitute_character(0xFFFD); + try { + $value = mb_scrub($value, 'UTF-8'); + } finally { + mb_substitute_character($substitute); + } + } + return preg_replace(self::NOT_XML_CHAR, self::REPLACEMENT_CHARACTER, $value) ?? $value; + } } diff --git a/tests/unit/Service/RowObjectXmlShaperTest.php b/tests/unit/Service/RowObjectXmlShaperTest.php index 2abe4580ab..63585ac2a9 100644 --- a/tests/unit/Service/RowObjectXmlShaperTest.php +++ b/tests/unit/Service/RowObjectXmlShaperTest.php @@ -260,6 +260,40 @@ public function testNonAsciiNamesRenderAsNamedElements(): void { } } + /** + * XMLWriter writes characters XML does not allow as they are, so the shaper replaces + * them and the document stays well-formed. + */ + public function testCharactersXmlDoesNotAllowBecomeReplacementCharacters(): void { + $object = $this->self(); + $object['@self']['createdBy'] = "al\x01ice"; + $object["a\x01"] = "control\x01"; + $object["\xff"] = "invalid\xff"; + $errors = ["a\x01" => 'There is no column with this technical name.', "\xff" => 'There is no column with this technical name.']; + + foreach ([false, true] as $v1) { + foreach ([ + [$this->shaper->shapeRow($object), Http::STATUS_OK], + [$this->shaper->shapeValidationError(['message' => 'The row has 2 invalid values.', 'errors' => $errors]), Http::STATUS_BAD_REQUEST], + ] as [$data, $status]) { + $xml = ($v1 ? new V1Response(new DataResponse($data, $status), 'xml') : new V2Response(new DataResponse($data, $status), 'xml'))->render(); + $document = new \DOMDocument(); + $this->assertTrue($document->loadXML($xml), $xml); + + $names = []; + foreach ((new \DOMXPath($document))->query('//element[@name]') as $element) { + $this->assertInstanceOf(\DOMElement::class, $element); + $names[$element->getAttribute('name')] = $element->getElementsByTagName('value')->item(0)?->textContent; + } + $this->assertSame(["a\u{FFFD}", "\u{FFFD}"], array_keys($names)); + if ($status === Http::STATUS_OK) { + $this->assertSame(["control\u{FFFD}", "invalid\u{FFFD}"], array_values($names)); + $this->assertSame("al\u{FFFD}ice", $document->getElementsByTagName('self')->item(0)?->getAttribute('createdBy')); + } + } + } + } + public function testAShapedRowRendersAsOcsXmlAndTheUnshapedOneDoesNot(): void { $object = $this->self() + ['name' => 'Alice']; From 1125128a86cfa2402955fe155575d0b365da25ad Mon Sep 17 00:00:00 2001 From: Robert Zondervan Date: Thu, 19 Nov 2026 15:18:31 +0100 Subject: [PATCH 5/8] =?UTF-8?q?docs(review):=20#67=20f3=20=E2=80=94=20note?= =?UTF-8?q?=20that=20the=20fallback=20cannot=20tell=20"x"=20from=20{"value?= =?UTF-8?q?":"x"}?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under , a scalar is held in , so it renders the same as an object whose only property is value. No column type gives such an object; the shaper's class docblock and the openapi text of the shape parameter now say so. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Robert Zondervan --- lib/Controller/RowOCSController.php | 4 ++-- lib/Service/RowObjectXmlShaper.php | 4 +++- openapi.json | 4 ++-- src/types/openapi/openapi.ts | 4 ++-- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/Controller/RowOCSController.php b/lib/Controller/RowOCSController.php index d4eabf3481..2c26016c22 100644 --- a/lib/Controller/RowOCSController.php +++ b/lib/Controller/RowOCSController.php @@ -153,7 +153,7 @@ public function createRow(string $nodeCollection, int $nodeId, mixed $data, ?str * @param string|null $search Text to look for in the text cells and the selection labels * @param string|null $fields Comma separated technical names or column ids of the columns to return, the metadata of a row is always returned * @param array>|null $filter Filters as filter[field]=value or filter[field][operator]=value, all of which must match. A deep object in the query string (for example filter[age][is-greater-than]=30&filter[name]=jane), shown as a string because the API description cannot express nested query parameters. field is a technical name, a column id or a meta field; operator is one of the view filter operators that fit the field's type (without one: is-equal, or contains-item on multi-value columns; long and rich text need an operator such as contains); a value is compared as given and written as the column stores it: a decimal number; a row id for relations and id; YYYY-MM-DD HH:MM for date and time columns, YYYY-MM-DD for date columns, HH:MM for time columns; YYYY-MM-DD with an optional HH:MM or HH:MM:SS, after a space or a T, for createdAt and updatedAt, in UTC unless the time ends in Z or an offset such as +02:00 (written %2B02:00 in the query string, where + means a space), an exact moment, so compare those with is-greater-than and is-lower-than rather than is-equal; an option id for selections; true or false for checkboxes; a user, group or team id for usergroup columns - * @param 'cells'|'object'|null $shape The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules + * @param 'cells'|'object'|null $shape The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object, so there a scalar and an object with only a value property look the same (no column type gives such an object). null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules * @return DataResponse|DataResponse * * 200: Rows returned @@ -216,7 +216,7 @@ public function getRows( * @param 'tables'|'views' $nodeCollection Indicates whether to get a row from a table or view * @param int $nodeId The identifier of the targeted table or view * @param string $rowId The identifier of the row, either its integer id or its uuid - * @param 'cells'|'object'|null $shape The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules + * @param 'cells'|'object'|null $shape The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object, so there a scalar and an object with only a value property look the same (no column type gives such an object). null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules * @return DataResponse|DataResponse * * 200: Row returned diff --git a/lib/Service/RowObjectXmlShaper.php b/lib/Service/RowObjectXmlShaper.php index 71d6788ddc..8967b365ae 100644 --- a/lib/Service/RowObjectXmlShaper.php +++ b/lib/Service/RowObjectXmlShaper.php @@ -21,7 +21,9 @@ * (a letter or `_`, then letters, digits, `_`, `.` or `-`), or that is `element` (or * `self` for a row), becomes ``, with the value in `` when * it is not a list or an object, because an OCS element cannot have attributes and - * text; + * text; so under the fallback a scalar `"x"` and an object `{"value": "x"}` render + * the same, which no column type runs into, because none gives an object with a + * `value` property; * - null becomes an empty element with `nil="true"`, unprefixed because an undeclared * prefix such as `xsi:` is not namespace-well-formed; an empty string or an empty list * becomes an empty element without it; diff --git a/openapi.json b/openapi.json index f3a1483651..a01f6cfd8f 100644 --- a/openapi.json +++ b/openapi.json @@ -16860,7 +16860,7 @@ { "name": "shape", "in": "query", - "description": "The shape of the returned rows, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", + "description": "The shape of the returned rows, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object, so there a scalar and an object with only a value property look the same (no column type gives such an object). null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", "schema": { "type": "string", "nullable": true, @@ -17155,7 +17155,7 @@ { "name": "shape", "in": "query", - "description": "The shape of the returned row, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", + "description": "The shape of the returned row, defaults to \"cells\". With \"object\" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object, so there a scalar and an object with only a value property look the same (no column type gives such an object). null is an empty element with nil=\"true\", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules", "schema": { "type": "string", "nullable": true, diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 2a91b21aaf..5057db5ac4 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -8827,7 +8827,7 @@ export interface operations { readonly fields?: string | null; /** @description Filters as filter[field]=value or filter[field][operator]=value, all of which must match. A deep object in the query string (for example filter[age][is-greater-than]=30&filter[name]=jane), shown as a string because the API description cannot express nested query parameters. field is a technical name, a column id or a meta field; operator is one of the view filter operators that fit the field's type (without one: is-equal, or contains-item on multi-value columns; long and rich text need an operator such as contains); a value is compared as given and written as the column stores it: a decimal number; a row id for relations and id; YYYY-MM-DD HH:MM for date and time columns, YYYY-MM-DD for date columns, HH:MM for time columns; YYYY-MM-DD with an optional HH:MM or HH:MM:SS, after a space or a T, for createdAt and updatedAt, in UTC unless the time ends in Z or an offset such as +02:00 (written %2B02:00 in the query string, where + means a space), an exact moment, so compare those with is-greater-than and is-lower-than rather than is-equal; an option id for selections; true or false for checkboxes; a user, group or team id for usergroup columns */ readonly filter?: string | null; - /** @description The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ + /** @description The shape of the returned rows, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object, so there a scalar and an object with only a value property look the same (no column type gives such an object). null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ readonly shape?: "cells" | "object" | null; }; readonly header: { @@ -9067,7 +9067,7 @@ export interface operations { readonly "rowocs-get-row": { readonly parameters: { readonly query?: { - /** @description The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object. null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ + /** @description The shape of the returned row, defaults to "cells". With "object" a row is one object with a property per column, keyed by its technical name and null without a value: datetimes with the offset of the instance timezone, links as {title, url, providerId}, relations as the uuid of the target row (its row id while it has no uuid yet, null when it no longer exists), and the metadata in @self, with its times in UTC. In XML a row is an element holding , with the metadata as attributes and an attribute without a value left out, and an element per column named by its technical name; a name that is not an ASCII XML name (a letter or _, then letters, digits, _, . or -), or is element or self, becomes , which holds the value in unless it is a list or an object, so there a scalar and an object with only a value property look the same (no column type gives such an object). null is an empty element with nil="true", unprefixed because xsi:nil would need a namespace declaration; an empty string or list is an empty element without it. Booleans are true and false, a list has an per item and an object a child element per property, by the same rules */ readonly shape?: "cells" | "object" | null; }; readonly header: { From 51d301fe1a4d0753d7997950d888dd03f8e4894e Mon Sep 17 00:00:00 2001 From: Robert Zondervan Date: Wed, 2 Dec 2026 14:53:27 +0100 Subject: [PATCH 6/8] test(rows): give XML self the numeric id and the uuid, without rowId The object shape's @self now has id as the row id and uuid as the uuid (3096/1); the XML tests use that metadata, so carries id and uuid, leaves uuid out when it is null and has no rowId. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Robert Zondervan --- .../unit/Controller/RowOCSControllerTest.php | 20 ++++++++------- tests/unit/Service/RowObjectXmlShaperTest.php | 25 ++++++++++--------- 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/tests/unit/Controller/RowOCSControllerTest.php b/tests/unit/Controller/RowOCSControllerTest.php index d5a66f99f5..9f84347f64 100644 --- a/tests/unit/Controller/RowOCSControllerTest.php +++ b/tests/unit/Controller/RowOCSControllerTest.php @@ -32,12 +32,12 @@ use Psr\Log\LoggerInterface; class RowOCSControllerTest extends TestCase { + private const UUID = '0199e3a0-1f2b-7c3d-8e4f-5a6b7c8d9e0f'; + private RowService&MockObject $rowService; private TableService&MockObject $tableService; private FederationService&MockObject $federationService; private RowObjectSerializer&MockObject $rowObjectSerializer; - private const UUID = '0199e3a0-1f2b-7c3d-8e4f-5a6b7c8d9e0f'; - private RowOCSController $controller; private ?string $responseFormat = 'json'; @@ -67,7 +67,7 @@ protected function setUp(): void { private function row(int $rowId): Row2 { $row = new Row2(); $row->setId($rowId); - $row->setUuid('0199e3a0-1f2b-7c3d-8e4f-5a6b7c8d9e0f'); + $row->setUuid(self::UUID); $row->setTableId(3); return $row; } @@ -224,10 +224,10 @@ public function testObjectShapeIsReadAsXmlForAnXmlResponse(?string $format): voi $this->responseFormat = $format; $this->rowService->method('findInNode')->willReturn($this->row(7)); $this->rowService->method('findPage')->willReturn(['rows' => [$this->row(7)], 'total' => 1]); - $object = ['@self' => ['id' => self::UUID, 'rowId' => 7, 'updatedBy' => null], 'name' => 'Alice', 'age' => null]; + $object = ['@self' => ['id' => 7, 'uuid' => self::UUID, 'updatedBy' => null], 'name' => 'Alice', 'age' => null]; $this->rowObjectSerializer->method('serialize')->willReturn($object); $this->rowObjectSerializer->method('serializeAll')->willReturn([$object]); - $shaped = ['self' => ['@attributes' => ['id' => self::UUID, 'rowId' => '7']], 'name' => 'Alice', 'age' => ['@attributes' => ['nil' => 'true']]]; + $shaped = ['self' => ['@attributes' => ['id' => '7', 'uuid' => self::UUID]], 'name' => 'Alice', 'age' => ['@attributes' => ['nil' => 'true']]]; $row = $this->controller->getRow('tables', 3, 7, 'object'); $rows = $this->controller->getRows('tables', 3, shape: 'object'); @@ -237,7 +237,9 @@ public function testObjectShapeIsReadAsXmlForAnXmlResponse(?string $format): voi $this->assertSame(Http::STATUS_OK, $rows->getStatus()); $this->assertSame([$shaped], $rows->getData()['results']); $xml = simplexml_load_string((new V2Response($row, 'xml'))->render()); - $this->assertSame(self::UUID, (string)$xml->data->self['id']); + $this->assertSame('7', (string)$xml->data->self['id']); + $this->assertSame(self::UUID, (string)$xml->data->self['uuid']); + $this->assertNull($xml->data->self['rowId']); $this->assertSame('Alice', (string)$xml->data->name); $this->assertSame('true', (string)$xml->data->age['nil']); } @@ -249,20 +251,20 @@ public function testAnObjectShapeWriteIsAnsweredAsXmlForAnXmlResponse(?string $f $this->responseFormat = $format; $this->rowService->expects($this->once())->method('create')->willReturn($this->row(7)); $this->rowService->expects($this->once())->method('updateSet')->willReturn($this->row(7)); - $this->rowObjectSerializer->method('serialize')->willReturn(['@self' => ['rowId' => 7], 'done' => true]); + $this->rowObjectSerializer->method('serialize')->willReturn(['@self' => ['id' => 7, 'uuid' => null], 'done' => true]); foreach ([ $this->controller->createRow('tables', 3, ['done' => true], 'object'), $this->controller->updateRow('tables', 3, 7, ['done' => true], 'object'), ] as $response) { $this->assertSame(Http::STATUS_OK, $response->getStatus()); - $this->assertSame(['self' => ['@attributes' => ['rowId' => '7']], 'done' => 'true'], $response->getData()); + $this->assertSame(['self' => ['@attributes' => ['id' => '7']], 'done' => 'true'], $response->getData()); } } public function testTheObjectShapeIsNotShapedForXmlInAJsonResponse(): void { $this->rowService->method('findInNode')->willReturn($this->row(7)); - $object = ['@self' => ['id' => self::UUID, 'updatedBy' => null], 'done' => true, 'age' => null]; + $object = ['@self' => ['id' => 7, 'uuid' => self::UUID, 'updatedBy' => null], 'done' => true, 'age' => null]; $this->rowObjectSerializer->method('serialize')->willReturn($object); $this->assertSame($object, $this->controller->getRow('tables', 3, 7, 'object')->getData()); diff --git a/tests/unit/Service/RowObjectXmlShaperTest.php b/tests/unit/Service/RowObjectXmlShaperTest.php index 63585ac2a9..2fb8a9b8a8 100644 --- a/tests/unit/Service/RowObjectXmlShaperTest.php +++ b/tests/unit/Service/RowObjectXmlShaperTest.php @@ -27,12 +27,12 @@ protected function setUp(): void { } /** - * @return array{'@self': array{id: ?string, rowId: int, tableId: int, createdBy: ?string, createdAt: ?string, updatedBy: ?string, updatedAt: ?string}} + * @return array{'@self': array{id: int, uuid: ?string, tableId: int, createdBy: ?string, createdAt: ?string, updatedBy: ?string, updatedAt: ?string}} */ private function self(?string $uuid = self::UUID): array { return ['@self' => [ - 'id' => $uuid, - 'rowId' => 7, + 'id' => 7, + 'uuid' => $uuid, 'tableId' => 3, 'createdBy' => 'alice', 'createdAt' => '2026-10-16T14:30:00+00:00', @@ -44,8 +44,8 @@ private function self(?string $uuid = self::UUID): array { public function testSelfBecomesAnElementWithAnAttributePerMember(): void { $this->assertSame( ['self' => ['@attributes' => [ - 'id' => self::UUID, - 'rowId' => '7', + 'id' => '7', + 'uuid' => self::UUID, 'tableId' => '3', 'createdBy' => 'alice', 'createdAt' => '2026-10-16T14:30:00+00:00', @@ -57,10 +57,10 @@ public function testSelfBecomesAnElementWithAnAttributePerMember(): void { public function testANullSelfMemberIsLeftOut(): void { $attributes = $this->shaper->shapeRow($this->self(null))['self']['@attributes']; - $this->assertArrayNotHasKey('id', $attributes); + $this->assertArrayNotHasKey('uuid', $attributes); $this->assertArrayNotHasKey('updatedBy', $attributes); $this->assertArrayNotHasKey('updatedAt', $attributes); - $this->assertSame('7', $attributes['rowId']); + $this->assertSame('7', $attributes['id']); } public function testScalarsBecomeText(): void { @@ -158,10 +158,10 @@ public function testTheFallbackHoldsNilListsAndObjectsByTheSameRules(): void { public function testShapeRowsShapesEachRow(): void { $this->assertSame( - [['self' => ['@attributes' => ['id' => 'a', 'rowId' => '1']], 'name' => 'Alice'], ['self' => ['@attributes' => ['rowId' => '2']], 'name' => self::NIL]], + [['self' => ['@attributes' => ['id' => '1', 'uuid' => 'a']], 'name' => 'Alice'], ['self' => ['@attributes' => ['id' => '2']], 'name' => self::NIL]], $this->shaper->shapeRows([ - ['@self' => ['id' => 'a', 'rowId' => 1], 'name' => 'Alice'], - ['@self' => ['id' => null, 'rowId' => 2], 'name' => null], + ['@self' => ['id' => 1, 'uuid' => 'a'], 'name' => 'Alice'], + ['@self' => ['id' => 2, 'uuid' => null], 'name' => null], ]), ); } @@ -207,8 +207,9 @@ public function testAShapedPageRendersAsOcsXml(): void { $this->assertSame('1', (string)$document->data->total); $row = $document->data->results->element[0]; $this->assertCount(1, $document->data->results->element); - $this->assertSame(self::UUID, (string)$row->self['id']); - $this->assertSame('7', (string)$row->self['rowId']); + $this->assertSame('7', (string)$row->self['id']); + $this->assertSame(self::UUID, (string)$row->self['uuid']); + $this->assertNull($row->self['rowId']); $this->assertSame('alice', (string)$row->self['createdBy']); $this->assertNull($row->self['updatedBy']); $this->assertSame('', (string)$row->self); From 4759ad552a28f4a59db9a8dd646f7073ebdee0ac Mon Sep 17 00:00:00 2001 From: Robert Zondervan Date: Wed, 2 Dec 2026 14:59:39 +0100 Subject: [PATCH 7/8] test(rows): read the XML object shape by row id and check id and uuid A uuid in the row path matches no route since 3096/2, so the XML GET step uses the row id. is checked for id = the row id and uuid = the row's uuid, without rowId, and a relation is compared with the row id of its target ("has the row id of row ... as ..."). Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Robert Zondervan --- tests/integration/features/APIv2.feature | 2 +- .../features/bootstrap/FeatureContext.php | 16 +++++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/integration/features/APIv2.feature b/tests/integration/features/APIv2.feature index 320c7bd112..49e15063f8 100644 --- a/tests/integration/features/APIv2.feature +++ b/tests/integration/features/APIv2.feature @@ -893,7 +893,7 @@ Feature: APIv2 | amount | nil | | done | true | | website | Nextcloudhttps://nextcloud.comurl | - And the XML object of row "xml-first" has the uuid of row "xml-target" as "project" + And the XML object of row "xml-first" has the row id of row "xml-target" as "project" When user "participant1-v2" creates a row in table "xml-shape" using v2 in the object shape as XML with | missing | "x" | | 1st | "x" | diff --git a/tests/integration/features/bootstrap/FeatureContext.php b/tests/integration/features/bootstrap/FeatureContext.php index def5e5fca9..d47037dbf6 100644 --- a/tests/integration/features/bootstrap/FeatureContext.php +++ b/tests/integration/features/bootstrap/FeatureContext.php @@ -1780,7 +1780,7 @@ public function userGetsRowV2InTheObjectShapeAsXml(string $user, string $rowAlia $this->setCurrentUser($user); $node = $this->collectionManager->getByAlias($nodeType, $nodeAlias); $row = $this->collectionManager->getByAlias('row', $rowAlias); - $this->sendOcsRequest('GET', sprintf('/apps/tables/api/2/%ss/%d/rows/%s?shape=object&format=xml', $nodeType, $node['id'], $row['uuid'])); + $this->sendOcsRequest('GET', sprintf('/apps/tables/api/2/%ss/%d/rows/%d?shape=object&format=xml', $nodeType, $node['id'], $row['id'])); $this->xmlData = $this->xmlDataFromResponse(); } @@ -1819,8 +1819,10 @@ private function xmlDataFromResponse(): \SimpleXMLElement { public function theXmlObjectIsRowWithFollowingValues(string $rowAlias, TableNode $properties): void { Assert::assertEquals(200, $this->response->getStatusCode()); $row = $this->collectionManager->getByAlias('row', $rowAlias); - Assert::assertSame($row['uuid'], (string)$this->xmlData->self['id']); - Assert::assertSame((string)$row['id'], (string)$this->xmlData->self['rowId']); + Assert::assertSame((string)$row['id'], (string)$this->xmlData->self['id']); + Assert::assertNotEmpty($row['uuid']); + Assert::assertSame($row['uuid'], (string)$this->xmlData->self['uuid']); + Assert::assertNull($this->xmlData->self['rowId']); foreach ($properties->getRows() as $property) { $technicalName = $this->collectionManager->getByAlias('column', $property[0])['technicalName']; $element = $this->xmlData->{$technicalName}; @@ -1830,12 +1832,12 @@ public function theXmlObjectIsRowWithFollowingValues(string $rowAlias, TableNode } /** - * @Then the XML object of row :rowAlias has the uuid of row :targetRowAlias as :columnAlias + * @Then the XML object of row :rowAlias has the row id of row :targetRowAlias as :columnAlias */ - public function theXmlObjectRelatesTo(string $rowAlias, string $targetRowAlias, string $columnAlias): void { - Assert::assertSame($this->collectionManager->getByAlias('row', $rowAlias)['uuid'], (string)$this->xmlData->self['id']); + public function theXmlObjectHasTheRowIdOfRowAs(string $rowAlias, string $targetRowAlias, string $columnAlias): void { + Assert::assertSame((string)$this->collectionManager->getByAlias('row', $rowAlias)['id'], (string)$this->xmlData->self['id']); $technicalName = $this->collectionManager->getByAlias('column', $columnAlias)['technicalName']; - Assert::assertSame($this->collectionManager->getByAlias('row', $targetRowAlias)['uuid'], (string)$this->xmlData->{$technicalName}); + Assert::assertSame((string)$this->collectionManager->getByAlias('row', $targetRowAlias)['id'], (string)$this->xmlData->{$technicalName}); } /** From 93c9e7e8758335cde772355cc361b4aa28acf3cb Mon Sep 17 00:00:00 2001 From: Robert Zondervan Date: Wed, 2 Dec 2026 15:41:45 +0100 Subject: [PATCH 8/8] test(rows): XML elements keep the order of the object's properties Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Robert Zondervan --- tests/unit/Service/RowObjectXmlShaperTest.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/unit/Service/RowObjectXmlShaperTest.php b/tests/unit/Service/RowObjectXmlShaperTest.php index 2fb8a9b8a8..6d551e65dd 100644 --- a/tests/unit/Service/RowObjectXmlShaperTest.php +++ b/tests/unit/Service/RowObjectXmlShaperTest.php @@ -156,6 +156,16 @@ public function testTheFallbackHoldsNilListsAndObjectsByTheSameRules(): void { $this->assertSame(['@attributes' => ['name' => '3'], 'title' => 'Nextcloud', ['@attributes' => ['name' => '4'], 'value' => 'true']], $shaped[2]); } + public function testTheElementsKeepTheOrderOfTheProperties(): void { + $document = $this->renderXml($this->shaper->shapeRow($this->self() + ['zeta' => 'z', 'alpha' => 'a', 'first name' => 'f', 'mid' => 'm'])); + + $names = []; + foreach ($document->data->children() as $name => $element) { + $names[] = $name === 'element' ? (string)$element['name'] : $name; + } + $this->assertSame(['self', 'zeta', 'alpha', 'first name', 'mid'], $names); + } + public function testShapeRowsShapesEachRow(): void { $this->assertSame( [['self' => ['@attributes' => ['id' => '1', 'uuid' => 'a']], 'name' => 'Alice'], ['self' => ['@attributes' => ['id' => '2']], 'name' => self::NIL]],