diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 5518429c9e..7a211eadda 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -9,7 +9,7 @@ jobs: styles: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Install PHP uses: shivammathur/setup-php@v2 with: @@ -21,14 +21,14 @@ jobs: staticanalysis: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Install PHP uses: shivammathur/setup-php@v2 with: php-version: '8.2' - name: Get changed files id: changedFiles - uses: tj-actions/changed-files@v46 + uses: tj-actions/changed-files@v47 - name: Run Script run: | composer install -d testing/ diff --git a/.kokoro/secrets-example.sh b/.kokoro/secrets-example.sh index 1b1dd312a7..74c4167519 100644 --- a/.kokoro/secrets-example.sh +++ b/.kokoro/secrets-example.sh @@ -100,6 +100,10 @@ export GOOGLE_KMS_SERVICEACCOUNTEMAIL= export REDIS_HOST= export REDIS_PORT= +# Model Armor +export MA_FOLDER_ID= +export MA_ORG_ID= + # PubSub export GOOGLE_PUBSUB_SUBSCRIPTION=php-example-subscription export GOOGLE_PUBSUB_TOPIC=php-example-topic diff --git a/.kokoro/secrets.sh.enc b/.kokoro/secrets.sh.enc index a69536b95c..cf97be8bf8 100644 Binary files a/.kokoro/secrets.sh.enc and b/.kokoro/secrets.sh.enc differ diff --git a/analyticsdata/composer.json b/analyticsdata/composer.json index 0be81e0c27..47387775f0 100644 --- a/analyticsdata/composer.json +++ b/analyticsdata/composer.json @@ -1,5 +1,5 @@ { "require": { - "google/analytics-data": "^0.22.0" + "google/analytics-data": "^0.23.0" } } diff --git a/analyticsdata/quickstart_oauth2/composer.json b/analyticsdata/quickstart_oauth2/composer.json index 7eef0e118c..59f6620a1a 100644 --- a/analyticsdata/quickstart_oauth2/composer.json +++ b/analyticsdata/quickstart_oauth2/composer.json @@ -1,6 +1,6 @@ { "require": { - "google/analytics-data": "^0.22.0", + "google/analytics-data": "^0.23.0", "ext-bcmath": "*" } } diff --git a/appengine/standard/errorreporting/composer.json b/appengine/standard/errorreporting/composer.json index b0a4fadaff..6d62b104c2 100644 --- a/appengine/standard/errorreporting/composer.json +++ b/appengine/standard/errorreporting/composer.json @@ -1,6 +1,6 @@ { "require": { - "google/cloud-error-reporting": "^0.23.0" + "google/cloud-error-reporting": "^0.25.0" }, "autoload": { "files": [ diff --git a/appengine/standard/grpc/composer.json b/appengine/standard/grpc/composer.json index 6fe6aca5b2..c45499a04a 100644 --- a/appengine/standard/grpc/composer.json +++ b/appengine/standard/grpc/composer.json @@ -1,6 +1,6 @@ { "require": { - "google/cloud-spanner": "^1.15.0", + "google/cloud-spanner": "^2.0.0", "google/cloud-monitoring": "^2.0.0", "google/cloud-speech": "^2.0.0" }, diff --git a/compute/firewall/composer.json b/compute/firewall/composer.json index 64feccc5f3..5b16ac87ee 100644 --- a/compute/firewall/composer.json +++ b/compute/firewall/composer.json @@ -1,5 +1,5 @@ { "require": { - "google/cloud-compute": "^1.14" + "google/cloud-compute": "^2.0" } } diff --git a/compute/firewall/src/create_firewall_rule.php b/compute/firewall/src/create_firewall_rule.php index de281f864e..a4b9550c3e 100644 --- a/compute/firewall/src/create_firewall_rule.php +++ b/compute/firewall/src/create_firewall_rule.php @@ -26,13 +26,8 @@ # [START compute_firewall_create] use Google\Cloud\Compute\V1\Allowed; use Google\Cloud\Compute\V1\Client\FirewallsClient; -use Google\Cloud\Compute\V1\Enums\Firewall\Direction; - -/** - * To correctly handle string enums in Cloud Compute library - * use constants defined in the Enums subfolder. - */ use Google\Cloud\Compute\V1\Firewall; +use Google\Cloud\Compute\V1\Firewall\Direction; use Google\Cloud\Compute\V1\InsertFirewallRequest; /** @@ -57,7 +52,7 @@ function create_firewall_rule(string $projectId, string $firewallRuleName, strin ->setPorts(['80', '443']); $firewallResource = (new Firewall()) ->setName($firewallRuleName) - ->setDirection(Direction::INGRESS) + ->setDirection(Direction::name(Direction::INGRESS)) ->setAllowed([$allowedPorts]) ->setSourceRanges(['0.0.0.0/0']) ->setTargetTags(['web']) diff --git a/compute/helloworld/composer.json b/compute/helloworld/composer.json index 64feccc5f3..5b16ac87ee 100644 --- a/compute/helloworld/composer.json +++ b/compute/helloworld/composer.json @@ -1,5 +1,5 @@ { "require": { - "google/cloud-compute": "^1.14" + "google/cloud-compute": "^2.0" } } diff --git a/compute/instances/composer.json b/compute/instances/composer.json index 4f0bf93c86..b65563baa8 100644 --- a/compute/instances/composer.json +++ b/compute/instances/composer.json @@ -1,6 +1,6 @@ { "require": { - "google/cloud-compute": "^1.14", + "google/cloud-compute": "^2.0", "google/cloud-storage": "^1.36" } } diff --git a/compute/instances/src/create_instance.php b/compute/instances/src/create_instance.php index c8e0fe6589..c59353dde6 100644 --- a/compute/instances/src/create_instance.php +++ b/compute/instances/src/create_instance.php @@ -25,9 +25,9 @@ # [START compute_instances_create] use Google\Cloud\Compute\V1\AttachedDisk; +use Google\Cloud\Compute\V1\AttachedDisk\Type; use Google\Cloud\Compute\V1\AttachedDiskInitializeParams; use Google\Cloud\Compute\V1\Client\InstancesClient; -use Google\Cloud\Compute\V1\Enums\AttachedDisk\Type; use Google\Cloud\Compute\V1\InsertInstanceRequest; /** @@ -67,7 +67,7 @@ function create_instance( $disk = (new AttachedDisk()) ->setBoot(true) ->setAutoDelete(true) - ->setType(Type::PERSISTENT) + ->setType(Type::name(Type::PERSISTENT)) ->setInitializeParams($diskInitializeParams); // Use the network interface provided in the $networkName argument. diff --git a/compute/instances/src/create_instance_with_encryption_key.php b/compute/instances/src/create_instance_with_encryption_key.php index cd1474ce3b..b469fa6947 100644 --- a/compute/instances/src/create_instance_with_encryption_key.php +++ b/compute/instances/src/create_instance_with_encryption_key.php @@ -25,10 +25,10 @@ # [START compute_instances_create_encrypted] use Google\Cloud\Compute\V1\AttachedDisk; +use Google\Cloud\Compute\V1\AttachedDisk\Type; use Google\Cloud\Compute\V1\AttachedDiskInitializeParams; use Google\Cloud\Compute\V1\Client\InstancesClient; use Google\Cloud\Compute\V1\CustomerEncryptionKey; -use Google\Cloud\Compute\V1\Enums\AttachedDisk\Type; use Google\Cloud\Compute\V1\InsertInstanceRequest; /** @@ -78,7 +78,7 @@ function create_instance_with_encryption_key( $disk = (new AttachedDisk()) ->setBoot(true) ->setAutoDelete(true) - ->setType(Type::PERSISTENT) + ->setType(Type::name(Type::PERSISTENT)) ->setInitializeParams($diskInitializeParams) ->setDiskEncryptionKey($customerEncryptionKey); diff --git a/datastore/api/composer.json b/datastore/api/composer.json index 1efd1cbb2f..732bac12fb 100644 --- a/datastore/api/composer.json +++ b/datastore/api/composer.json @@ -1,5 +1,5 @@ { "require": { - "google/cloud-datastore": "^1.2" + "google/cloud-datastore": "^2.0" } } diff --git a/datastore/quickstart/composer.json b/datastore/quickstart/composer.json index 1efd1cbb2f..732bac12fb 100644 --- a/datastore/quickstart/composer.json +++ b/datastore/quickstart/composer.json @@ -1,5 +1,5 @@ { "require": { - "google/cloud-datastore": "^1.2" + "google/cloud-datastore": "^2.0" } } diff --git a/datastore/tutorial/composer.json b/datastore/tutorial/composer.json index 1efd1cbb2f..732bac12fb 100644 --- a/datastore/tutorial/composer.json +++ b/datastore/tutorial/composer.json @@ -1,5 +1,5 @@ { "require": { - "google/cloud-datastore": "^1.2" + "google/cloud-datastore": "^2.0" } } diff --git a/dialogflow/composer.json b/dialogflow/composer.json index 5d8f90ad80..d7c9ccaded 100644 --- a/dialogflow/composer.json +++ b/dialogflow/composer.json @@ -1,7 +1,7 @@ { "require": { "google/cloud-dialogflow": "^2.0", - "symfony/console": "^5.0" + "symfony/console": "^7.0" }, "autoload": { "files": [ diff --git a/error_reporting/composer.json b/error_reporting/composer.json index c76ee28368..bfd7d462e4 100644 --- a/error_reporting/composer.json +++ b/error_reporting/composer.json @@ -1,5 +1,5 @@ { "require": { - "google/cloud-error-reporting": "^0.23.0" + "google/cloud-error-reporting": "^0.25.0" } } diff --git a/firestore/src/data_batch_writes.php b/firestore/src/data_batch_writes.php index 156637ec41..ff1a53c554 100644 --- a/firestore/src/data_batch_writes.php +++ b/firestore/src/data_batch_writes.php @@ -37,7 +37,7 @@ function data_batch_writes(string $projectId): void 'projectId' => $projectId, ]); # [START firestore_data_batch_writes] - $batch = $db->batch(); + $batch = $db->bulkWriter(); # Set the data for NYC $nycRef = $db->collection('samples/php/cities')->document('NYC'); diff --git a/functions/imagemagick/composer.json b/functions/imagemagick/composer.json index 92fb3580a9..d02daed178 100644 --- a/functions/imagemagick/composer.json +++ b/functions/imagemagick/composer.json @@ -2,7 +2,7 @@ "require": { "google/cloud-functions-framework": "^1.0", "google/cloud-storage": "^1.23", - "google/cloud-vision": "^1.2", + "google/cloud-vision": "^2.0", "ext-imagick": "*" }, "scripts": { diff --git a/iap/composer.json b/iap/composer.json index d48982548b..baedaa04c2 100644 --- a/iap/composer.json +++ b/iap/composer.json @@ -2,7 +2,7 @@ "require": { "kelvinmo/simplejwt": "^1.0.0", "google/auth":"^1.8.0", - "guzzlehttp/guzzle": "~7.9.0" + "guzzlehttp/guzzle": "~7.10.0" }, "autoload": { "psr-4": { diff --git a/modelarmor/composer.json b/modelarmor/composer.json index 0538e20f51..1072d7db63 100644 --- a/modelarmor/composer.json +++ b/modelarmor/composer.json @@ -1,6 +1,6 @@ { "require": { - "google/cloud-dlp": "^2.4", - "google/cloud-modelarmor": "^0.1.0" + "google/cloud-dlp": "^2.6", + "google/cloud-modelarmor": "^0.5.0" } } diff --git a/modelarmor/test/modelarmorTest.php b/modelarmor/test/modelarmorTest.php index 8f071fbedc..efa4948844 100644 --- a/modelarmor/test/modelarmorTest.php +++ b/modelarmor/test/modelarmorTest.php @@ -50,6 +50,8 @@ use Google\Cloud\ModelArmor\V1\RaiFilterType; use Google\Cloud\ModelArmor\V1\RaiFilterSettings; use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter; +use Google\Cloud\ModelArmor\V1\FloorSetting; +use Google\Cloud\ModelArmor\V1\UpdateFloorSettingRequest; class modelarmorTest extends TestCase { @@ -76,6 +78,8 @@ class modelarmorTest extends TestCase protected static $testRaiTemplateId; protected static $testMaliciousTemplateId; protected static $testPIandJailbreakTemplateId; + protected static $organizationId; + protected static $folderId; public static function setUpBeforeClass(): void { @@ -96,10 +100,23 @@ public static function setUpBeforeClass(): void self::$testSanitizeModelResponseUserPromptId = self::getTemplateId('php-sanitize-model-response-user-prompt-'); self::$testRaiTemplateId = self::getTemplateId('php-rai-template-'); self::$testMaliciousTemplateId = self::getTemplateId('php-malicious-template-'); - self::$testPIandJailbreakTemplateId = self::getTemplateId('php-pi-and-jailbreak-template-'); + self::$testPIandJailbreakTemplateId = self::getTemplateId('php-template-with-pijailbreak-'); + self::$organizationId = self::requireEnv('MA_ORG_ID'); + self::$folderId = self::requireEnv('MA_FOLDER_ID'); self::createTemplateWithMaliciousURI(); self::createTemplateWithPIJailbreakFilter(); self::createTemplateWithRAI(); + + // Reset floor settings before tests + if (self::$projectId) { + self::resetFloorSettings('project', self::$projectId); + } + if (self::$folderId) { + self::resetFloorSettings('folder', self::$folderId); + } + if (self::$organizationId) { + self::resetFloorSettings('organization', self::$organizationId); + } } public static function tearDownAfterClass(): void @@ -122,6 +139,18 @@ public static function tearDownAfterClass(): void self::deleteTemplate(self::$projectId, self::$locationId, self::$testMaliciousTemplateId); self::deleteTemplate(self::$projectId, self::$locationId, self::$testPIandJailbreakTemplateId); self::deleteDlpTemplates(self::$inspectTemplateName, self::$deidentifyTemplateName, self::$locationId); + + // Reset floor settings after tests + if (self::$projectId) { + self::resetFloorSettings('project', self::$projectId); + } + if (self::$folderId) { + self::resetFloorSettings('folder', self::$folderId); + } + if (self::$organizationId) { + self::resetFloorSettings('organization', self::$organizationId); + } + self::$client->close(); } @@ -143,6 +172,48 @@ public static function getTemplateId(string $testId): string return uniqid($testId); } + /** + * Resets floor settings to default values for various resource types + * + * @param string $resourceType The type of resource (project, folder, organization) + * @param string $resourceId The ID of the resource + */ + protected static function resetFloorSettings(string $resourceType, string $resourceId): void + { + try { + $client = new ModelArmorClient(); + + // Format resource path based on resource type + $resourcePathFormat = match($resourceType) { + 'project' => 'projects/%s/locations/global/floorSetting', + 'folder' => 'folders/%s/locations/global/floorSetting', + 'organization' => 'organizations/%s/locations/global/floorSetting', + default => throw new \InvalidArgumentException("Invalid resource type: {$resourceType}"), + }; + + $floorSettingsName = sprintf($resourcePathFormat, $resourceId); + + // Create an empty filter config + $filterConfig = new FilterConfig(); + + // Create floor setting with enforcement disabled + $floorSetting = (new FloorSetting()) + ->setName($floorSettingsName) + ->setFilterConfig($filterConfig) + ->setEnableFloorSettingEnforcement(false); + + $updateRequest = (new UpdateFloorSettingRequest())->setFloorSetting($floorSetting); + $response = $client->updateFloorSetting($updateRequest); + + echo "Floor settings reset for {$resourceType} {$resourceId}\n"; + } catch (\Exception $e) { + // Log but don't fail teardown if reset fails + echo "Warning: Failed to reset {$resourceType} floor settings: " . $e->getMessage() . "\n"; + } + } + + // Wrapper methods removed in favor of directly calling resetFloorSettings + public function testCreateTemplate() { $output = $this->runFunctionSnippet('create_template', [ @@ -696,5 +767,63 @@ protected static function createTemplate($templateId, $template) } } - # TODO: Add tests for floor settings once API issues are resolved. + public function testGetFolderFloorSettings() + { + $output = $this->runSnippet('get_folder_floor_settings', [ + self::$folderId, + ]); + + $expectedResponseString = 'Floor settings retrieved successfully:'; + $this->assertStringContainsString($expectedResponseString, $output); + } + + public function testGetProjectFloorSettings() + { + $output = $this->runSnippet('get_project_floor_settings', [ + self::$projectId, + ]); + + $expectedResponseString = 'Floor settings retrieved successfully:'; + $this->assertStringContainsString($expectedResponseString, $output); + } + + public function testGetOrganizationFloorSettings() + { + $output = $this->runSnippet('get_organization_floor_settings', [ + self::$organizationId, + ]); + + $expectedResponseString = 'Floor settings retrieved successfully:'; + $this->assertStringContainsString($expectedResponseString, $output); + } + + public function testUpdateFolderFloorSettings() + { + $output = $this->runSnippet('update_folder_floor_settings', [ + self::$folderId, + ]); + + $expectedResponseString = 'Floor setting updated'; + $this->assertStringContainsString($expectedResponseString, $output); + } + + public function testUpdateProjectFloorSettings() + { + $output = $this->runSnippet('update_project_floor_settings', [ + self::$projectId, + ]); + + $expectedResponseString = 'Floor setting updated'; + $this->assertStringContainsString($expectedResponseString, $output); + } + + public function testUpdateOrganizationFloorSettings() + { + $output = $this->runSnippet('update_organization_floor_settings', [ + self::$organizationId, + ]); + + $expectedResponseString = 'Floor setting updated'; + $this->assertStringContainsString($expectedResponseString, $output); + } } diff --git a/parametermanager/composer.json b/parametermanager/composer.json index 925b837cc0..a0e0ecc6fd 100644 --- a/parametermanager/composer.json +++ b/parametermanager/composer.json @@ -1,7 +1,7 @@ { "require": { "google/cloud-kms": "^2.3", - "google/cloud-secret-manager": "^1.15.2", - "google/cloud-parametermanager": "^0.2.0" + "google/cloud-secret-manager": "^2.0.0", + "google/cloud-parametermanager": "^0.5.0" } } diff --git a/pubsub/api/src/create_unwrapped_push_subscription.php b/pubsub/api/src/create_unwrapped_push_subscription.php index 6d30ab84de..b067b4444f 100644 --- a/pubsub/api/src/create_unwrapped_push_subscription.php +++ b/pubsub/api/src/create_unwrapped_push_subscription.php @@ -28,7 +28,7 @@ use Google\Cloud\PubSub\PubSubClient; /** - * Create unwrappped push subscription. + * Creates an unwrapped push subscription. * * @param string $projectId The Google project ID. * @param string $topicName The Pub/Sub topic name. diff --git a/pubsub/app/composer.json b/pubsub/app/composer.json index 076ca7666d..e8c247fa8d 100644 --- a/pubsub/app/composer.json +++ b/pubsub/app/composer.json @@ -1,7 +1,7 @@ { "require": { "google/cloud-pubsub": "^2.0", - "google/cloud-datastore": "^1.11.2", + "google/cloud-datastore": "^2.0.0", "slim/slim": "^4.7", "slim/psr7": "^1.3", "slim/twig-view": "^3.0", diff --git a/secretmanager/composer.json b/secretmanager/composer.json index f1840b1317..2a20b5355d 100644 --- a/secretmanager/composer.json +++ b/secretmanager/composer.json @@ -1,5 +1,6 @@ { "require": { - "google/cloud-secret-manager": "^2.0.0" + "google/cloud-secret-manager": "^2.1.0", + "google/cloud-resource-manager": "^1.0" } } diff --git a/secretmanager/src/bind_tags_to_regional_secret.php b/secretmanager/src/bind_tags_to_regional_secret.php new file mode 100644 index 0000000000..949a6f9aa8 --- /dev/null +++ b/secretmanager/src/bind_tags_to_regional_secret.php @@ -0,0 +1,92 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the parent project. + $parent = $client->locationName($projectId, $locationId); + + $secret = new Secret(); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret %s' . PHP_EOL, $newSecret->getName()); + + // Specify regional endpoint. + $tagBindOptions = ['apiEndpoint' => "$locationId-cloudresourcemanager.googleapis.com"]; + $tagBindingsClient = new TagBindingsClient($tagBindOptions); + $tagBinding = (new TagBinding()) + ->setParent('//secretmanager.googleapis.com/' . $newSecret->getName()) + ->setTagValue($tagValue); + + // Build the request. + $request = (new CreateTagBindingRequest()) + ->setTagBinding($tagBinding); + + // Create the tag binding. + $operationResponse = $tagBindingsClient->createTagBinding($request); + $operationResponse->pollUntilComplete(); + + // Check if the operation succeeded. + if ($operationResponse->operationSucceeded()) { + printf('Tag binding created for secret %s with tag value %s' . PHP_EOL, $newSecret->getName(), $tagValue); + } else { + $error = $operationResponse->getError(); + printf('Error in creating tag binding: %s' . PHP_EOL, $error->getMessage()); + } +} +// [END secretmanager_bind_tags_to_regional_secret] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/bind_tags_to_secret.php b/secretmanager/src/bind_tags_to_secret.php new file mode 100644 index 0000000000..60616353b7 --- /dev/null +++ b/secretmanager/src/bind_tags_to_secret.php @@ -0,0 +1,92 @@ +projectName($projectId); + + $secret = new Secret([ + 'replication' => new Replication([ + 'automatic' => new Automatic(), + ]), + ]); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret %s' . PHP_EOL, $newSecret->getName()); + + $tagBindingsClient = new TagBindingsClient(); + $tagBinding = (new TagBinding()) + ->setParent('//secretmanager.googleapis.com/' . $newSecret->getName()) + ->setTagValue($tagValue); + + // Build the binding request. + $request = (new CreateTagBindingRequest()) + ->setTagBinding($tagBinding); + + // Create the tag binding. + $operationResponse = $tagBindingsClient->createTagBinding($request); + $operationResponse->pollUntilComplete(); + + // Check if the operation succeeded. + if ($operationResponse->operationSucceeded()) { + printf('Tag binding created for secret %s with tag value %s' . PHP_EOL, $newSecret->getName(), $tagValue); + } else { + $error = $operationResponse->getError(); + printf('Error in creating tag binding: %s' . PHP_EOL, $error->getMessage()); + } +} +// [END secretmanager_bind_tags_to_secret] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/create_regional_secret_with_annotations.php b/secretmanager/src/create_regional_secret_with_annotations.php new file mode 100644 index 0000000000..03d78d0ebc --- /dev/null +++ b/secretmanager/src/create_regional_secret_with_annotations.php @@ -0,0 +1,71 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the parent project. + $parent = $client->locationName($projectId, $locationId); + + $secret = new Secret(); + + // set the annotations. + $annotations = [$annotationKey => $annotationValue]; + $secret->setAnnotations($annotations); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret %s with annotations', $newSecret->getName()); +} +// [END secretmanager_create_regional_secret_with_annotations] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/create_regional_secret_with_delayed_destroy.php b/secretmanager/src/create_regional_secret_with_delayed_destroy.php new file mode 100644 index 0000000000..7ebd4606af --- /dev/null +++ b/secretmanager/src/create_regional_secret_with_delayed_destroy.php @@ -0,0 +1,72 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the parent project. + $parent = $client->locationName($projectId, $locationId); + + // Build the secret. + $secret = new Secret([ + 'version_destroy_ttl' => new Duration([ + 'seconds' => $versionDestroyTtl + ]) + ]); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret: %s', $newSecret->getName()); +} +// [END secretmanager_create_regional_secret_with_delayed_destroy] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/create_regional_secret_with_labels.php b/secretmanager/src/create_regional_secret_with_labels.php new file mode 100644 index 0000000000..0ebf77e31f --- /dev/null +++ b/secretmanager/src/create_regional_secret_with_labels.php @@ -0,0 +1,71 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the parent project. + $parent = $client->locationName($projectId, $locationId); + + $secret = new Secret(); + + // set the labels. + $labels = [$labelKey => $labelValue]; + $secret->setLabels($labels); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret %s with labels', $newSecret->getName()); +} +// [END secretmanager_create_regional_secret_with_labels] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/create_regional_secret_with_tags.php b/secretmanager/src/create_regional_secret_with_tags.php new file mode 100644 index 0000000000..519e8b84f3 --- /dev/null +++ b/secretmanager/src/create_regional_secret_with_tags.php @@ -0,0 +1,71 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the parent project. + $parent = $client->locationName($projectId, $locationId); + + $secret = new Secret(); + + // set the tags. + $tags = [$tagKey => $tagValue]; + $secret ->setTags($tags); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret %s with tag', $newSecret->getName()); +} +// [END secretmanager_regional_create_secret_with_tags] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/create_secret_with_annotations.php b/secretmanager/src/create_secret_with_annotations.php new file mode 100644 index 0000000000..40d8a44d04 --- /dev/null +++ b/secretmanager/src/create_secret_with_annotations.php @@ -0,0 +1,73 @@ +projectName($projectId); + + $secret = new Secret([ + 'replication' => new Replication([ + 'automatic' => new Automatic(), + ]), + ]); + + // set the annoation. + $annotation = [$annotationKey => $annotationValue]; + $secret->setAnnotations($annotation); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret %s with annotations', $newSecret->getName()); +} +// [END secretmanager_create_secret_with_annotations] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/create_secret_with_delayed_destroy.php b/secretmanager/src/create_secret_with_delayed_destroy.php new file mode 100644 index 0000000000..a7e40764d9 --- /dev/null +++ b/secretmanager/src/create_secret_with_delayed_destroy.php @@ -0,0 +1,73 @@ +projectName($projectId); + + // Build the secret. + $secret = new Secret([ + 'replication' => new Replication([ + 'automatic' => new Automatic(), + ]), + 'version_destroy_ttl' => new Duration([ + 'seconds' => $versionDestroyTtl + ]) + ]); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret: %s', $newSecret->getName()); +} +// [END secretmanager_create_secret_with_delayed_destroy] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/create_secret_with_labels.php b/secretmanager/src/create_secret_with_labels.php new file mode 100644 index 0000000000..02edcdb988 --- /dev/null +++ b/secretmanager/src/create_secret_with_labels.php @@ -0,0 +1,73 @@ +projectName($projectId); + + $secret = new Secret([ + 'replication' => new Replication([ + 'automatic' => new Automatic(), + ]), + ]); + + // set the labels. + $labels = [$labelKey => $labelValue]; + $secret->setLabels($labels); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret %s with labels', $newSecret->getName()); +} +// [END secretmanager_create_secret_with_labels] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/create_secret_with_tags.php b/secretmanager/src/create_secret_with_tags.php new file mode 100644 index 0000000000..33d7353c1f --- /dev/null +++ b/secretmanager/src/create_secret_with_tags.php @@ -0,0 +1,73 @@ +projectName($projectId); + + $secret = new Secret([ + 'replication' => new Replication([ + 'automatic' => new Automatic(), + ]), + ]); + + // set the tags. + $tags = [$tagKey => $tagValue]; + $secret->setTags($tags); + + // Build the request. + $request = CreateSecretRequest::build($parent, $secretId, $secret); + + // Create the secret. + $newSecret = $client->createSecret($request); + + // Print the new secret name. + printf('Created secret %s with tag', $newSecret->getName()); +} +// [END secretmanager_create_secret_with_tags] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/delete_regional_secret_annotation.php b/secretmanager/src/delete_regional_secret_annotation.php new file mode 100644 index 0000000000..c76fe6d1c4 --- /dev/null +++ b/secretmanager/src/delete_regional_secret_annotation.php @@ -0,0 +1,89 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the secret. + $name = $client->projectLocationSecretName($projectId, $locationId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the annotations + $annotations = $getSecret->getAnnotations(); + + // delete the annotation + unset($annotations[$annotationKey]); + + // set the field mask + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['annotations']); + + // build the secret + $secret = new Secret(); + $secret->setAnnotations($annotations); + $secret->setName($getSecret->getName()); + + // build the request + $request = new UpdateSecretRequest(); + $request->setSecret($getSecret); + $request->setUpdateMask($fieldMask); + + // update the secret + $updateSecret = $client->updateSecret($request); + + // print the secret name + printf('Updated secret %s' . PHP_EOL, $updateSecret->getName()); +} +// [END secretmanager_delete_regional_secret_annotation] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/delete_regional_secret_label.php b/secretmanager/src/delete_regional_secret_label.php new file mode 100644 index 0000000000..00c9c18bba --- /dev/null +++ b/secretmanager/src/delete_regional_secret_label.php @@ -0,0 +1,89 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the secret. + $name = $client->projectLocationSecretName($projectId, $locationId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the secret labels + $labels = $getSecret->getLabels(); + + // delete the label + unset($labels[$labelKey]); + + // set the field mask + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['labels']); + + // build the secret + $secret = new Secret(); + $secret->setLabels($labels); + $secret->setName($getSecret->getName()); + + // build the request + $request = new UpdateSecretRequest(); + $request->setSecret($getSecret); + $request->setUpdateMask($fieldMask); + + // update the secret + $updateSecret = $client->updateSecret($request); + + // print the secret name + printf('Updated secret %s' . PHP_EOL, $updateSecret->getName()); +} +// [END secretmanager_delete_regional_secret_label] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/delete_secret_annotation.php b/secretmanager/src/delete_secret_annotation.php new file mode 100644 index 0000000000..57286ac62e --- /dev/null +++ b/secretmanager/src/delete_secret_annotation.php @@ -0,0 +1,85 @@ +secretName($projectId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the annotations + $annotations = $getSecret->getAnnotations(); + + // delete the annotation + unset($annotations[$annotationKey]); + + // set the field mask + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['annotations']); + + // build the secret + $secret = new Secret(); + $secret->setAnnotations($annotations); + $secret->setName($getSecret->getName()); + + // build the request + $request = new UpdateSecretRequest(); + $request->setSecret($getSecret); + $request->setUpdateMask($fieldMask); + + // update the secret + $updateSecret = $client->updateSecret($request); + + // print the secret name + printf('Updated secret %s' . PHP_EOL, $updateSecret->getName()); +} +// [END secretmanager_delete_secret_annotation] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/delete_secret_label.php b/secretmanager/src/delete_secret_label.php new file mode 100644 index 0000000000..9e337f1dfb --- /dev/null +++ b/secretmanager/src/delete_secret_label.php @@ -0,0 +1,85 @@ +secretName($projectId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the secret labels + $labels = $getSecret->getLabels(); + + // delete the label + unset($labels[$labelKey]); + + // set the field mask + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['labels']); + + // build the secret + $secret = new Secret(); + $secret->setLabels($labels); + $secret->setName($getSecret->getName()); + + // build the request + $request = new UpdateSecretRequest(); + $request->setSecret($getSecret); + $request->setUpdateMask($fieldMask); + + // update the secret + $updateSecret = $client->updateSecret($request); + + // print the secret name + printf('Updated secret %s' . PHP_EOL, $updateSecret->getName()); +} +// [END secretmanager_delete_secret_label] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/disable_regional_secret_delayed_destroy.php b/secretmanager/src/disable_regional_secret_delayed_destroy.php new file mode 100644 index 0000000000..d6ed2dc52e --- /dev/null +++ b/secretmanager/src/disable_regional_secret_delayed_destroy.php @@ -0,0 +1,75 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the secret. + $name = $client->projectLocationSecretName($projectId, $locationId, $secretId); + + // Build the secret. + $secret = new Secret([ + 'name' => $name, + ]); + + // Set the field mask. + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['version_destroy_ttl']); + + // Build the request. + $request = new UpdateSecretRequest(); + $request->setSecret($secret); + $request->setUpdateMask($fieldMask); + + // Update the secret. + $newSecret = $client->updateSecret($request); + + // Print the new secret name. + printf('Updated secret: %s', $newSecret->getName()); +} +// [END secretmanager_disable_regional_secret_delayed_destroy] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/disable_secret_delayed_destroy.php b/secretmanager/src/disable_secret_delayed_destroy.php new file mode 100644 index 0000000000..2e01612a9d --- /dev/null +++ b/secretmanager/src/disable_secret_delayed_destroy.php @@ -0,0 +1,71 @@ +secretName($projectId, $secretId); + + // Build the secret. + $secret = new Secret([ + 'name' => $name + ]); + + // Set the field mask. + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['version_destroy_ttl']); + + // Build the request. + $request = new UpdateSecretRequest(); + $request->setSecret($secret); + $request->setUpdateMask($fieldMask); + + // Update the secret. + $newSecret = $client->updateSecret($request); + + // Print the new secret name. + printf('Updated secret: %s', $newSecret->getName()); +} +// [END secretmanager_disable_secret_delayed_destroy] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/edit_regional_secret_annotations.php b/secretmanager/src/edit_regional_secret_annotations.php new file mode 100644 index 0000000000..832022f751 --- /dev/null +++ b/secretmanager/src/edit_regional_secret_annotations.php @@ -0,0 +1,89 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the secret. + $name = $client->projectLocationSecretName($projectId, $locationId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the annotations + $annotations = $getSecret->getAnnotations(); + + // update the annotation - need to create a new annotations map with the updated values + $newAnnotations = []; + foreach ($annotations as $key => $value) { + $newAnnotations[$key] = $value; + } + $newAnnotations[$annotationKey] = $annotationValue; + $getSecret->setAnnotations($newAnnotations); + + // set the field mask + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['annotations']); + + // build the secret + $request = new UpdateSecretRequest(); + $request->setSecret($getSecret); + $request->setUpdateMask($fieldMask); + + // update the secret + $updateSecret = $client->updateSecret($request); + + // print the updated secret + printf('Updated secret %s annotations' . PHP_EOL, $updateSecret->getName()); +} +// [END secretmanager_edit_regional_secret_annotations] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/edit_regional_secret_labels.php b/secretmanager/src/edit_regional_secret_labels.php new file mode 100644 index 0000000000..fa2cfadefd --- /dev/null +++ b/secretmanager/src/edit_regional_secret_labels.php @@ -0,0 +1,89 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the secret. + $name = $client->projectLocationSecretName($projectId, $locationId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the secret labels + $labels = $getSecret->getLabels(); + + // update the label - need to create a new labels map with the updated values + $newLabels = []; + foreach ($labels as $key => $value) { + $newLabels[$key] = $value; + } + $newLabels[$labelKey] = $labelValue; + $getSecret->setLabels($newLabels); + + // set the field mask + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['labels']); + + // build the secret + $request = new UpdateSecretRequest(); + $request->setSecret($getSecret); + $request->setUpdateMask($fieldMask); + + // update the secret + $updateSecret = $client->updateSecret($request); + + // print the updated secret + printf('Updated secret %s labels' . PHP_EOL, $updateSecret->getName()); +} +// [END secretmanager_edit_regional_secret_labels] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/edit_secret_annotations.php b/secretmanager/src/edit_secret_annotations.php new file mode 100644 index 0000000000..1a58cf521b --- /dev/null +++ b/secretmanager/src/edit_secret_annotations.php @@ -0,0 +1,85 @@ +secretName($projectId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the annotations + $annotations = $getSecret->getAnnotations(); + + // update the annotation - need to create a new annotations map with the updated values + $newAnnotations = []; + foreach ($annotations as $key => $value) { + $newAnnotations[$key] = $value; + } + $newAnnotations[$annotationKey] = $annotationValue; + $getSecret->setAnnotations($newAnnotations); + + // set the field mask + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['annotations']); + + // build the secret + $request = new UpdateSecretRequest(); + $request->setSecret($getSecret); + $request->setUpdateMask($fieldMask); + + // update the secret + $updateSecret = $client->updateSecret($request); + + // print the updated secret + printf('Updated secret %s annotations' . PHP_EOL, $updateSecret->getName()); +} +// [END secretmanager_edit_secret_annotations] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/edit_secret_labels.php b/secretmanager/src/edit_secret_labels.php new file mode 100644 index 0000000000..cdbb79ce1f --- /dev/null +++ b/secretmanager/src/edit_secret_labels.php @@ -0,0 +1,85 @@ +secretName($projectId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the secret labels + $labels = $getSecret->getLabels(); + + // update the label - need to create a new labels map with the updated values + $newLabels = []; + foreach ($labels as $key => $value) { + $newLabels[$key] = $value; + } + $newLabels[$labelKey] = $labelValue; + $getSecret->setLabels($newLabels); + + // set the field mask + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['labels']); + + // build the secret + $request = new UpdateSecretRequest(); + $request->setSecret($getSecret); + $request->setUpdateMask($fieldMask); + + // update the secret + $updateSecret = $client->updateSecret($request); + + // print the updated secret + printf('Updated secret %s labels' . PHP_EOL, $updateSecret->getName()); +} +// [END secretmanager_edit_secret_labels] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/update_regional_secret_with_delayed_destroy.php b/secretmanager/src/update_regional_secret_with_delayed_destroy.php new file mode 100644 index 0000000000..98e0d114e7 --- /dev/null +++ b/secretmanager/src/update_regional_secret_with_delayed_destroy.php @@ -0,0 +1,80 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the secret. + $name = $client->projectLocationSecretName($projectId, $locationId, $secretId); + + // Build the secret. + $secret = new Secret([ + 'name' => $name, + 'version_destroy_ttl' => new Duration([ + 'seconds' => $versionDestroyTtl, + ]) + ]); + + // Set the field mask. + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['version_destroy_ttl']); + + // Build the request. + $request = new UpdateSecretRequest(); + $request->setSecret($secret); + $request->setUpdateMask($fieldMask); + + // Update the secret. + $newSecret = $client->updateSecret($request); + + // Print the new secret name. + printf('Updated secret: %s', $newSecret->getName()); +} +// [END secretmanager_update_regional_secret_with_delayed_destroy] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/update_secret_with_delayed_destroy.php b/secretmanager/src/update_secret_with_delayed_destroy.php new file mode 100644 index 0000000000..b487ff9553 --- /dev/null +++ b/secretmanager/src/update_secret_with_delayed_destroy.php @@ -0,0 +1,76 @@ +secretName($projectId, $secretId); + + // Build the secret. + $secret = new Secret([ + 'name' => $name, + 'version_destroy_ttl' => new Duration([ + 'seconds' => $versionDestroyTtl, + ]) + ]); + + // Set the field mask. + $fieldMask = new FieldMask(); + $fieldMask->setPaths(['version_destroy_ttl']); + + // Build the request. + $request = new UpdateSecretRequest(); + $request->setSecret($secret); + $request->setUpdateMask($fieldMask); + + // Update the secret. + $newSecret = $client->updateSecret($request); + + // Print the new secret name. + printf('Updated secret: %s', $newSecret->getName()); +} +// [END secretmanager_update_secret_with_delayed_destroy] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/view_regional_secret_annotations.php b/secretmanager/src/view_regional_secret_annotations.php new file mode 100644 index 0000000000..d58c9e9d7e --- /dev/null +++ b/secretmanager/src/view_regional_secret_annotations.php @@ -0,0 +1,69 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the secret. + $name = $client->projectLocationSecretName($projectId, $locationId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the annotations + $annotations = $getSecret->getAnnotations(); + + // print the secret name + printf('Get secret %s with annotation:' . PHP_EOL, $getSecret->getName()); + // we can even loop over all the annotations + foreach ($annotations as $key => $val) { + printf("\t$key: $val" . PHP_EOL); + } +} +// [END secretmanager_view_regional_secret_annotations] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/view_regional_secret_labels.php b/secretmanager/src/view_regional_secret_labels.php new file mode 100644 index 0000000000..af04dfe721 --- /dev/null +++ b/secretmanager/src/view_regional_secret_labels.php @@ -0,0 +1,69 @@ + "secretmanager.$locationId.rep.googleapis.com"]; + + // Create the Secret Manager client. + $client = new SecretManagerServiceClient($options); + + // Build the resource name of the secret. + $name = $client->projectLocationSecretName($projectId, $locationId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the secret labels + $labels = $getSecret->getLabels(); + + // print the secret name + printf('Get secret %s with labels:' . PHP_EOL, $getSecret->getName()); + // we can even loop over all the labels + foreach ($labels as $key => $val) { + printf("\t$key: $val" . PHP_EOL); + } +} +// [END secretmanager_view_regional_secret_labels] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/view_secret_annotations.php b/secretmanager/src/view_secret_annotations.php new file mode 100644 index 0000000000..e61aea65aa --- /dev/null +++ b/secretmanager/src/view_secret_annotations.php @@ -0,0 +1,65 @@ +secretName($projectId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the annotations + $annotations = $getSecret->getAnnotations(); + + // print the secret name + printf('Get secret %s with annotation:' . PHP_EOL, $getSecret->getName()); + // we can even loop over all the annotations + foreach ($annotations as $key => $val) { + printf("\t$key: $val" . PHP_EOL); + } +} +// [END secretmanager_view_secret_annotations] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/src/view_secret_labels.php b/secretmanager/src/view_secret_labels.php new file mode 100644 index 0000000000..d549ccf56c --- /dev/null +++ b/secretmanager/src/view_secret_labels.php @@ -0,0 +1,65 @@ +secretName($projectId, $secretId); + + // Build the request. + $request = GetSecretRequest::build($name); + + // get the secret. + $getSecret = $client->getSecret($request); + + // get the secret labels + $labels = $getSecret->getLabels(); + + // print the secret name + printf('Get secret %s with labels:' . PHP_EOL, $getSecret->getName()); + // we can even loop over all the labels + foreach ($labels as $key => $val) { + printf("\t$key: $val" . PHP_EOL); + } +} +// [END secretmanager_view_secret_labels] + +// The following 2 lines are only needed to execute the samples on the CLI +require_once __DIR__ . '/../../testing/sample_helpers.php'; +\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); diff --git a/secretmanager/test/regionalsecretmanagerTest.php b/secretmanager/test/regionalsecretmanagerTest.php index 80c6946200..18c9c97ac5 100644 --- a/secretmanager/test/regionalsecretmanagerTest.php +++ b/secretmanager/test/regionalsecretmanagerTest.php @@ -20,11 +20,20 @@ namespace Google\Cloud\Samples\SecretManager; use Google\ApiCore\ApiException as GaxApiException; +use Google\Cloud\ResourceManager\V3\DeleteTagKeyRequest; +use Google\Cloud\ResourceManager\V3\DeleteTagValueRequest; +use Google\Cloud\ResourceManager\V3\Client\TagKeysClient; +use Google\Cloud\ResourceManager\V3\CreateTagKeyRequest; +use Google\Cloud\ResourceManager\V3\TagKey; +use Google\Cloud\ResourceManager\V3\Client\TagValuesClient; +use Google\Cloud\ResourceManager\V3\CreateTagValueRequest; +use Google\Cloud\ResourceManager\V3\TagValue; use Google\Cloud\SecretManager\V1\AddSecretVersionRequest; use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient; use Google\Cloud\SecretManager\V1\CreateSecretRequest; use Google\Cloud\SecretManager\V1\DeleteSecretRequest; use Google\Cloud\SecretManager\V1\DisableSecretVersionRequest; +use Google\Cloud\SecretManager\V1\GetSecretRequest; use Google\Cloud\SecretManager\V1\Secret; use Google\Cloud\SecretManager\V1\SecretPayload; use Google\Cloud\SecretManager\V1\SecretVersion; @@ -36,6 +45,9 @@ class regionalsecretmanagerTest extends TestCase use TestTrait; private static $client; + private static $tagKeyClient; + private static $tagValuesClient; + private static $testSecret; private static $testSecretToDelete; private static $testSecretWithVersions; @@ -44,14 +56,31 @@ class regionalsecretmanagerTest extends TestCase private static $testSecretVersionToDestroy; private static $testSecretVersionToDisable; private static $testSecretVersionToEnable; + private static $testSecretWithTagToCreateName; + private static $testSecretBindTagToCreateName; + private static $testSecretWithLabelsToCreateName; + private static $testSecretWithAnnotationsToCreateName; + private static $testSecretWithDelayedDestroyToCreateName; private static $iamUser = 'user:kapishsingh@google.com'; private static $locationId = 'us-central1'; + private static $testLabelKey = 'test-label-key'; + private static $testLabelValue = 'test-label-value'; + private static $testUpdatedLabelValue = 'test-label-new-value'; + private static $testAnnotationKey = 'test-annotation-key'; + private static $testAnnotationValue = 'test-annotation-value'; + private static $testUpdatedAnnotationValue = 'test-annotation-new-value'; + private static $testDelayedDestroyTime = 86400; + + private static $testTagKey; + private static $testTagValue; public static function setUpBeforeClass(): void { $options = ['apiEndpoint' => 'secretmanager.' . self::$locationId . '.rep.googleapis.com' ]; self::$client = new SecretManagerServiceClient($options); + self::$tagKeyClient = new TagKeysClient(); + self::$tagValuesClient = new TagValuesClient(); self::$testSecret = self::createSecret(); self::$testSecretToDelete = self::createSecret(); @@ -61,7 +90,15 @@ public static function setUpBeforeClass(): void self::$testSecretVersionToDestroy = self::addSecretVersion(self::$testSecretWithVersions); self::$testSecretVersionToDisable = self::addSecretVersion(self::$testSecretWithVersions); self::$testSecretVersionToEnable = self::addSecretVersion(self::$testSecretWithVersions); + self::$testSecretWithTagToCreateName = self::$client->projectLocationSecretName(self::$projectId, self::$locationId, self::randomSecretId()); + self::$testSecretBindTagToCreateName = self::$client->projectLocationSecretName(self::$projectId, self::$locationId, self::randomSecretId()); + self::$testSecretWithLabelsToCreateName = self::$client->projectLocationSecretName(self::$projectId, self::$locationId, self::randomSecretId()); + self::$testSecretWithAnnotationsToCreateName = self::$client->projectLocationSecretName(self::$projectId, self::$locationId, self::randomSecretId()); + self::$testSecretWithDelayedDestroyToCreateName = self::$client->projectLocationSecretName(self::$projectId, self::$locationId, self::randomSecretId()); self::disableSecretVersion(self::$testSecretVersionToEnable); + + self::$testTagKey = self::createTagKey(self::randomSecretId()); + self::$testTagValue = self::createTagValue(self::randomSecretId()); } public static function tearDownAfterClass(): void @@ -73,6 +110,14 @@ public static function tearDownAfterClass(): void self::deleteSecret(self::$testSecretToDelete->getName()); self::deleteSecret(self::$testSecretWithVersions->getName()); self::deleteSecret(self::$testSecretToCreateName); + self::deleteSecret(self::$testSecretWithTagToCreateName); + self::deleteSecret(self::$testSecretBindTagToCreateName); + self::deleteSecret(self::$testSecretWithLabelsToCreateName); + self::deleteSecret(self::$testSecretWithAnnotationsToCreateName); + self::deleteSecret(self::$testSecretWithDelayedDestroyToCreateName); + sleep(15); // Added a sleep to wait for the tag unbinding + self::deleteTagValue(); + self::deleteTagKey(); } private static function randomSecretId(): string @@ -122,6 +167,93 @@ private static function deleteSecret(string $name) } } + private static function getSecret(string $projectId, string $locationId, string $secretId): Secret + { + $name = self::$client->projectLocationSecretName($projectId, $locationId, $secretId); + $getSecretRequest = (new GetSecretRequest())->setName($name); + return self::$client->getSecret($getSecretRequest); + } + + private static function createTagKey(string $short_name): string + { + $parent = self::$client->projectName(self::$projectId); + $tagKey = (new TagKey()) + ->setParent($parent) + ->setShortName($short_name); + + $request = (new CreateTagKeyRequest()) + ->setTagKey($tagKey); + + $operation = self::$tagKeyClient->createTagKey($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + $createdTagKey = $operation->getResult(); + printf("Tag key created: %s\n", $createdTagKey->getName()); + return $createdTagKey->getName(); + } else { + $error = $operation->getError(); + printf("Error creating tag key: %s\n", $error->getMessage()); + return ''; + } + } + + private static function createTagValue(string $short_name): string + { + $tagValuesClient = new TagValuesClient(); + $tagValue = (new TagValue()) + ->setParent(self::$testTagKey) + ->setShortName($short_name); + + $request = (new CreateTagValueRequest()) + ->setTagValue($tagValue); + + $operation = self::$tagValuesClient->createTagValue($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + $createdTagValue = $operation->getResult(); + printf("Tag value created: %s\n", $createdTagValue->getName()); + return $createdTagValue->getName(); + } else { + $error = $operation->getError(); + printf("Error creating tag value: %s\n", $error->getMessage()); + return ''; + } + } + + private static function deleteTagKey() + { + $request = (new DeleteTagKeyRequest()) + ->setName(self::$testTagKey); + + $operation = self::$tagKeyClient->deleteTagKey($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + printf("Tag key deleted: %s\n", self::$testTagValue); + } else { + $error = $operation->getError(); + printf("Error deleting tag key: %s\n", $error->getMessage()); + } + } + + private static function deleteTagValue() + { + $request = (new DeleteTagValueRequest()) + ->setName(self::$testTagValue); + + $operation = self::$tagValuesClient->deleteTagValue($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + printf("Tag value deleted: %s\n", self::$testTagValue); + } else { + $error = $operation->getError(); + printf("Error deleting tag value: %s\n", $error->getMessage()); + } + } + public function testAccessSecretVersion() { $name = self::$client->parseName(self::$testSecretVersion->getName()); @@ -324,4 +456,197 @@ public function testUpdateSecretWithAlias() $this->assertStringContainsString('Updated secret', $output); } + + public function testCreateSecretWithTags() + { + $name = self::$client->parseName(self::$testSecretWithTagToCreateName); + + $output = $this->runFunctionSnippet('create_regional_secret_with_tags', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testTagKey, + self::$testTagValue + ]); + + $this->assertStringContainsString('Created secret', $output); + } + + public function testBindTagsToSecret() + { + $name = self::$client->parseName(self::$testSecretBindTagToCreateName); + + $output = $this->runFunctionSnippet('bind_tags_to_regional_secret', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testTagValue + ]); + + $this->assertStringContainsString('Created secret', $output); + $this->assertStringContainsString('Tag binding created for secret', $output); + } + + public function testCreateSecretWithLabels() + { + $name = self::$client->parseName(self::$testSecretWithLabelsToCreateName); + + $output = $this->runFunctionSnippet('create_regional_secret_with_labels', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testLabelKey, + self::$testLabelValue + ]); + + $this->assertStringContainsString('Created secret', $output); + } + + public function testCreateSecretWithAnnotations() + { + $name = self::$client->parseName(self::$testSecretWithAnnotationsToCreateName); + + $output = $this->runFunctionSnippet('create_regional_secret_with_annotations', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testAnnotationKey, + self::$testAnnotationValue + ]); + + $this->assertStringContainsString('Created secret', $output); + } + + public function testViewSecretAnnotations() + { + $name = self::$client->parseName(self::$testSecretWithAnnotationsToCreateName); + + $output = $this->runFunctionSnippet('view_regional_secret_annotations', [ + $name['project'], + $name['location'], + $name['secret'] + ]); + + $this->assertStringContainsString('Get secret', $output); + } + + public function testViewSecretLabels() + { + $name = self::$client->parseName(self::$testSecretWithLabelsToCreateName); + + $output = $this->runFunctionSnippet('view_regional_secret_labels', [ + $name['project'], + $name['location'], + $name['secret'] + ]); + + $this->assertStringContainsString('Get secret', $output); + } + + public function testEditSecretLabels() + { + $name = self::$client->parseName(self::$testSecretWithLabelsToCreateName); + + $output = $this->runFunctionSnippet('edit_regional_secret_labels', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testLabelKey, + self::$testUpdatedLabelValue + ]); + + $this->assertStringContainsString('Updated secret', $output); + } + + public function testEditSecretAnnotations() + { + $name = self::$client->parseName(self::$testSecretWithAnnotationsToCreateName); + + $output = $this->runFunctionSnippet('edit_regional_secret_annotations', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testAnnotationKey, + self::$testUpdatedAnnotationValue + ]); + + $this->assertStringContainsString('Updated secret', $output); + } + + public function testDeleteSecretLabel() + { + $name = self::$client->parseName(self::$testSecretWithLabelsToCreateName); + + $output = $this->runFunctionSnippet('delete_regional_secret_label', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testLabelKey + ]); + + $this->assertStringContainsString('Updated secret', $output); + } + + public function testDeleteSecretAnnotation() + { + $name = self::$client->parseName(self::$testSecretWithAnnotationsToCreateName); + + $output = $this->runFunctionSnippet('delete_regional_secret_annotation', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testAnnotationKey + ]); + + $this->assertStringContainsString('Updated secret', $output); + } + + public function testCreateSecretWithDelayedDestroyed() + { + $name = self::$client->parseName(self::$testSecretWithDelayedDestroyToCreateName); + + $output = $this->runFunctionSnippet('create_regional_secret_with_delayed_destroy', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testDelayedDestroyTime + ]); + + $this->assertStringContainsString('Created secret', $output); + + $secret = self::getSecret($name['project'], $name['location'], $name['secret']); + $this->assertEquals(self::$testDelayedDestroyTime, $secret->getVersionDestroyTtl()->getSeconds()); + } + + public function testDisableSecretDelayedDestroy() + { + $name = self::$client->parseName(self::$testSecretWithDelayedDestroyToCreateName); + + $output = $this->runFunctionSnippet('disable_regional_secret_delayed_destroy', [ + $name['project'], + $name['location'], + $name['secret'] + ]); + + $this->assertStringContainsString('Updated secret', $output); + + $secret = self::getSecret($name['project'], $name['location'], $name['secret']); + $this->assertNull($secret->getVersionDestroyTtl()); + } + + public function testUpdateSecretWithDelayedDestroyed() + { + $name = self::$client->parseName(self::$testSecretWithDelayedDestroyToCreateName); + + $output = $this->runFunctionSnippet('update_regional_secret_with_delayed_destroy', [ + $name['project'], + $name['location'], + $name['secret'], + self::$testDelayedDestroyTime + ]); + + $this->assertStringContainsString('Updated secret', $output); + $secret = self::getSecret($name['project'], $name['location'], $name['secret']); + $this->assertEquals(self::$testDelayedDestroyTime, $secret->getVersionDestroyTtl()->getSeconds()); + } } diff --git a/secretmanager/test/secretmanagerTest.php b/secretmanager/test/secretmanagerTest.php index 48570fe253..11b9dd3bd6 100644 --- a/secretmanager/test/secretmanagerTest.php +++ b/secretmanager/test/secretmanagerTest.php @@ -20,11 +20,20 @@ namespace Google\Cloud\Samples\SecretManager; use Google\ApiCore\ApiException as GaxApiException; +use Google\Cloud\ResourceManager\V3\DeleteTagKeyRequest; +use Google\Cloud\ResourceManager\V3\DeleteTagValueRequest; +use Google\Cloud\ResourceManager\V3\Client\TagKeysClient; +use Google\Cloud\ResourceManager\V3\CreateTagKeyRequest; +use Google\Cloud\ResourceManager\V3\TagKey; +use Google\Cloud\ResourceManager\V3\Client\TagValuesClient; +use Google\Cloud\ResourceManager\V3\CreateTagValueRequest; +use Google\Cloud\ResourceManager\V3\TagValue; use Google\Cloud\SecretManager\V1\AddSecretVersionRequest; use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient; use Google\Cloud\SecretManager\V1\CreateSecretRequest; use Google\Cloud\SecretManager\V1\DeleteSecretRequest; use Google\Cloud\SecretManager\V1\DisableSecretVersionRequest; +use Google\Cloud\SecretManager\V1\GetSecretRequest; use Google\Cloud\SecretManager\V1\Replication; use Google\Cloud\SecretManager\V1\Replication\Automatic; use Google\Cloud\SecretManager\V1\Secret; @@ -38,6 +47,9 @@ class secretmanagerTest extends TestCase use TestTrait; private static $client; + private static $tagKeyClient; + private static $tagValuesClient; + private static $testSecret; private static $testSecretToDelete; private static $testSecretWithVersions; @@ -47,24 +59,49 @@ class secretmanagerTest extends TestCase private static $testSecretVersionToDestroy; private static $testSecretVersionToDisable; private static $testSecretVersionToEnable; + private static $testSecretWithTagToCreateName; + private static $testSecretBindTagToCreateName; + private static $testSecretWithLabelsToCreateName; + private static $testSecretWithAnnotationsToCreateName; + private static $testSecretWithDelayedDestroyToCreateName; private static $iamUser = 'user:sethvargo@google.com'; + private static $testLabelKey = 'test-label-key'; + private static $testLabelValue = 'test-label-value'; + private static $testUpdatedLabelValue = 'test-label-new-value'; + private static $testAnnotationKey = 'test-annotation-key'; + private static $testAnnotationValue = 'test-annotation-value'; + private static $testUpdatedAnnotationValue = 'test-annotation-new-value'; + private static $testDelayedDestroyTime = 86400; + + private static $testTagKey; + private static $testTagValue; public static function setUpBeforeClass(): void { self::$client = new SecretManagerServiceClient(); + self::$tagKeyClient = new TagKeysClient(); + self::$tagValuesClient = new TagValuesClient(); self::$testSecret = self::createSecret(); self::$testSecretToDelete = self::createSecret(); self::$testSecretWithVersions = self::createSecret(); self::$testSecretToCreateName = self::$client->secretName(self::$projectId, self::randomSecretId()); self::$testUmmrSecretToCreateName = self::$client->secretName(self::$projectId, self::randomSecretId()); + self::$testSecretWithTagToCreateName = self::$client->secretName(self::$projectId, self::randomSecretId()); + self::$testSecretBindTagToCreateName = self::$client->secretName(self::$projectId, self::randomSecretId()); + self::$testSecretWithLabelsToCreateName = self::$client->secretName(self::$projectId, self::randomSecretId()); + self::$testSecretWithAnnotationsToCreateName = self::$client->secretName(self::$projectId, self::randomSecretId()); + self::$testSecretWithDelayedDestroyToCreateName = self::$client->secretName(self::$projectId, self::randomSecretId()); self::$testSecretVersion = self::addSecretVersion(self::$testSecretWithVersions); self::$testSecretVersionToDestroy = self::addSecretVersion(self::$testSecretWithVersions); self::$testSecretVersionToDisable = self::addSecretVersion(self::$testSecretWithVersions); self::$testSecretVersionToEnable = self::addSecretVersion(self::$testSecretWithVersions); self::disableSecretVersion(self::$testSecretVersionToEnable); + + self::$testTagKey = self::createTagKey(self::randomSecretId()); + self::$testTagValue = self::createTagValue(self::randomSecretId()); } public static function tearDownAfterClass(): void @@ -74,6 +111,14 @@ public static function tearDownAfterClass(): void self::deleteSecret(self::$testSecretWithVersions->getName()); self::deleteSecret(self::$testSecretToCreateName); self::deleteSecret(self::$testUmmrSecretToCreateName); + self::deleteSecret(self::$testSecretWithTagToCreateName); + self::deleteSecret(self::$testSecretBindTagToCreateName); + self::deleteSecret(self::$testSecretWithLabelsToCreateName); + self::deleteSecret(self::$testSecretWithAnnotationsToCreateName); + self::deleteSecret(self::$testSecretWithDelayedDestroyToCreateName); + sleep(15); // Added a sleep to wait for the tag unbinding + self::deleteTagValue(); + self::deleteTagKey(); } private static function randomSecretId(): string @@ -127,6 +172,94 @@ private static function deleteSecret(string $name) } } + private static function getSecret(string $projectId, string $secretId): Secret + { + $name = self::$client->secretName($projectId, $secretId); + $getSecretRequest = (new GetSecretRequest()) + ->setName($name); + return self::$client->getSecret($getSecretRequest); + } + + private static function createTagKey(string $short_name): string + { + $parent = self::$client->projectName(self::$projectId); + $tagKey = (new TagKey()) + ->setParent($parent) + ->setShortName($short_name); + + $request = (new CreateTagKeyRequest()) + ->setTagKey($tagKey); + + $operation = self::$tagKeyClient->createTagKey($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + $createdTagKey = $operation->getResult(); + printf("Tag key created: %s\n", $createdTagKey->getName()); + return $createdTagKey->getName(); + } else { + $error = $operation->getError(); + printf("Error creating tag key: %s\n", $error->getMessage()); + return ''; + } + } + + private static function createTagValue(string $short_name): string + { + $tagValuesClient = new TagValuesClient(); + $tagValue = (new TagValue()) + ->setParent(self::$testTagKey) + ->setShortName($short_name); + + $request = (new CreateTagValueRequest()) + ->setTagValue($tagValue); + + $operation = self::$tagValuesClient->createTagValue($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + $createdTagValue = $operation->getResult(); + printf("Tag value created: %s\n", $createdTagValue->getName()); + return $createdTagValue->getName(); + } else { + $error = $operation->getError(); + printf("Error creating tag value: %s\n", $error->getMessage()); + return ''; + } + } + + private static function deleteTagKey() + { + $request = (new DeleteTagKeyRequest()) + ->setName(self::$testTagKey); + + $operation = self::$tagKeyClient->deleteTagKey($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + printf("Tag key deleted: %s\n", self::$testTagValue); + } else { + $error = $operation->getError(); + printf("Error deleting tag key: %s\n", $error->getMessage()); + } + } + + private static function deleteTagValue() + { + $request = (new DeleteTagValueRequest()) + ->setName(self::$testTagValue); + + $operation = self::$tagValuesClient->deleteTagValue($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + printf("Tag value deleted: %s\n", self::$testTagValue); + } else { + $error = $operation->getError(); + printf("Error deleting tag value: %s\n", $error->getMessage()); + } + } + public function testAccessSecretVersion() { $name = self::$client->parseName(self::$testSecretVersion->getName()); @@ -328,4 +461,185 @@ public function testUpdateSecretWithAlias() $this->assertStringContainsString('Updated secret', $output); } + + public function testCreateSecretWithTags() + { + $name = self::$client->parseName(self::$testSecretWithTagToCreateName); + + $output = $this->runFunctionSnippet('create_secret_with_tags', [ + $name['project'], + $name['secret'], + self::$testTagKey, + self::$testTagValue + ]); + + $this->assertStringContainsString('Created secret', $output); + } + + public function testBindTagsToSecret() + { + $name = self::$client->parseName(self::$testSecretBindTagToCreateName); + + $output = $this->runFunctionSnippet('bind_tags_to_secret', [ + $name['project'], + $name['secret'], + self::$testTagValue + ]); + + $this->assertStringContainsString('Created secret', $output); + $this->assertStringContainsString('Tag binding created for secret', $output); + } + + public function testCreateSecretWithLabels() + { + $name = self::$client->parseName(self::$testSecretWithLabelsToCreateName); + + $output = $this->runFunctionSnippet('create_secret_with_labels', [ + $name['project'], + $name['secret'], + self::$testLabelKey, + self::$testLabelValue + ]); + + $this->assertStringContainsString('Created secret', $output); + } + + public function testCreateSecretWithAnnotations() + { + $name = self::$client->parseName(self::$testSecretWithAnnotationsToCreateName); + + $output = $this->runFunctionSnippet('create_secret_with_annotations', [ + $name['project'], + $name['secret'], + self::$testAnnotationKey, + self::$testAnnotationValue + ]); + + $this->assertStringContainsString('Created secret', $output); + } + + public function testViewSecretAnnotations() + { + $name = self::$client->parseName(self::$testSecretWithAnnotationsToCreateName); + + $output = $this->runFunctionSnippet('view_secret_annotations', [ + $name['project'], + $name['secret'] + ]); + + $this->assertStringContainsString('Get secret', $output); + } + + public function testViewSecretLabels() + { + $name = self::$client->parseName(self::$testSecretWithLabelsToCreateName); + + $output = $this->runFunctionSnippet('view_secret_labels', [ + $name['project'], + $name['secret'] + ]); + + $this->assertStringContainsString('Get secret', $output); + } + + public function testEditSecretLabels() + { + $name = self::$client->parseName(self::$testSecretWithLabelsToCreateName); + + $output = $this->runFunctionSnippet('edit_secret_labels', [ + $name['project'], + $name['secret'], + self::$testLabelKey, + self::$testUpdatedLabelValue + ]); + + $this->assertStringContainsString('Updated secret', $output); + } + + public function testEditSecretAnnotations() + { + $name = self::$client->parseName(self::$testSecretWithAnnotationsToCreateName); + + $output = $this->runFunctionSnippet('edit_secret_annotations', [ + $name['project'], + $name['secret'], + self::$testAnnotationKey, + self::$testUpdatedAnnotationValue + ]); + + $this->assertStringContainsString('Updated secret', $output); + } + + public function testDeleteSecretLabel() + { + $name = self::$client->parseName(self::$testSecretWithLabelsToCreateName); + + $output = $this->runFunctionSnippet('delete_secret_label', [ + $name['project'], + $name['secret'], + self::$testLabelKey + ]); + + $this->assertStringContainsString('Updated secret', $output); + } + + public function testDeleteSecretAnnotation() + { + $name = self::$client->parseName(self::$testSecretWithAnnotationsToCreateName); + + $output = $this->runFunctionSnippet('delete_secret_annotation', [ + $name['project'], + $name['secret'], + self::$testAnnotationKey + ]); + + $this->assertStringContainsString('Updated secret', $output); + } + + public function testCreateSecretWithDelayedDestroyed() + { + $name = self::$client->parseName(self::$testSecretWithDelayedDestroyToCreateName); + + $output = $this->runFunctionSnippet('create_secret_with_delayed_destroy', [ + $name['project'], + $name['secret'], + self::$testDelayedDestroyTime + ]); + + $this->assertStringContainsString('Created secret', $output); + + $secret = self::getSecret($name['project'], $name['secret']); + $this->assertEquals(self::$testDelayedDestroyTime, $secret->getVersionDestroyTtl()->getSeconds()); + } + + public function testDisableSecretDelayedDestroy() + { + $name = self::$client->parseName(self::$testSecretWithDelayedDestroyToCreateName); + + $output = $this->runFunctionSnippet('disable_secret_delayed_destroy', [ + $name['project'], + $name['secret'], + ]); + + $this->assertStringContainsString('Updated secret', $output); + + $secret = self::getSecret($name['project'], $name['secret']); + $this->assertNull($secret->getVersionDestroyTtl()); + } + + public function testUpdateSecretWithDelayedDestroyed() + { + $name = self::$client->parseName(self::$testSecretWithDelayedDestroyToCreateName); + + $output = $this->runFunctionSnippet('update_secret_with_delayed_destroy', [ + $name['project'], + $name['secret'], + self::$testDelayedDestroyTime + ]); + + $this->assertStringContainsString('Updated secret', $output); + + $secret = self::getSecret($name['project'], $name['secret']); + $this->assertEquals(self::$testDelayedDestroyTime, $secret->getVersionDestroyTtl()->getSeconds()); + } } diff --git a/spanner/composer.json b/spanner/composer.json index f06d93f93f..cfa4184bc3 100755 --- a/spanner/composer.json +++ b/spanner/composer.json @@ -1,6 +1,6 @@ { "require": { - "google/cloud-spanner": "^1.97" + "google/cloud-spanner": "^2.0" }, "autoload": { "psr-4": { diff --git a/spanner/src/pg_update_dml_returning.php b/spanner/src/pg_update_dml_returning.php index 2a975b2297..f5f11f57d6 100644 --- a/spanner/src/pg_update_dml_returning.php +++ b/spanner/src/pg_update_dml_returning.php @@ -48,7 +48,7 @@ function pg_update_dml_returning(string $instanceId, string $databaseId): void $result = $transaction->execute( 'UPDATE Albums ' . 'SET MarketingBudget = MarketingBudget * 2 ' - . 'WHERE SingerId = 1 and AlbumId = 1' + . 'WHERE SingerId = 1 and AlbumId = 1 ' . 'RETURNING MarketingBudget' ); foreach ($result->rows() as $row) { diff --git a/spanner/src/read_stale_data.php b/spanner/src/read_stale_data.php index f06695410c..977d3ebb20 100644 --- a/spanner/src/read_stale_data.php +++ b/spanner/src/read_stale_data.php @@ -24,7 +24,7 @@ namespace Google\Cloud\Samples\Spanner; // [START spanner_read_stale_data] -use Google\Cloud\Spanner\Duration; +use Google\Protobuf\Duration; use Google\Cloud\Spanner\SpannerClient; /** @@ -49,7 +49,7 @@ function read_stale_data(string $instanceId, string $databaseId): void 'Albums', $keySet, ['SingerId', 'AlbumId', 'AlbumTitle'], - ['exactStaleness' => new Duration(15)] + ['exactStaleness' => new Duration(['seconds' => 15])] ); foreach ($results->rows() as $row) { diff --git a/speech/README.md b/speech/README.md index e5bec707dd..c18207281c 100644 --- a/speech/README.md +++ b/speech/README.md @@ -44,7 +44,6 @@ API using the transcribe command: ```sh php src/transcribe_sync.php test/data/audio32KHz.raw -php src/transcribe_async.php test/data/audio32KHz.raw php src/transcribe_async_words.php test/data/audio32KHz.raw ``` ## Troubleshooting diff --git a/speech/composer.json b/speech/composer.json index 4e10c30a50..8f9ce951b5 100644 --- a/speech/composer.json +++ b/speech/composer.json @@ -1,6 +1,6 @@ { "require": { - "google/cloud-speech": "^1.0.0", - "google/cloud-storage": "^1.20.1" + "google/cloud-speech": "^2.2", + "google/cloud-storage": "^1.36" } } diff --git a/speech/quickstart.php b/speech/quickstart.php index 742e5892d7..d1e0bb4d17 100644 --- a/speech/quickstart.php +++ b/speech/quickstart.php @@ -1,6 +1,6 @@ setUri($gcsURI); +# Your Google Cloud Project ID and location +$projectId = 'YOUR_PROJECT_ID'; +$location = 'global'; + +# Instantiates a client +$speech = new SpeechClient(); -# The audio file's encoding, sample rate and language -$config = new RecognitionConfig([ - 'encoding' => AudioEncoding::LINEAR16, - 'sample_rate_hertz' => 16000, - 'language_code' => 'en-US' +// Create a Recognizer +$createRecognizerRequest = new CreateRecognizerRequest([ + 'parent' => SpeechClient::locationName($projectId, $location), + 'recognizer_id' => $recognizerId = 'quickstart-recognizer-' . uniqid(), + 'recognizer' => new Recognizer([ + 'language_codes' => ['en-US'], + 'model' => 'latest_short' + ]) ]); -# Instantiates a client -$client = new SpeechClient(); +$operation = $speech->createRecognizer($createRecognizerRequest); + +// Wait for the operation to complete +$operation->pollUntilComplete(); +if ($operation->operationSucceeded()) { + $result = $operation->getResult(); + printf('Created Recognizer: %s' . PHP_EOL, $result->getName()); +} else { + print_r($operation->getError()); +} + +$config = (new RecognitionConfig()) + // Can also use {@see Google\Cloud\Speech\V2\AutoDetectDecodingConfig} + // ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); + + ->setExplicitDecodingConfig(new ExplicitDecodingConfig([ + 'encoding' => AudioEncoding::LINEAR16, + 'sample_rate_hertz' => 16000, + 'audio_channel_count' => 1, + ])); + +$recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); +$request = (new RecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setUri($gcsURI); # Detects speech in the audio file -$response = $client->recognize($config, $audio); +$response = $speech->recognize($request); # Print most likely transcription foreach ($response->getResults() as $result) { @@ -53,6 +87,4 @@ printf('Transcript: %s' . PHP_EOL, $transcript); } -$client->close(); - -# [END speech_quickstart] +$speech->close(); diff --git a/speech/src/create_recognizer.php b/speech/src/create_recognizer.php new file mode 100644 index 0000000000..37a49aa164 --- /dev/null +++ b/speech/src/create_recognizer.php @@ -0,0 +1,72 @@ + $apiEndpoint]); + + // Create a Recognizer + $recognizer = new Recognizer([ + 'language_codes' => ['en-US'], + 'model' => $model, + ]); + + // Create the CreateRecognizerRequest + $createRecognizerRequest = new CreateRecognizerRequest([ + 'parent' => SpeechClient::locationName($projectId, $location), + 'recognizer_id' => $recognizerId, + 'recognizer' => $recognizer + ]); + + // Call the createRecognizer method + $operation = $speech->createRecognizer($createRecognizerRequest); + + // Wait for the operation to complete + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + $result = $operation->getResult(); + printf('Created Recognizer: %s' . PHP_EOL, $result->getName()); + } else { + print_r($operation->getError()); + } + + $speech->close(); +} + +// 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/speech/src/delete_recognizer.php b/speech/src/delete_recognizer.php new file mode 100644 index 0000000000..2db7732d0f --- /dev/null +++ b/speech/src/delete_recognizer.php @@ -0,0 +1,57 @@ + $apiEndpoint]); + + // Create the DeleteRecognizerRequest + $deleteRecognizerRequest = new DeleteRecognizerRequest([ + 'name' => SpeechClient::recognizerName($projectId, $location, $recognizerId) + ]); + + // Call the deleteRecognizer method + $operation = $speech->deleteRecognizer($deleteRecognizerRequest); + + // Wait for the operation to complete + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + printf('Deleted Recognizer: %s' . PHP_EOL, $deleteRecognizerRequest->getName()); + } else { + print_r($operation->getError()); + } + + $speech->close(); +} + +// 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/speech/src/list_recognizers.php b/speech/src/list_recognizers.php new file mode 100644 index 0000000000..7876423fa9 --- /dev/null +++ b/speech/src/list_recognizers.php @@ -0,0 +1,52 @@ + $apiEndpoint]); + + // Create the ListRecognizersRequest + $ListRecognizersRequest = new ListRecognizersRequest([ + 'parent' => SpeechClient::locationName($projectId, $location), + ]); + + // Call the ListRecognizers method + $responses = $speech->listRecognizers($ListRecognizersRequest); + + foreach ($responses as $recognizer) { + printf('Recognizer name: %s' . PHP_EOL, $recognizer->getName()); + } +} + +// 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/speech/src/multi_region_gcs.php b/speech/src/multi_region_gcs.php index 2d65a9a783..97e0586ae2 100644 --- a/speech/src/multi_region_gcs.php +++ b/speech/src/multi_region_gcs.php @@ -1,6 +1,6 @@ setUri($uri); + $options = ['apiEndpoint' => sprintf('%s-speech.googleapis.com', $location)]; + $speech = new SpeechClient($options); + + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); - # The audio file's encoding, sample rate and language - $config = new RecognitionConfig([ - 'encoding' => AudioEncoding::LINEAR16, - 'sample_rate_hertz' => 16000, - 'language_code' => 'en-US' - ]); + $config = (new RecognitionConfig()) + // Can also use {@see Google\Cloud\Speech\V2\AutoDetectDecodingConfig} + // ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); - # Specify a new endpoint. - $options = ['apiEndpoint' => 'eu-speech.googleapis.com']; + ->setExplicitDecodingConfig(new ExplicitDecodingConfig([ + 'encoding' => AudioEncoding::LINEAR16, + 'sample_rate_hertz' => 16000, + 'audio_channel_count' => 1, + ])); - # Instantiates a client - $client = new SpeechClient($options); + $request = (new RecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setUri($uri); # Detects speech in the audio file - $response = $client->recognize($config, $audio); + $response = $speech->recognize($request); # Print most likely transcription foreach ($response->getResults() as $result) { @@ -57,8 +63,6 @@ function multi_region_gcs(string $uri) $transcript = $mostLikely->getTranscript(); printf('Transcript: %s' . PHP_EOL, $transcript); } - - $client->close(); } # [END speech_transcribe_with_multi_region_gcs] diff --git a/speech/src/profanity_filter.php b/speech/src/profanity_filter.php index cbe5ba5554..cb93fa5618 100644 --- a/speech/src/profanity_filter.php +++ b/speech/src/profanity_filter.php @@ -1,5 +1,5 @@ $apiEndpoint]); // get contents of a file into a string $content = file_get_contents($audioFile); - // set string as audio content - $audio = (new RecognitionAudio()) - ->setContent($content); + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); + + // When true, the profanity filter will be enabled. + $features = new RecognitionFeatures([ + 'profanity_filter' => true + ]); - // set config $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode) - ->setProfanityFilter($profanityFilter); + ->setFeatures($features) - // create the speech client - $client = new SpeechClient(); + // Can also use {@see Google\Cloud\Speech\V2\ExplicitDecodingConfig} + // ->setExplicitDecodingConfig(new ExplicitDecodingConfig([...]); + + ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); + + $request = (new RecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setContent($content); # Detects speech in the audio file - $response = $client->recognize($config, $audio); + $response = $speech->recognize($request); # Print most likely transcription foreach ($response->getResults() as $result) { @@ -57,7 +66,7 @@ function profanity_filter(string $audioFile) printf('Transcript: %s' . PHP_EOL, $transcript); } - $client->close(); + $speech->close(); } # [END speech_profanity_filter] diff --git a/speech/src/profanity_filter_gcs.php b/speech/src/profanity_filter_gcs.php index 609e19e9c1..19c2596f5d 100644 --- a/speech/src/profanity_filter_gcs.php +++ b/speech/src/profanity_filter_gcs.php @@ -1,5 +1,5 @@ setUri($uri); + // create the speech client + $apiEndpoint = $location === 'global' ? null : sprintf('%s-speech.googleapis.com', $location); + $speech = new SpeechClient(['apiEndpoint' => $apiEndpoint]); + + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); + + // When true, the profanity filter will be enabled. + $features = new RecognitionFeatures([ + 'profanity_filter' => true + ]); - // set config $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode) - ->setProfanityFilter($profanityFilter); + ->setFeatures($features) - // create the speech client - $client = new SpeechClient(); + // Can also use {@see Google\Cloud\Speech\V2\AutoDetectDecodingConfig} + // ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); + + ->setExplicitDecodingConfig(new ExplicitDecodingConfig([ + 'encoding' => AudioEncoding::LINEAR16, + 'sample_rate_hertz' => 16000, + 'audio_channel_count' => 1, + ])); + + $request = (new RecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setUri($uri); # Detects speech in the audio file - $response = $client->recognize($config, $audio); + $response = $speech->recognize($request); # Print most likely transcription foreach ($response->getResults() as $result) { - $transcript = $result->getAlternatives()[0]->getTranscript(); + $alternatives = $result->getAlternatives(); + $mostLikely = $alternatives[0]; + $transcript = $mostLikely->getTranscript(); printf('Transcript: %s' . PHP_EOL, $transcript); } - $client->close(); + $speech->close(); } # [END speech_profanity_filter_gcs] diff --git a/speech/src/streaming_recognize.php b/speech/src/streaming_recognize.php index 2465de4aee..31e6f449bc 100644 --- a/speech/src/streaming_recognize.php +++ b/speech/src/streaming_recognize.php @@ -1,6 +1,6 @@ $apiEndpoint]); - $speechClient = new SpeechClient(); - try { - $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode); + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); - $strmConfig = new StreamingRecognitionConfig(); - $strmConfig->setConfig($config); + // set streaming config + $features = new RecognitionFeatures([ + 'enable_automatic_punctuation' => true + ]); + $streamingConfig = (new StreamingRecognitionConfig()) + ->setConfig(new RecognitionConfig([ + // Can also use {@see Google\Cloud\Speech\V2\ExplicitDecodingConfig} + 'auto_decoding_config' => new AutoDetectDecodingConfig(), + 'features' => $features + ])); + $streamingRequest = (new StreamingRecognizeRequest()) + ->setRecognizer($recognizerName) + ->setStreamingConfig($streamingConfig); - $strmReq = new StreamingRecognizeRequest(); - $strmReq->setStreamingConfig($strmConfig); + // set the streaming request + $stream = $speech->streamingRecognize(); + $stream->write($streamingRequest); - $strm = $speechClient->streamingRecognize(); - $strm->write($strmReq); + // stream the audio file + $handle = fopen($audioFile, 'r'); + while (!feof($handle)) { + $chunk = fread($handle, 4096); + $streamingRequest = (new StreamingRecognizeRequest()) + ->setAudio($chunk); + $stream->write($streamingRequest); + } + fclose($handle); - $strmReq = new StreamingRecognizeRequest(); - $content = file_get_contents($audioFile); - $strmReq->setAudioContent($content); - $strm->write($strmReq); + // read the responses + foreach ($stream->closeWriteAndReadAll() as $response) { + // an empty response indicates the end of the stream + if (!$response->getResults()) { + continue; + } - foreach ($strm->closeWriteAndReadAll() as $response) { - foreach ($response->getResults() as $result) { - foreach ($result->getAlternatives() as $alt) { - printf("Transcription: %s\n", $alt->getTranscript()); - } - } + // process the results + foreach ($response->getResults() as $result) { + printf( + 'Transcript: "%s"' . PHP_EOL, + $result->getAlternatives()[0]->getTranscript() + ); } - } finally { - $speechClient->close(); } } # [END speech_transcribe_streaming] diff --git a/speech/src/transcribe_async.php b/speech/src/transcribe_async.php deleted file mode 100644 index 99fe72157c..0000000000 --- a/speech/src/transcribe_async.php +++ /dev/null @@ -1,85 +0,0 @@ -setContent($content); - - // set config - $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode); - - // create the speech client - $client = new SpeechClient(); - - // create the asyncronous recognize operation - $operation = $client->longRunningRecognize($config, $audio); - $operation->pollUntilComplete(); - - if ($operation->operationSucceeded()) { - $response = $operation->getResult(); - - // each result is for a consecutive portion of the audio. iterate - // through them to get the transcripts for the entire audio file. - foreach ($response->getResults() as $result) { - $alternatives = $result->getAlternatives(); - $mostLikely = $alternatives[0]; - $transcript = $mostLikely->getTranscript(); - $confidence = $mostLikely->getConfidence(); - printf('Transcript: %s' . PHP_EOL, $transcript); - printf('Confidence: %s' . PHP_EOL, $confidence); - } - } else { - print_r($operation->getError()); - } - - $client->close(); -} -# [END speech_transcribe_async] - -// 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/speech/src/transcribe_async_gcs.php b/speech/src/transcribe_async_gcs.php index 75d050091f..217f5f71dd 100644 --- a/speech/src/transcribe_async_gcs.php +++ b/speech/src/transcribe_async_gcs.php @@ -24,56 +24,78 @@ namespace Google\Cloud\Samples\Speech; # [START speech_transcribe_async_gcs] -use Google\Cloud\Speech\V1\SpeechClient; -use Google\Cloud\Speech\V1\RecognitionAudio; -use Google\Cloud\Speech\V1\RecognitionConfig; -use Google\Cloud\Speech\V1\RecognitionConfig\AudioEncoding; +use Google\Cloud\Speech\V2\Client\SpeechClient; +use Google\Cloud\Speech\V2\BatchRecognizeRequest; +use Google\Cloud\Speech\V2\RecognitionConfig; +use Google\Cloud\Speech\V2\BatchRecognizeFileMetadata; +use Google\Cloud\Speech\V2\ExplicitDecodingConfig; +use Google\Cloud\Speech\V2\ExplicitDecodingConfig\AudioEncoding; +use Google\Cloud\Speech\V2\RecognitionOutputConfig; +use Google\Cloud\Speech\V2\InlineOutputConfig; /** - * @param string $uri The Cloud Storage object to transcribe (gs://your-bucket-name/your-object-name) + * @param string $projectId The Google Cloud project ID. + * @param string $location The location of the recognizer. + * @param string $recognizerId The ID of the recognizer to use. + * @param string $uri The Cloud Storage object to transcribe (other than global) + * e.x. gs://cloud-samples-data/speech/brooklyn_bridge.raw */ -function transcribe_async_gcs(string $uri) +function transcribe_async_gcs(string $projectId, string $location, string $recognizerId, string $uri) { - // change these variables if necessary - $encoding = AudioEncoding::LINEAR16; - $sampleRateHertz = 32000; - $languageCode = 'en-US'; + $apiEndpoint = $location === 'global' ? null : sprintf('%s-speech.googleapis.com', $location); + $speech = new SpeechClient(['apiEndpoint' => $apiEndpoint]); + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); - // set string as audio content - $audio = (new RecognitionAudio()) - ->setUri($uri); - - // set config $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode); + // Can also use {@see Google\Cloud\Speech\V2\ExplicitDecodingConfig} + // ->setExplicitDecodingConfig(new ExplicitDecodingConfig([...]); + + ->setExplicitDecodingConfig(new ExplicitDecodingConfig([ + // change these variables if necessary + 'encoding' => AudioEncoding::LINEAR16, + 'sample_rate_hertz' => 16000, + 'audio_channel_count' => 1, + ])); - // create the speech client - $client = new SpeechClient(); + $outputConfig = (new RecognitionOutputConfig()) + ->setInlineResponseConfig(new InlineOutputConfig()); - // create the asyncronous recognize operation - $operation = $client->longRunningRecognize($config, $audio); - $operation->pollUntilComplete(); + $file = new BatchRecognizeFileMetadata(); + $file->setUri($uri); - if ($operation->operationSucceeded()) { - $response = $operation->getResult(); + $request = (new BatchRecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setFiles([$file]) + ->setRecognitionOutputConfig($outputConfig); - // each result is for a consecutive portion of the audio. iterate - // through them to get the transcripts for the entire audio file. - foreach ($response->getResults() as $result) { - $alternatives = $result->getAlternatives(); - $mostLikely = $alternatives[0]; - $transcript = $mostLikely->getTranscript(); - $confidence = $mostLikely->getConfidence(); - printf('Transcript: %s' . PHP_EOL, $transcript); - printf('Confidence: %s' . PHP_EOL, $confidence); + try { + $operation = $speech->batchRecognize($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + $response = $operation->getResult(); + foreach ($response->getResults() as $result) { + if ($result->getError()) { + print('Error: ' . $result->getError()->getMessage()); + } + // get the most likely transcription + $transcript = $result->getInlineResult()->getTranscript(); + foreach ($transcript->getResults() as $transacriptResult) { + $alternatives = $transacriptResult->getAlternatives(); + $mostLikely = $alternatives[0]; + $transcript = $mostLikely->getTranscript(); + $confidence = $mostLikely->getConfidence(); + printf('Transcript: %s' . PHP_EOL, $transcript); + printf('Confidence: %s' . PHP_EOL, $confidence); + } + } + } else { + print_r($operation->getError()); } - } else { - print_r($operation->getError()); + } finally { + $speech->close(); } - - $client->close(); } # [END speech_transcribe_async_gcs] diff --git a/speech/src/transcribe_async_words.php b/speech/src/transcribe_async_words.php index 0e7f12c0d3..a393885520 100644 --- a/speech/src/transcribe_async_words.php +++ b/speech/src/transcribe_async_words.php @@ -1,6 +1,6 @@ $apiEndpoint]); + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); - // When true, time offsets for every word will be included in the response. - $enableWordTimeOffsets = true; + // When this is enabled, we send all the words from the beginning of the audio. + $features = new RecognitionFeatures([ + 'diarization_config' => new SpeakerDiarizationConfig(), + ]); - // get contents of a file into a string - $content = file_get_contents($audioFile); + $config = (new RecognitionConfig()) + ->setFeatures($features) + // When running outside the "global" location, you can set the model to "chirp_3" in + // RecognitionConfig instead of on the recognizer. + // ->setModel('chirp_3') - // set string as audio content - $audio = (new RecognitionAudio()) - ->setContent($content); + // Can also use {@see Google\Cloud\Speech\V2\AutoDetectDecodingConfig} + // ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); - // set config - $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode) - ->setEnableWordTimeOffsets($enableWordTimeOffsets); + ->setExplicitDecodingConfig(new ExplicitDecodingConfig([ + // change these variables if necessary + 'encoding' => AudioEncoding::LINEAR16, + 'sample_rate_hertz' => 16000, + 'audio_channel_count' => 1, + ])); - // create the speech client - $client = new SpeechClient(); + $outputConfig = (new RecognitionOutputConfig()) + ->setInlineResponseConfig(new InlineOutputConfig()); - // create the asyncronous recognize operation - $operation = $client->longRunningRecognize($config, $audio); - $operation->pollUntilComplete(); + $file = new BatchRecognizeFileMetadata(); + $file->setUri($uri); - if ($operation->operationSucceeded()) { - $response = $operation->getResult(); + $request = (new BatchRecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setFiles([$file]) + ->setRecognitionOutputConfig($outputConfig); - // each result is for a consecutive portion of the audio. iterate - // through them to get the transcripts for the entire audio file. - foreach ($response->getResults() as $result) { - $alternatives = $result->getAlternatives(); - $mostLikely = $alternatives[0]; - $transcript = $mostLikely->getTranscript(); - $confidence = $mostLikely->getConfidence(); - printf('Transcript: %s' . PHP_EOL, $transcript); - printf('Confidence: %s' . PHP_EOL, $confidence); - foreach ($mostLikely->getWords() as $wordInfo) { - $startTime = $wordInfo->getStartTime(); - $endTime = $wordInfo->getEndTime(); - printf(' Word: %s (start: %s, end: %s)' . PHP_EOL, - $wordInfo->getWord(), - $startTime->serializeToJsonString(), - $endTime->serializeToJsonString()); + try { + $operation = $speech->batchRecognize($request); + $operation->pollUntilComplete(); + + if ($operation->operationSucceeded()) { + $response = $operation->getResult(); + foreach ($response->getResults() as $result) { + if ($result->getError()) { + print('Error: ' . $result->getError()->getMessage()); + } + // get the most likely transcription + $transcript = $result->getInlineResult()->getTranscript(); + foreach ($transcript->getResults() as $transacriptResult) { + $alternatives = $transacriptResult->getAlternatives(); + $mostLikely = $alternatives[0]; + foreach ($mostLikely->getWords() as $wordInfo) { + $startTime = $wordInfo->getStartOffset(); + $endTime = $wordInfo->getEndOffset(); + printf(' Word: %s (start: %s, end: %s)' . PHP_EOL, + $wordInfo->getWord(), + $startTime?->serializeToJsonString(), + $endTime?->serializeToJsonString() + ); + } + } } + } else { + print_r($operation->getError()); } - } else { - print_r($operation->getError()); + } finally { + $speech->close(); } - - $client->close(); } # [END speech_transcribe_async_word_time_offsets_gcs] diff --git a/speech/src/transcribe_auto_punctuation.php b/speech/src/transcribe_auto_punctuation.php index 2eb1808f05..5e48d5c45e 100644 --- a/speech/src/transcribe_auto_punctuation.php +++ b/speech/src/transcribe_auto_punctuation.php @@ -1,6 +1,6 @@ $apiEndpoint]); // get contents of a file into a string $content = file_get_contents($audioFile); - // set string as audio content - $audio = (new RecognitionAudio()) - ->setContent($content); + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); + + // When true, automatic punctuation will be enabled. + $features = new RecognitionFeatures([ + 'enable_automatic_punctuation' => true + ]); - // set config $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode) - ->setEnableAutomaticPunctuation(true); + ->setFeatures($features) - // create the speech client - $client = new SpeechClient(); + // Can also use {@see Google\Cloud\Speech\V2\ExplicitDecodingConfig} + // ->setExplicitDecodingConfig(new ExplicitDecodingConfig([...]); + + ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); + + $request = (new RecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setContent($content); // make the API call - $response = $client->recognize($config, $audio); + $response = $speech->recognize($request); $results = $response->getResults(); // print results @@ -70,7 +79,7 @@ function transcribe_auto_punctuation(string $audioFile) printf('Confidence: %s' . PHP_EOL, $confidence); } - $client->close(); + $speech->close(); } # [END speech_transcribe_auto_punctuation] diff --git a/speech/src/transcribe_enhanced_model.php b/speech/src/transcribe_enhanced_model.php index 8341552523..f81886806e 100644 --- a/speech/src/transcribe_enhanced_model.php +++ b/speech/src/transcribe_enhanced_model.php @@ -1,6 +1,6 @@ $apiEndpoint]); // get contents of a file into a string $content = file_get_contents($audioFile); - // set string as audio content - $audio = (new RecognitionAudio()) - ->setContent($content); + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); // set config $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode) - ->setUseEnhanced(true) - ->setModel('phone_call'); + ->setModel('telephony') - // create the speech client - $client = new SpeechClient(); + // Can also use {@see Google\Cloud\Speech\V2\ExplicitDecodingConfig} + // ->setExplicitDecodingConfig(new ExplicitDecodingConfig([...]); + + ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); + + $request = (new RecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setContent($content); // make the API call - $response = $client->recognize($config, $audio); + $response = $speech->recognize($request); $results = $response->getResults(); // print results @@ -71,7 +74,7 @@ function transcribe_enhanced_model(string $audioFile) printf('Confidence: %s' . PHP_EOL, $confidence); } - $client->close(); + $speech->close(); } # [END speech_transcribe_enhanced_model] diff --git a/speech/src/transcribe_model_selection.php b/speech/src/transcribe_model_selection.php index 3d5a97385f..d352f0f548 100644 --- a/speech/src/transcribe_model_selection.php +++ b/speech/src/transcribe_model_selection.php @@ -1,6 +1,6 @@ $apiEndpoint]); // get contents of a file into a string $content = file_get_contents($audioFile); - // set string as audio content - $audio = (new RecognitionAudio()) - ->setContent($content); + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); // set config $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode) - ->setModel($model); + ->setModel($model) - // create the speech client - $client = new SpeechClient(); + // Can also use {@see Google\Cloud\Speech\V2\ExplicitDecodingConfig} + // ->setExplicitDecodingConfig(new ExplicitDecodingConfig([...]); + + ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); + + $request = (new RecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setContent($content); // make the API call - $response = $client->recognize($config, $audio); + $response = $speech->recognize($request); $results = $response->getResults(); // print results @@ -71,7 +75,7 @@ function transcribe_model_selection(string $audioFile, string $model) printf('Confidence: %s' . PHP_EOL, $confidence); } - $client->close(); + $speech->close(); } # [END speech_transcribe_model_selection] diff --git a/speech/src/transcribe_sync.php b/speech/src/transcribe_sync.php index 82defef734..c450a96d7c 100644 --- a/speech/src/transcribe_sync.php +++ b/speech/src/transcribe_sync.php @@ -1,6 +1,6 @@ $apiEndpoint]); // get contents of a file into a string $content = file_get_contents($audioFile); - // set string as audio content - $audio = (new RecognitionAudio()) - ->setContent($content); + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); - // set config $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode); - // create the speech client - $client = new SpeechClient(); + // Can also use {@see Google\Cloud\Speech\V2\ExplicitDecodingConfig} + // ->setExplicitDecodingConfig(new ExplicitDecodingConfig([...]); + + ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); + + $request = (new RecognizeRequest()) + ->setRecognizer($recognizerName) + ->setContent($content) + ->setConfig($config); try { - $response = $client->recognize($config, $audio); + $response = $speech->recognize($request); foreach ($response->getResults() as $result) { $alternatives = $result->getAlternatives(); $mostLikely = $alternatives[0]; @@ -66,7 +69,7 @@ function transcribe_sync(string $audioFile) printf('Confidence: %s' . PHP_EOL, $confidence); } } finally { - $client->close(); + $speech->close(); } } # [END speech_transcribe_sync] diff --git a/speech/src/transcribe_sync_gcs.php b/speech/src/transcribe_sync_gcs.php index 542f7c0e0f..7c38fadf04 100644 --- a/speech/src/transcribe_sync_gcs.php +++ b/speech/src/transcribe_sync_gcs.php @@ -1,6 +1,6 @@ $apiEndpoint]); - // set string as audio content - $audio = (new RecognitionAudio()) - ->setUri($uri); + $recognizerName = SpeechClient::recognizerName($projectId, $location, $recognizerId); - // set config $config = (new RecognitionConfig()) - ->setEncoding($encoding) - ->setSampleRateHertz($sampleRateHertz) - ->setLanguageCode($languageCode); + // Can also use {@see Google\Cloud\Speech\V2\AutoDetectDecodingConfig} + // ->setAutoDecodingConfig(new AutoDetectDecodingConfig()); - // create the speech client - $client = new SpeechClient(); + ->setExplicitDecodingConfig(new ExplicitDecodingConfig([ + // change these variables if necessary + 'encoding' => AudioEncoding::LINEAR16, + 'sample_rate_hertz' => 16000, + 'audio_channel_count' => 1, + ])); + + $request = (new RecognizeRequest()) + ->setRecognizer($recognizerName) + ->setConfig($config) + ->setUri($uri); try { - $response = $client->recognize($config, $audio); + $response = $speech->recognize($request); foreach ($response->getResults() as $result) { $alternatives = $result->getAlternatives(); $mostLikely = $alternatives[0]; @@ -63,7 +71,7 @@ function transcribe_sync_gcs(string $uri) printf('Confidence: %s' . PHP_EOL, $confidence); } } finally { - $client->close(); + $speech->close(); } } # [END speech_transcribe_sync_gcs] diff --git a/speech/test/quickstartTest.php b/speech/test/quickstartTest.php index d958182ff9..8a86fcb886 100644 --- a/speech/test/quickstartTest.php +++ b/speech/test/quickstartTest.php @@ -1,6 +1,6 @@ expectOutputRegex('/Bridge/'); + if (!$projectId = getenv('GOOGLE_PROJECT_ID')) { + $this->markTestSkipped('GOOGLE_PROJECT_ID must be set.'); + } + + $file = sys_get_temp_dir() . '/speech_quickstart.php'; + $contents = file_get_contents(__DIR__ . '/../quickstart.php'); + $contents = str_replace( + ['YOUR_PROJECT_ID', '__DIR__'], + [$projectId, sprintf('"%s/.."', __DIR__)], + $contents + ); + file_put_contents($file, $contents); + + // Invoke quickstart.php and capture output + ob_start(); + include $file; + $result = ob_get_clean(); + + // Make sure it looks correct + $this->assertStringContainsString('Transcript: how old is the Brooklyn Bridge', $result); } } diff --git a/speech/test/speechTest.php b/speech/test/speechTest.php index d4198a0fb7..76326e9cc5 100644 --- a/speech/test/speechTest.php +++ b/speech/test/speechTest.php @@ -1,6 +1,6 @@ runFunctionSnippet('base64_encode_audio', [$audioFile]); @@ -39,69 +51,99 @@ public function testBase64Audio() ); } + public function testCreateRecognizer() + { + $output = $this->runFunctionSnippet('create_recognizer', [self::$projectId, self::GLOBAL, self::$recognizerId]); + $this->assertStringContainsString('Created Recognizer:', $output); + } + + /** @depends testCreateRecognizer */ public function testTranscribeEnhanced() { $path = __DIR__ . '/data/commercial_mono.wav'; - $output = $this->runFunctionSnippet('transcribe_enhanced_model', [$path]); + $output = $this->runFunctionSnippet('transcribe_enhanced_model', [self::$projectId, self::GLOBAL, self::$recognizerId, $path]); $this->assertStringContainsString('Chrome', $output); } + /** @depends testCreateRecognizer */ public function testTranscribeModel() { - $path = __DIR__ . '/data/audio32KHz.raw'; + $path = __DIR__ . '/data/audio32KHz.flac'; $output = $this->runFunctionSnippet( 'transcribe_model_selection', - [$path, 'video'] + [self::$projectId, self::GLOBAL, self::$recognizerId, $path, 'telephony'] ); - // $this->assertStringContainsString('the weather outside is sunny',$output); $this->assertStringContainsStringIgnoringCase( 'how old is the Brooklyn Bridge', $output ); } + /** @depends testCreateRecognizer */ public function testTranscribePunctuation() { - $path = __DIR__ . '/data/audio32KHz.raw'; - $output = $this->runFunctionSnippet('transcribe_auto_punctuation', [$path]); + $path = __DIR__ . '/data/audio32KHz.flac'; + $output = $this->runFunctionSnippet('transcribe_auto_punctuation', [self::$projectId, self::GLOBAL, self::$recognizerId, $path]); $this->assertStringContainsStringIgnoringCase( 'How old is the Brooklyn Bridge', $output ); } - /** @dataProvider provideTranscribe */ + public function testTranscribeWords() + { + $recognizerId = self::$recognizerId . '-chirp3'; + $audioFile = 'gs://cloud-samples-data/speech/brooklyn_bridge.raw'; + $location = 'eu'; + + $output = $this->runFunctionSnippet('create_recognizer', [self::$projectId, $location, $recognizerId, 'chirp_3']); + $this->assertStringContainsString('Created Recognizer:', $output); + + $output = $this->runFunctionSnippet('transcribe_async_words', [self::$projectId, $location, $recognizerId, $audioFile]); + + // Check for the word time offsets + $this->assertStringContainsString('Word: How (start: ', $output); + } + + public function testTranscribeMultRegion() + { + $recognizerId = self::$recognizerId . '-eu'; + $audioFile = 'gs://cloud-samples-data/speech/brooklyn_bridge.raw'; + $location = 'eu'; + + $output = $this->runFunctionSnippet('create_recognizer', [self::$projectId, $location, $recognizerId]); + $this->assertStringContainsString('Created Recognizer:', $output); + + $output = $this->runFunctionSnippet('multi_region_gcs', [self::$projectId, $location, $recognizerId, $audioFile]); + + $this->assertStringContainsString('how old is the Brooklyn Bridge', $output); + } + + /** + * @dataProvider provideTranscribe + * + * @depends testCreateRecognizer + */ public function testTranscribe($command, $audioFile, $requireGrpc = false) { if ($requireGrpc && !extension_loaded('grpc')) { self::markTestSkipped('Must enable grpc extension.'); } - if (!self::$bucketName && '_gcs' == substr($command, -4)) { - $this->requireEnv('GOOGLE_STORAGE_BUCKET'); - } - $output = $this->runFunctionSnippet($command, [$audioFile]); - $this->assertStringContainsString('how old is the Brooklyn Bridge', $output); + $output = $this->runFunctionSnippet($command, [self::$projectId, self::GLOBAL, self::$recognizerId, $audioFile]); - // Check for the word time offsets - if (in_array($command, ['transcribe_async_words'])) { - $this->assertMatchesRegularExpression('/start: "*.*s", end: "*.*s/', $output); - } + $this->assertStringContainsString('old is the Brooklyn Bridge', $output); } public function provideTranscribe() { - self::$bucketName = getenv('GOOGLE_STORAGE_BUCKET'); return [ - ['transcribe_sync', __DIR__ . '/data/audio32KHz.raw'], - ['transcribe_sync_gcs', 'gs://' . self::$bucketName . '/speech/audio32KHz.raw'], - ['transcribe_async', __DIR__ . '/data/audio32KHz.raw'], - ['transcribe_async_gcs', 'gs://' . self::$bucketName . '/speech/audio32KHz.raw'], - ['transcribe_async_words', __DIR__ . '/data/audio32KHz.raw'], - ['profanity_filter_gcs', 'gs://' . self::$bucketName . '/speech/audio32KHz.raw'], - ['multi_region_gcs', 'gs://cloud-samples-data/speech/brooklyn_bridge.raw' ], - ['profanity_filter', __DIR__ . '/data/audio32KHz.raw'], - ['streaming_recognize', __DIR__ . '/data/audio32KHz.raw', true], + ['transcribe_sync', __DIR__ . '/data/audio32KHz.flac'], + ['transcribe_sync_gcs', 'gs://cloud-samples-data/speech/audio.raw'], + ['transcribe_async_gcs', 'gs://cloud-samples-data/speech/audio.raw'], + ['profanity_filter_gcs', 'gs://cloud-samples-data/speech/brooklyn_bridge.raw'], + ['profanity_filter', __DIR__ . '/data/audio32KHz.flac'], + ['streaming_recognize', __DIR__ . '/data/audio32KHz.flac', true], ]; } } diff --git a/storage/composer.json b/storage/composer.json index 085871e33f..d77d3e2e74 100644 --- a/storage/composer.json +++ b/storage/composer.json @@ -1,6 +1,6 @@ { "require": { - "google/cloud-storage": "^1.28.0", + "google/cloud-storage": "^1.48.7", "paragonie/random_compat": "^9.0.0" }, "require-dev": { diff --git a/storage/src/configure_retries.php b/storage/src/configure_retries.php new file mode 100644 index 0000000000..87656d8f7e --- /dev/null +++ b/storage/src/configure_retries.php @@ -0,0 +1,127 @@ + 10, + + // Exponential backoff settings + // Retry strategy to signify that we never want to retry an operation + // even if the error is retryable. + // Default: StorageClient::RETRY_IDEMPOTENT + 'retryStrategy' => StorageClient::RETRY_ALWAYS, + + // Executes a delay + // Defaults to utilizing `usleep`. + // Function signature should match: `function (int $delay) : void`. + // This function is mostly used internally, so the tests don't wait + // the time of the delay to run. + 'restDelayFunction' => function ($delay) { + usleep($delay); + }, + + // Sets the conditions for determining how long to wait between attempts to retry. + // Function signature should match: `function (int $attempt) : int`. + // Allows to change the initial retry delay, retry delay multiplier and maximum retry delay. + 'restCalcDelayFunction' => fn ($attempt) => ($attempt + 1) * 100, + + // Sets the conditions for whether or not a request should attempt to retry. + // Function signature should match: `function (\Exception $ex) : bool`. + 'restRetryFunction' => function (\Exception $e) { + // Custom logic: ex. only retry if the error code is 404. + return $e->getCode() === 404; + }, + + // Runs after the restRetryFunction. This might be used to simply consume the + // exception and $arguments b/w retries. This returns the new $arguments thus allowing + // modification on demand for $arguments. For ex: changing the headers in b/w retries. + 'restRetryListener' => function (\Exception $e, $retryAttempt, &$arguments) { + // logic + }, + ]); + $bucket = $storage->bucket($bucketName); + $operationRetriesOverrides = [ + // The maximum number of automatic retries attempted before returning + // the error. + // Default: 3 + 'retries' => 10, + + // Exponential backoff settings + // Retry strategy to signify that we never want to retry an operation + // even if the error is retryable. + // Default: StorageClient::RETRY_IDEMPOTENT + 'retryStrategy' => StorageClient::RETRY_ALWAYS, + + // Executes a delay + // Defaults to utilizing `usleep`. + // Function signature should match: `function (int $delay) : void`. + // This function is mostly used internally, so the tests don't wait + // the time of the delay to run. + 'restDelayFunction' => function ($delay) { + usleep($delay); + }, + + // Sets the conditions for determining how long to wait between attempts to retry. + // Function signature should match: `function (int $attempt) : int`. + // Allows to change the initial retry delay, retry delay multiplier and maximum retry delay. + 'restCalcDelayFunction' => fn ($attempt) => ($attempt + 1) * 100, + + // Sets the conditions for whether or not a request should attempt to retry. + // Function signature should match: `function (\Exception $ex) : bool`. + 'restRetryFunction' => function (\Exception $e) { + // Custom logic: ex. only retry if the error code is 404. + return $e->getCode() === 404; + }, + + // Runs after the restRetryFunction. This might be used to simply consume the + // exception and $arguments b/w retries. This returns the new $arguments thus allowing + // modification on demand for $arguments. For ex: changing the headers in b/w retries. + 'restRetryListener' => function (\Exception $e, $retryAttempt, &$arguments) { + // logic + }, + ]; + foreach ($bucket->objects($operationRetriesOverrides) as $object) { + printf('Object: %s' . PHP_EOL, $object->name()); + } +} +# [END storage_configure_retries] + +// 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/src/move_object_atomic.php b/storage/src/move_object_atomic.php index 059ad7d2a1..3b76cbfc80 100644 --- a/storage/src/move_object_atomic.php +++ b/storage/src/move_object_atomic.php @@ -27,7 +27,7 @@ use Google\Cloud\Storage\StorageClient; /** - * Move an object to a new name within HNS-enabled bucket. + * Move an object to a new name within bucket. * * @param string $bucketName The name of your Cloud Storage bucket. * (e.g. 'my-bucket') diff --git a/storage/test/ObjectsTest.php b/storage/test/ObjectsTest.php index 5cf9ab3f3a..f88af49e04 100644 --- a/storage/test/ObjectsTest.php +++ b/storage/test/ObjectsTest.php @@ -151,13 +151,16 @@ public function testManageObject() $this->assertEquals($output, $outputString); } - public function testMoveObjectAtomic() + /** + * @dataProvider provideMoveObject + */ + public function testMoveObjectAtomic(bool $hnEnabled) { - $bucketName = self::$bucketName . '-hns'; + $bucketName = 'move-object-bucket-' . uniqid(); $objectName = 'test-object-' . time(); $newObjectName = $objectName . '-moved'; $bucket = self::$storage->createBucket($bucketName, [ - 'hierarchicalNamespace' => ['enabled' => true], + 'hierarchicalNamespace' => ['enabled' => $hnEnabled], 'iamConfiguration' => ['uniformBucketLevelAccess' => ['enabled' => true]] ]); @@ -189,6 +192,11 @@ public function testMoveObjectAtomic() $bucket->delete(); } + public function provideMoveObject() + { + return [[true], [false]]; + } + public function testCompose() { $bucket = self::$storage->bucket(self::$bucketName); diff --git a/storagebatchoperations/composer.json b/storagebatchoperations/composer.json index e4f2639c56..de5ab2eb10 100644 --- a/storagebatchoperations/composer.json +++ b/storagebatchoperations/composer.json @@ -1,6 +1,6 @@ { "require": { - "google/cloud-storagebatchoperations": "0.1.1" + "google/cloud-storagebatchoperations": "0.2.1" }, "require-dev": { "google/cloud-storage": "^1.48.1" diff --git a/storagecontrol/composer.json b/storagecontrol/composer.json index 01218016b5..46deccbf4c 100644 --- a/storagecontrol/composer.json +++ b/storagecontrol/composer.json @@ -1,8 +1,8 @@ { "require": { - "google/cloud-storage-control": "1.3.0" + "google/cloud-storage-control": "1.6.1" }, "require-dev": { - "google/cloud-storage": "^1.41.3" + "google/cloud-storage": "^1.48.1" } } diff --git a/storagecontrol/src/create_anywhere_cache.php b/storagecontrol/src/create_anywhere_cache.php new file mode 100644 index 0000000000..9e8ac273c5 --- /dev/null +++ b/storagecontrol/src/create_anywhere_cache.php @@ -0,0 +1,77 @@ +bucketName('_', $bucketName); + + $anywhereCache = new AnywhereCache([ + 'zone' => $zone, + ]); + + $request = new CreateAnywhereCacheRequest([ + 'parent' => $formattedName, + 'anywhere_cache' => $anywhereCache, + ]); + + // Start a create operation and block until it completes. Real applications + // may want to setup a callback, wait on a coroutine, or poll until it + // completes. + $operation = $storageControlClient->createAnywhereCache($request); + + printf('Waiting for operation %s to complete...' . PHP_EOL, $operation->getName()); + $operation->pollUntilComplete([ + 'totalPollTimeoutMillis' => 5400000, + 'initialPollDelayMillis' => 1000, // Start with 1 second delay + 'pollDelayMultiplier' => 2, // Double delay each time + 'maxPollDelayMillis' => 60000, // Max 60 seconds delay between polls + ]); + + /** @var AnywhereCache $anywhereCacheResult */ + $anywhereCacheResult = $operation->getResult(); + printf('Created anywhere cache: %s' . PHP_EOL, $anywhereCacheResult->getName()); +} +# [END storage_control_create_anywhere_cache] + +// 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/storagecontrol/src/disable_anywhere_cache.php b/storagecontrol/src/disable_anywhere_cache.php new file mode 100644 index 0000000000..dbddf3c765 --- /dev/null +++ b/storagecontrol/src/disable_anywhere_cache.php @@ -0,0 +1,58 @@ +anywhereCacheName('_', $bucketName, $anywhereCacheId); + + $request = new DisableAnywhereCacheRequest([ + 'name' => $formattedName + ]); + + $response = $storageControlClient->disableAnywhereCache($request); + + printf('Disabled anywhere cache: %s', $response->getName()); +} +# [END storage_control_disable_anywhere_cache] + +// 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/storagecontrol/src/get_anywhere_cache.php b/storagecontrol/src/get_anywhere_cache.php new file mode 100644 index 0000000000..7687cf6cac --- /dev/null +++ b/storagecontrol/src/get_anywhere_cache.php @@ -0,0 +1,58 @@ +anywhereCacheName('_', $bucketName, $anywhereCacheId); + + $request = new GetAnywhereCacheRequest([ + 'name' => $formattedName, + ]); + + $response = $storageControlClient->getAnywhereCache($request); + + printf('Got anywhere cache: %s', $response->getName()); +} +# [END storage_control_get_anywhere_cache] + +// 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/storagecontrol/src/list_anywhere_caches.php b/storagecontrol/src/list_anywhere_caches.php new file mode 100644 index 0000000000..91ed6e29b0 --- /dev/null +++ b/storagecontrol/src/list_anywhere_caches.php @@ -0,0 +1,58 @@ +bucketName('_', $bucketName); + + $request = new ListAnywhereCachesRequest([ + 'parent' => $formattedName, + ]); + + $response = $storageControlClient->listAnywhereCaches($request); + + foreach ($response as $anywhereCache) { + printf('Anywhere cache name: %s' . PHP_EOL, $anywhereCache->getName()); + } +} +# [END storage_control_list_anywhere_caches] + +// 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/storagecontrol/src/pause_anywhere_cache.php b/storagecontrol/src/pause_anywhere_cache.php new file mode 100644 index 0000000000..260e7bb379 --- /dev/null +++ b/storagecontrol/src/pause_anywhere_cache.php @@ -0,0 +1,58 @@ +anywhereCacheName('_', $bucketName, $anywhereCacheId); + + $request = new PauseAnywhereCacheRequest([ + 'name' => $formattedName, + ]); + + $response = $storageControlClient->pauseAnywhereCache($request); + + printf('Paused anywhere cache: %s', $response->getName()); +} +# [END storage_control_pause_anywhere_cache] + +// 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/storagecontrol/src/resume_anywhere_cache.php b/storagecontrol/src/resume_anywhere_cache.php new file mode 100644 index 0000000000..a95dd6f92d --- /dev/null +++ b/storagecontrol/src/resume_anywhere_cache.php @@ -0,0 +1,58 @@ +anywhereCacheName('_', $bucketName, $anywhereCacheId); + + $request = new ResumeAnywhereCacheRequest([ + 'name' => $formattedName + ]); + + $response = $storageControlClient->resumeAnywhereCache($request); + + printf('Resumed anywhere cache: %s', $response->getName()); +} +# [END storage_control_resume_anywhere_cache] + +// 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/storagecontrol/src/update_anywhere_cache.php b/storagecontrol/src/update_anywhere_cache.php new file mode 100644 index 0000000000..99b262e00c --- /dev/null +++ b/storagecontrol/src/update_anywhere_cache.php @@ -0,0 +1,82 @@ +anywhereCacheName('_', $bucketName, $anywhereCacheId); + + $anywhereCache = new AnywhereCache([ + 'name' => $formattedName, + 'admission_policy' => $admission_policy, + ]); + + $updateMask = new FieldMask([ + 'paths' => ['admission_policy'], + ]); + + $request = new UpdateAnywhereCacheRequest([ + 'anywhere_cache' => $anywhereCache, + 'update_mask' => $updateMask, + ]); + + // Start an update operation. This returns an Operation object which can be polled. + $operation = $storageControlClient->updateAnywhereCache($request); + + printf('Waiting for operation %s to complete...' . PHP_EOL, $operation->getName()); + $operation->pollUntilComplete([ + 'totalPollTimeoutMillis' => 5400000, + 'initialPollDelayMillis' => 1000, // Start with 1 second delay + 'pollDelayMultiplier' => 2, // Double delay each time + 'maxPollDelayMillis' => 60000, // Max 60 seconds delay between polls + ]); + + $anywhereCacheResult = $operation->getResult(); + printf('Updated anywhere cache: %s', $anywhereCacheResult->getName()); +} +# [END storage_control_update_anywhere_cache] + +// 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/storagecontrol/test/anywhereCacheTest.php b/storagecontrol/test/anywhereCacheTest.php new file mode 100644 index 0000000000..d36f5b6134 --- /dev/null +++ b/storagecontrol/test/anywhereCacheTest.php @@ -0,0 +1,182 @@ +createBucket( + sprintf('php-gcscontrol-sample-%s', $uniqueBucketId), + [ + 'location' => self::$location, + 'hierarchicalNamespace' => ['enabled' => true], + 'iamConfiguration' => ['uniformBucketLevelAccess' => ['enabled' => true]] + ] + ); + self::$anywhereCacheName = self::$storageControlClient->anywhereCacheName( + '_', // Set project to "_" to signify global bucket + self::$sourceBucket->name(), + self::$cacheId + ); + } + + public static function tearDownAfterClass(): void + { + foreach (self::$sourceBucket->objects(['versions' => true]) as $object) { + $object->delete(); + } + self::$sourceBucket->delete(); + } + + public function testCreateAnywhereCache() + { + $output = $this->runFunctionSnippet('create_anywhere_cache', [ + self::$sourceBucket->name(), + self::$zone, + ]); + + $this->assertStringContainsString( + sprintf('Created anywhere cache: %s', self::$anywhereCacheName), + $output + ); + } + + /** + * @depends testCreateAnywhereCache + */ + public function testGetAnywhereCache() + { + $output = $this->runFunctionSnippet('get_anywhere_cache', [ + self::$sourceBucket->name(), + self::$cacheId, + ]); + + $this->assertStringContainsString( + sprintf('Got anywhere cache: %s', self::$anywhereCacheName), + $output + ); + } + + /** + * @depends testGetAnywhereCache + */ + public function testListAnywhereCaches() + { + $output = $this->runFunctionSnippet('list_anywhere_caches', [ + self::$sourceBucket->name(), + ]); + + $this->assertStringContainsString( + sprintf('Anywhere cache name: %s', self::$anywhereCacheName), + $output + ); + } + + /** + * @depends testListAnywhereCaches + */ + public function testPauseAnywhereCache() + { + $output = $this->runFunctionSnippet('pause_anywhere_cache', [ + self::$sourceBucket->name(), + self::$cacheId, + ]); + + $this->assertStringContainsString( + sprintf('Paused anywhere cache: %s', self::$anywhereCacheName), + $output + ); + } + + /** + * @depends testPauseAnywhereCache + */ + public function testResumeAnywhereCache() + { + $output = $this->runFunctionSnippet('resume_anywhere_cache', [ + self::$sourceBucket->name(), + self::$cacheId, + ]); + + $this->assertStringContainsString( + sprintf('Resumed anywhere cache: %s', self::$anywhereCacheName), + $output + ); + } + + /** + * @depends testResumeAnywhereCache + */ + public function testUpdateAnywhereCache() + { + $admission_policy = 'admit-on-second-miss'; + $output = $this->runFunctionSnippet('update_anywhere_cache', [ + self::$sourceBucket->name(), + self::$cacheId, + $admission_policy + ]); + + $this->assertStringContainsString( + sprintf('Updated anywhere cache: %s', self::$anywhereCacheName), + $output + ); + } + + /** + * @depends testUpdateAnywhereCache + */ + public function testDisableAnywhereCache() + { + $output = $this->runFunctionSnippet('disable_anywhere_cache', [ + self::$sourceBucket->name(), + self::$cacheId, + ]); + + $this->assertStringContainsString( + sprintf('Disabled anywhere cache: %s', self::$anywhereCacheName), + $output + ); + } +} diff --git a/vision/composer.json b/vision/composer.json index 5d79fa2baf..258acb585e 100644 --- a/vision/composer.json +++ b/vision/composer.json @@ -2,7 +2,7 @@ "name": "google/vision", "type": "project", "require": { - "google/cloud-vision": "^1.0.0", + "google/cloud-vision": "^1.7", "google/cloud-storage": "^1.20.1" } } diff --git a/vision/quickstart.php b/vision/quickstart.php index 4a0a387fda..c9cffa0bde 100644 --- a/vision/quickstart.php +++ b/vision/quickstart.php @@ -20,7 +20,7 @@ require __DIR__ . '/vendor/autoload.php'; # imports the Google Cloud client library -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; # instantiates a client $imageAnnotator = new ImageAnnotatorClient(); diff --git a/vision/src/detect_document_text.php b/vision/src/detect_document_text.php index e6f9e51c14..bf4af162ad 100644 --- a/vision/src/detect_document_text.php +++ b/vision/src/detect_document_text.php @@ -18,7 +18,7 @@ // [START vision_fulltext_detection] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path Path to the image, e.g. "path/to/your/image.jpg" diff --git a/vision/src/detect_document_text_gcs.php b/vision/src/detect_document_text_gcs.php index 6406819f87..10e8ae188e 100644 --- a/vision/src/detect_document_text_gcs.php +++ b/vision/src/detect_document_text_gcs.php @@ -18,7 +18,7 @@ // [START vision_fulltext_detection_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_face.php b/vision/src/detect_face.php index a423f484d5..9d6307febf 100644 --- a/vision/src/detect_face.php +++ b/vision/src/detect_face.php @@ -18,7 +18,7 @@ namespace Google\Cloud\Samples\Vision; // [START vision_face_detection_tutorial_imports] -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; // [END vision_face_detection_tutorial_imports] /** diff --git a/vision/src/detect_face_gcs.php b/vision/src/detect_face_gcs.php index 0dfde0d3d6..d6377d3cd3 100644 --- a/vision/src/detect_face_gcs.php +++ b/vision/src/detect_face_gcs.php @@ -18,7 +18,7 @@ // [START vision_face_detection_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_image_property.php b/vision/src/detect_image_property.php index d21f9dd0cc..48eed63aa8 100644 --- a/vision/src/detect_image_property.php +++ b/vision/src/detect_image_property.php @@ -18,7 +18,7 @@ // [START vision_image_property_detection] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path Path to the image, e.g. "path/to/your/image.jpg" diff --git a/vision/src/detect_image_property_gcs.php b/vision/src/detect_image_property_gcs.php index 9f67ae1ace..b7a79d8a6a 100644 --- a/vision/src/detect_image_property_gcs.php +++ b/vision/src/detect_image_property_gcs.php @@ -18,7 +18,7 @@ // [START vision_image_property_detection_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_label.php b/vision/src/detect_label.php index f88c2f8ae1..217171d5cb 100644 --- a/vision/src/detect_label.php +++ b/vision/src/detect_label.php @@ -18,7 +18,7 @@ // [START vision_label_detection] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path Path to the image, e.g. "path/to/your/image.jpg" diff --git a/vision/src/detect_label_gcs.php b/vision/src/detect_label_gcs.php index ad56abe81b..c03711a65c 100644 --- a/vision/src/detect_label_gcs.php +++ b/vision/src/detect_label_gcs.php @@ -18,7 +18,7 @@ // [START vision_label_detection_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_landmark.php b/vision/src/detect_landmark.php index 66011af5fb..b31813bd8a 100644 --- a/vision/src/detect_landmark.php +++ b/vision/src/detect_landmark.php @@ -18,7 +18,7 @@ // [START vision_landmark_detection] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path Path to the image, e.g. "path/to/your/image.jpg" diff --git a/vision/src/detect_landmark_gcs.php b/vision/src/detect_landmark_gcs.php index d7fb9d2112..60c1ae6562 100644 --- a/vision/src/detect_landmark_gcs.php +++ b/vision/src/detect_landmark_gcs.php @@ -18,7 +18,7 @@ // [START vision_landmark_detection_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_logo.php b/vision/src/detect_logo.php index 6c629bb7f3..eb3eeb4d64 100644 --- a/vision/src/detect_logo.php +++ b/vision/src/detect_logo.php @@ -18,7 +18,7 @@ // [START vision_logo_detection] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path Path to the image, e.g. "path/to/your/image.jpg" diff --git a/vision/src/detect_logo_gcs.php b/vision/src/detect_logo_gcs.php index fd9d53b7ce..9c89d409d4 100644 --- a/vision/src/detect_logo_gcs.php +++ b/vision/src/detect_logo_gcs.php @@ -18,7 +18,7 @@ // [START vision_logo_detection_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_object.php b/vision/src/detect_object.php index 081ea52a7b..77aa0c8f9d 100644 --- a/vision/src/detect_object.php +++ b/vision/src/detect_object.php @@ -18,7 +18,7 @@ // [START vision_localize_objects] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path Path to the image, e.g. "path/to/your/image.jpg" diff --git a/vision/src/detect_object_gcs.php b/vision/src/detect_object_gcs.php index 91cd2dd1db..389116b218 100644 --- a/vision/src/detect_object_gcs.php +++ b/vision/src/detect_object_gcs.php @@ -18,7 +18,7 @@ // [START vision_localize_objects_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_pdf_gcs.php b/vision/src/detect_pdf_gcs.php index a0d73f1118..b97a62a622 100644 --- a/vision/src/detect_pdf_gcs.php +++ b/vision/src/detect_pdf_gcs.php @@ -21,11 +21,12 @@ use Google\Cloud\Storage\StorageClient; use Google\Cloud\Vision\V1\AnnotateFileResponse; use Google\Cloud\Vision\V1\AsyncAnnotateFileRequest; +use Google\Cloud\Vision\V1\AsyncBatchAnnotateFilesRequest; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; use Google\Cloud\Vision\V1\Feature; use Google\Cloud\Vision\V1\Feature\Type; use Google\Cloud\Vision\V1\GcsDestination; use Google\Cloud\Vision\V1\GcsSource; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; use Google\Cloud\Vision\V1\InputConfig; use Google\Cloud\Vision\V1\OutputConfig; @@ -66,7 +67,9 @@ function detect_pdf_gcs(string $path, string $output) # make request $imageAnnotator = new ImageAnnotatorClient(); - $operation = $imageAnnotator->asyncBatchAnnotateFiles($requests); + $request = (new AsyncBatchAnnotateFilesRequest()) + ->setRequests($requests); + $operation = $imageAnnotator->asyncBatchAnnotateFiles($request); print('Waiting for operation to finish.' . PHP_EOL); $operation->pollUntilComplete(); diff --git a/vision/src/detect_safe_search.php b/vision/src/detect_safe_search.php index 1275329e0b..da8fefbf8e 100644 --- a/vision/src/detect_safe_search.php +++ b/vision/src/detect_safe_search.php @@ -18,7 +18,7 @@ // [START vision_safe_search_detection] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path Path to the image, e.g. "path/to/your/image.jpg" diff --git a/vision/src/detect_safe_search_gcs.php b/vision/src/detect_safe_search_gcs.php index 1390be46af..89379453a4 100644 --- a/vision/src/detect_safe_search_gcs.php +++ b/vision/src/detect_safe_search_gcs.php @@ -18,7 +18,7 @@ // [START vision_safe_search_detection_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_text.php b/vision/src/detect_text.php index 0bf10d6df0..133c068670 100644 --- a/vision/src/detect_text.php +++ b/vision/src/detect_text.php @@ -18,7 +18,7 @@ // [START vision_text_detection] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path Path to the image, e.g. "path/to/your/image.jpg" diff --git a/vision/src/detect_text_gcs.php b/vision/src/detect_text_gcs.php index ef9b548c23..d281e08dd4 100644 --- a/vision/src/detect_text_gcs.php +++ b/vision/src/detect_text_gcs.php @@ -18,7 +18,7 @@ // [START vision_text_detection_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_web.php b/vision/src/detect_web.php index a071ec2970..7ad7ece823 100644 --- a/vision/src/detect_web.php +++ b/vision/src/detect_web.php @@ -18,7 +18,7 @@ // [START vision_web_detection] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path Path to the image, e.g. "path/to/your/image.jpg" diff --git a/vision/src/detect_web_gcs.php b/vision/src/detect_web_gcs.php index 330ac95f00..d3c6256946 100644 --- a/vision/src/detect_web_gcs.php +++ b/vision/src/detect_web_gcs.php @@ -18,7 +18,7 @@ // [START vision_web_detection_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; /** * @param string $path GCS path to the image, e.g. "gs://path/to/your/image.jpg" diff --git a/vision/src/detect_web_with_geo_metadata.php b/vision/src/detect_web_with_geo_metadata.php index 019887942b..7b8cf0e29a 100644 --- a/vision/src/detect_web_with_geo_metadata.php +++ b/vision/src/detect_web_with_geo_metadata.php @@ -18,7 +18,7 @@ // [START vision_web_detection_include_geo] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; use Google\Cloud\Vision\V1\ImageContext; use Google\Cloud\Vision\V1\WebDetectionParams; diff --git a/vision/src/detect_web_with_geo_metadata_gcs.php b/vision/src/detect_web_with_geo_metadata_gcs.php index 8a0cc0d594..c50f9e9ca8 100644 --- a/vision/src/detect_web_with_geo_metadata_gcs.php +++ b/vision/src/detect_web_with_geo_metadata_gcs.php @@ -18,7 +18,7 @@ // [START vision_web_detection_include_geo_gcs] namespace Google\Cloud\Samples\Vision; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; +use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient; use Google\Cloud\Vision\V1\ImageContext; use Google\Cloud\Vision\V1\WebDetectionParams;