From b4bc51c8ef6885e1e806411f27784964520f156e Mon Sep 17 00:00:00 2001 From: Sneha Sahu Date: Tue, 27 Oct 2026 19:55:12 +0000 Subject: [PATCH] feat(storage): add delete object contexts sample Adds delete_object_contexts.php (region tag storage_delete_object_contexts) that clears all custom contexts on an object with a metageneration precondition, plus a PHPUnit test. Internal bug: b/482946642 [Generated-by: AI] --- storage/src/delete_object_contexts.php | 66 ++++++++++++++++++++++++++ storage/test/ObjectsTest.php | 13 +++-- 2 files changed, 74 insertions(+), 5 deletions(-) create mode 100644 storage/src/delete_object_contexts.php diff --git a/storage/src/delete_object_contexts.php b/storage/src/delete_object_contexts.php new file mode 100644 index 000000000..4fc90dc6e --- /dev/null +++ b/storage/src/delete_object_contexts.php @@ -0,0 +1,66 @@ +bucket($bucketName); + $object = $bucket->object($objectName); + + // Fetch the current metageneration so the update can be made conditional. + $info = $object->info(); + + // To delete all contexts, set the 'custom' key to null, which is sent as a + // JSON null and clears every context. Do not use an empty PHP array: it + // serializes as a JSON list ([]) rather than an empty map. + // Optional: set a metageneration-match precondition to avoid potential + // race conditions and data corruptions. The request to update is aborted + // if the object's metageneration does not match your precondition. + $object->update([ + 'contexts' => [ + 'custom' => null, + ], + ], [ + 'ifMetagenerationMatch' => $info['metageneration'], + ]); + + printf('Deleted object contexts for object %s in bucket %s.' . PHP_EOL, $objectName, $bucketName); +} +# [END storage_delete_object_contexts] + +// The following 2 lines are only needed to run the samples +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/storage/test/ObjectsTest.php b/storage/test/ObjectsTest.php index 5f1acc644..c6260fde8 100644 --- a/storage/test/ObjectsTest.php +++ b/storage/test/ObjectsTest.php @@ -77,12 +77,15 @@ public function testObjectContexts() ]); $this->assertStringContainsString("Found object: $objectInfo", $listOutput); - // Clear all contexts on the object. - $object->update([ - 'contexts' => [ - 'custom' => null, - ], + // Delete all contexts on the object. + $deleteOutput = $this->runFunctionSnippet('delete_object_contexts', [ + $bucketName, + $objectInfo, ]); + $this->assertStringContainsString( + "Deleted object contexts for object $objectInfo in bucket $bucketName.", + $deleteOutput + ); $object->reload(); $clearedGetOutput = $this->runFunctionSnippet('get_object_contexts', [