diff --git a/lib/Controller/RowOCSController.php b/lib/Controller/RowOCSController.php index d4fe872a95..9c61ee18fc 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, as the object shape reads a row: a relation as the row id or the label of its target, where labels are checked before row ids and the first row with a matching label wins, so an integer is always a row id and a numeric string is tried as a label first; an @self block, its id and uuid included, is ignored - * @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, in the column order of the table or view, 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 row id of the target row (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, in the column order of the table or view, 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 row id of the target row (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 @@ -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 int $rowId The identifier of the row - * @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, in the column order of the table or view, 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 row id of the target row (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, in the column order of the table or view, 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 row id of the target row (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 - * 400: An unknown shape or the object shape for a response that is not JSON, or the table or view is federated + * 400: 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, int $rowId, ?string [$tableId, $viewId] = $this->splitNode($nodeCollection, $nodeId); try { try { - $rowShape = $this->rowShapeFromRequest($shape); + $rowShape = RowShape::fromRequest($shape); } catch (\InvalidArgumentException $e) { throw new BadRequestError($e->getMessage()); } @@ -256,11 +258,11 @@ public function getRow(string $nodeCollection, int $nodeId, int $rowId, ?string * @param int $nodeId The identifier of the targeted table or view * @param int $rowId The identifier of the row to update * @param string|array $data The values to change: keyed by column id, or with shape "object" keyed by technical name, as the object shape reads a row: a relation as the row id or the label of its target, where labels are checked before row ids and the first row with a matching label wins, so an integer is always a row id and a numeric string is tried as a label first; an @self block, its id and uuid included, is ignored - * @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 @@ -270,7 +272,7 @@ public function getRow(string $nodeCollection, int $nodeId, int $rowId, ?string #[ApiRoute(verb: 'PUT', url: '/api/2/{nodeCollection}/{nodeId}/rows/{rowId}', requirements: ['nodeCollection' => '(tables|views)', 'nodeId' => '(\d+)', 'rowId' => '(\d+)'])] public function updateRow(string $nodeCollection, int $nodeId, int $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())); } @@ -299,7 +301,7 @@ public function updateRow(string $nodeCollection, int $nodeId, int $rowId, mixed } return new DataResponse($this->shapeRow($this->rowService->updateSet($rowId, $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, int $rowId): Data } /** - * 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..8967b365ae --- /dev/null +++ b/lib/Service/RowObjectXmlShaper.php @@ -0,0 +1,173 @@ +` 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 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; 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; + * - 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. + * + * @psalm-import-type TablesRowObject from ResponseDefinitions + * @psalm-import-type TablesRowValidationError from ResponseDefinitions + */ +class RowObjectXmlShaper { + /** + * 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'; + /** 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'; + + /** + * @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::SAFE_NAME, $name) === 1 && !in_array($name, $reservedNames, true)) { + $shaped[$name] = $this->shapeValue($value); + return; + } + $fallback = ['@attributes' => ['name' => $this->xmlString($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) => $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/openapi.json b/openapi.json index e06c128777..92dd2439f4 100644 --- a/openapi.json +++ b/openapi.json @@ -16441,7 +16441,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" } } } @@ -16523,7 +16523,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": { @@ -16823,7 +16823,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, in the column order of the table or view, 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 row id of the target row (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, in the column order of the table or view, 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 row id of the target row (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, @@ -17119,7 +17119,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, in the column order of the table or view, 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 row id of the target row (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, in the column order of the table or view, 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 row id of the target row (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, @@ -17218,7 +17218,7 @@ } }, "400": { - "description": "An unknown shape or the object shape for a response that is not JSON, or the table or view is federated", + "description": "An unknown shape, or the table or view is federated", "content": { "application/json": { "schema": { @@ -17407,7 +17407,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" } } } @@ -17499,7 +17499,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 750c03c523..5082996be0 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -8811,7 +8811,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, in the column order of the table or view, 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 row id of the target row (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, in the column order of the table or view, 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 row id of the target row (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: { @@ -8945,7 +8945,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} */ @@ -8968,7 +8968,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; @@ -9051,7 +9051,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, in the column order of the table or view, 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 row id of the target row (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, in the column order of the table or view, 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 row id of the target row (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: { @@ -9084,7 +9084,7 @@ export interface operations { }; }; }; - /** @description An unknown shape or the object shape for a response that is not JSON, or the table or view is federated */ + /** @description An unknown shape, or the table or view is federated */ readonly 400: { headers: { readonly [name: string]: unknown; @@ -9189,7 +9189,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} */ @@ -9212,7 +9212,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; diff --git a/tests/integration/features/APIv2.feature b/tests/integration/features/APIv2.feature index 3bc1d595f6..f00de466e7 100644 --- a/tests/integration/features/APIv2.feature +++ b/tests/integration/features/APIv2.feature @@ -866,6 +866,53 @@ Feature: APIv2 When user "participant1-v2" gets row "source" of table "object-write" using v2 in the object shape Then the listed object of row "source" has the row id of row "alpha" as "target" + @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 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" | + 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 b991b90570..d47037dbf6 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,104 @@ 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/%d?shape=object&format=xml', $nodeType, $node['id'], $row['id'])); + $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((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}; + Assert::assertCount(1, $element, $technicalName); + $this->assertXmlValue($property[1], $element, $technicalName); + } + } + + /** + * @Then the XML object of row :rowAlias has the row id of row :targetRowAlias as :columnAlias + */ + 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((string)$this->collectionManager->getByAlias('row', $targetRowAlias)['id'], (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); + } + /** * Reads one row; when it is found it is the only listed object, for the steps below. * diff --git a/tests/unit/Controller/RowOCSControllerTest.php b/tests/unit/Controller/RowOCSControllerTest.php index 06ced959ab..9f84347f64 100644 --- a/tests/unit/Controller/RowOCSControllerTest.php +++ b/tests/unit/Controller/RowOCSControllerTest.php @@ -20,6 +20,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; @@ -31,6 +32,8 @@ 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; @@ -57,13 +60,14 @@ protected function setUp(): void { $this->createMock(ViewService::class), $this->federationService, $this->rowObjectSerializer, + new RowObjectXmlShaper(), ); } 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; } @@ -216,36 +220,85 @@ 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('findInNode')->willReturn($this->row(7)); $this->rowService->method('findPage')->willReturn(['rows' => [$this->row(7)], 'total' => 1]); - $this->rowObjectSerializer->method('serialize')->willReturn(['@self' => ['id' => 7], 'name' => 'Alice']); - $this->rowObjectSerializer->method('serializeAll')->willReturn([['@self' => ['id' => 7], 'name' => 'Alice']]); + $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' => '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'); + + $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('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']); + } - foreach ([$this->controller->getRow('tables', 3, 7, '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()); + /** + * @dataProvider xmlResponseFormat + */ + public function testAnObjectShapeWriteIsAnsweredAsXmlForAnXmlResponse(?string $format): void { + $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' => ['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' => ['id' => '7']], 'done' => 'true'], $response->getData()); } - $this->assertSame(Http::STATUS_OK, $this->controller->getRow('tables', 3, 7, 'cells')->getStatus()); - $this->assertSame(Http::STATUS_OK, $this->controller->getRows('tables', 3, shape: 'cells')->getStatus()); + } + + public function testTheObjectShapeIsNotShapedForXmlInAJsonResponse(): void { + $this->rowService->method('findInNode')->willReturn($this->row(7)); + $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()); } /** * @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('findInNode')->willReturn($this->row(7)); + $this->rowObjectSerializer->expects($this->never())->method('serialize'); + + $this->assertSame($this->row(7)->jsonSerialize(), $this->controller->getRow('tables', 3, 7, 'cells')->getData()); + } + + /** + * @dataProvider xmlResponseFormat + */ + public function testInvalidValuesAreNamedInTheXmlResponse(?string $format): void { + $this->responseFormat = $format; + $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, 7, ['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..6d551e65dd --- /dev/null +++ b/tests/unit/Service/RowObjectXmlShaperTest.php @@ -0,0 +1,332 @@ + ['nil' => 'true']]; + + private RowObjectXmlShaper $shaper; + + protected function setUp(): void { + $this->shaper = new RowObjectXmlShaper(); + } + + /** + * @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' => 7, + 'uuid' => $uuid, + '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' => '7', + 'uuid' => self::UUID, + '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('uuid', $attributes); + $this->assertArrayNotHasKey('updatedBy', $attributes); + $this->assertArrayNotHasKey('updatedAt', $attributes); + $this->assertSame('7', $attributes['id']); + } + + 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'], + 'a trailing newline' => ["name\n"], + 'a non-ASCII letter' => ['größe'], + ]; + } + + /** + * @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 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]], + $this->shaper->shapeRows([ + ['@self' => ['id' => 1, 'uuid' => 'a'], 'name' => 'Alice'], + ['@self' => ['id' => 2, 'uuid' => null], '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('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); + $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); + } + } + + /** + * 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); + } + } + } + + /** + * 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']; + + $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); + } +}