From d5cdb06dc7bd45980c9bad1922f3272a3d14a947 Mon Sep 17 00:00:00 2001 From: Jeremy Dormitzer Date: Sat, 2 Mar 2019 17:23:53 -0500 Subject: [PATCH] Leverage the totalItems field for O(1) collection adding if present --- src/Objects/CollectionsService.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Objects/CollectionsService.php b/src/Objects/CollectionsService.php index 6fefaa6..4895eaf 100644 --- a/src/Objects/CollectionsService.php +++ b/src/Objects/CollectionsService.php @@ -283,9 +283,14 @@ class CollectionsService if ( !$items instanceof ActivityPubObject ) { throw new Exception( 'Attempted to add an item to a collection with a non-object items field' ); } - // This is making the assumption that $items *only* contains numeric fields (i.e., it is an array) - // Also, it's O(n) on the size of the collection - $itemCount = count( $items->getFields() ); + if ( $collection->hasField( 'totalItems' ) && is_numeric( $collection['totalItems'] ) ) { + // This will break if some other server puts in an incorrect value for totalItems + $itemCount = intval( $collection['totalItems'] ); + } else { + // This is making the assumption that $items *only* contains numeric fields (i.e., it is an array) + // Also, it's O(n) on the size of the collection + $itemCount = count( $items->getFields() ); + } if ( is_array( $item ) ) { $item = $this->objectsService->persist( $item, 'collections-service.add' ); $newItemField = Field::withObject(