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
NJEm}Vx^-|{0+<~!(@FpU
From f9c729597d5b77b05aaefd8ea1b77cee575bd801 Mon Sep 17 00:00:00 2001
From: Mend Renovate
Date: Thu, 27 Jul 2023 20:08:53 +0200
Subject: [PATCH 055/285] fix(deps): update dependency google/cloud-document-ai
to v2 (#1890)
---
documentai/composer.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/documentai/composer.json b/documentai/composer.json
index 326aafb6aa..062bbdc8ad 100644
--- a/documentai/composer.json
+++ b/documentai/composer.json
@@ -1,5 +1,5 @@
{
"require": {
- "google/cloud-document-ai": "^1.0.1"
+ "google/cloud-document-ai": "^2.0.0"
}
}
From 228d11906597506405a56fb2ef0fa117d64e9845 Mon Sep 17 00:00:00 2001
From: Brent Shaffer
Date: Thu, 27 Jul 2023 11:24:57 -0700
Subject: [PATCH 056/285] Revert "fix(deps): update dependency
google/cloud-document-ai to v2 (#1890)"
This reverts commit f9c729597d5b77b05aaefd8ea1b77cee575bd801.
---
documentai/composer.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/documentai/composer.json b/documentai/composer.json
index 062bbdc8ad..326aafb6aa 100644
--- a/documentai/composer.json
+++ b/documentai/composer.json
@@ -1,5 +1,5 @@
{
"require": {
- "google/cloud-document-ai": "^2.0.0"
+ "google/cloud-document-ai": "^1.0.1"
}
}
From 18c687234b2c72b57ea7503fb4806df701308e26 Mon Sep 17 00:00:00 2001
From: Brent Shaffer
Date: Mon, 31 Jul 2023 00:36:38 -0600
Subject: [PATCH 057/285] chore: upgrade texttospeech samples to new surface
(#1880)
---
texttospeech/composer.json | 2 +-
texttospeech/quickstart.php | 9 +++++++--
texttospeech/src/list_voices.php | 6 ++++--
texttospeech/src/synthesize_ssml.php | 9 +++++++--
texttospeech/src/synthesize_ssml_file.php | 9 +++++++--
texttospeech/src/synthesize_text.php | 9 +++++++--
texttospeech/src/synthesize_text_effects_profile.php | 9 +++++++--
.../src/synthesize_text_effects_profile_file.php | 9 +++++++--
texttospeech/src/synthesize_text_file.php | 9 +++++++--
9 files changed, 54 insertions(+), 17 deletions(-)
diff --git a/texttospeech/composer.json b/texttospeech/composer.json
index bac8f0cb0b..18aec934ff 100644
--- a/texttospeech/composer.json
+++ b/texttospeech/composer.json
@@ -1,5 +1,5 @@
{
"require": {
- "google/cloud-text-to-speech": "^1.0.0"
+ "google/cloud-text-to-speech": "^1.7"
}
}
diff --git a/texttospeech/quickstart.php b/texttospeech/quickstart.php
index cc9b75cb5e..375781b657 100644
--- a/texttospeech/quickstart.php
+++ b/texttospeech/quickstart.php
@@ -22,9 +22,10 @@
// Imports the Cloud Client Library
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
+use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
+use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
// instantiates a client
@@ -50,7 +51,11 @@
// perform text-to-speech request on the text input with selected voice
// parameters and audio file type
-$response = $client->synthesizeSpeech($synthesisInputText, $voice, $audioConfig);
+$request = (new SynthesizeSpeechRequest())
+ ->setInput($synthesisInputText)
+ ->setVoice($voice)
+ ->setAudioConfig($audioConfig);
+$response = $client->synthesizeSpeech($request);
$audioContent = $response->getAudioContent();
// the response's audioContent is binary
diff --git a/texttospeech/src/list_voices.php b/texttospeech/src/list_voices.php
index 8f2f014ecd..9fdc773bac 100644
--- a/texttospeech/src/list_voices.php
+++ b/texttospeech/src/list_voices.php
@@ -24,7 +24,8 @@
namespace Google\Cloud\Samples\TextToSpeech;
// [START tts_list_voices]
-use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
+use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
+use Google\Cloud\TextToSpeech\V1\ListVoicesRequest;
function list_voices(): void
{
@@ -32,7 +33,8 @@ function list_voices(): void
$client = new TextToSpeechClient();
// perform list voices request
- $response = $client->listVoices();
+ $request = (new ListVoicesRequest());
+ $response = $client->listVoices($request);
$voices = $response->getVoices();
foreach ($voices as $voice) {
diff --git a/texttospeech/src/synthesize_ssml.php b/texttospeech/src/synthesize_ssml.php
index 7a0fe4469f..2b58b786f4 100644
--- a/texttospeech/src/synthesize_ssml.php
+++ b/texttospeech/src/synthesize_ssml.php
@@ -26,9 +26,10 @@
// [START tts_synthesize_ssml]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
+use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
+use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -50,8 +51,12 @@ function synthesize_ssml(string $ssml): void
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3);
+ $request = (new SynthesizeSpeechRequest())
+ ->setInput($input_text)
+ ->setVoice($voice)
+ ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
+ $response = $client->synthesizeSpeech($request);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_ssml_file.php b/texttospeech/src/synthesize_ssml_file.php
index 7ccd1e1290..0682429963 100644
--- a/texttospeech/src/synthesize_ssml_file.php
+++ b/texttospeech/src/synthesize_ssml_file.php
@@ -26,9 +26,10 @@
// [START tts_synthesize_ssml_file]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
+use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
+use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -52,8 +53,12 @@ function synthesize_ssml_file(string $path): void
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3);
+ $request = (new SynthesizeSpeechRequest())
+ ->setInput($input_text)
+ ->setVoice($voice)
+ ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
+ $response = $client->synthesizeSpeech($request);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_text.php b/texttospeech/src/synthesize_text.php
index ff441cf9f2..be27fdaf79 100644
--- a/texttospeech/src/synthesize_text.php
+++ b/texttospeech/src/synthesize_text.php
@@ -26,9 +26,10 @@
// [START tts_synthesize_text]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
+use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
+use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -50,8 +51,12 @@ function synthesize_text(string $text): void
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3);
+ $request = (new SynthesizeSpeechRequest())
+ ->setInput($input_text)
+ ->setVoice($voice)
+ ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
+ $response = $client->synthesizeSpeech($request);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_text_effects_profile.php b/texttospeech/src/synthesize_text_effects_profile.php
index 14acbf554c..2517961289 100644
--- a/texttospeech/src/synthesize_text_effects_profile.php
+++ b/texttospeech/src/synthesize_text_effects_profile.php
@@ -26,9 +26,10 @@
// [START tts_synthesize_text_audio_profile]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
+use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
+use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -53,8 +54,12 @@ function synthesize_text_effects_profile(string $text, string $effectsProfileId)
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3)
->setEffectsProfileId(array($effectsProfileId));
+ $request = (new SynthesizeSpeechRequest())
+ ->setInput($inputText)
+ ->setVoice($voice)
+ ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($inputText, $voice, $audioConfig);
+ $response = $client->synthesizeSpeech($request);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_text_effects_profile_file.php b/texttospeech/src/synthesize_text_effects_profile_file.php
index 80fe8033eb..a437bcd4bd 100644
--- a/texttospeech/src/synthesize_text_effects_profile_file.php
+++ b/texttospeech/src/synthesize_text_effects_profile_file.php
@@ -26,9 +26,10 @@
// [START tts_synthesize_text_audio_profile_file]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
+use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
+use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -54,8 +55,12 @@ function synthesize_text_effects_profile_file(string $path, string $effectsProfi
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3)
->setEffectsProfileId(array($effectsProfileId));
+ $request = (new SynthesizeSpeechRequest())
+ ->setInput($inputText)
+ ->setVoice($voice)
+ ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($inputText, $voice, $audioConfig);
+ $response = $client->synthesizeSpeech($request);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_text_file.php b/texttospeech/src/synthesize_text_file.php
index db7067f254..91df4bae23 100644
--- a/texttospeech/src/synthesize_text_file.php
+++ b/texttospeech/src/synthesize_text_file.php
@@ -26,9 +26,10 @@
// [START tts_synthesize_text_file]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
+use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
+use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -52,8 +53,12 @@ function synthesize_text_file(string $path): void
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3);
+ $request = (new SynthesizeSpeechRequest())
+ ->setInput($input_text)
+ ->setVoice($voice)
+ ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
+ $response = $client->synthesizeSpeech($request);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
From fa6f3a4cb7238a7ae00a32be5b18efd9ec9fd0de Mon Sep 17 00:00:00 2001
From: Yash Sahu <54198301+yash30201@users.noreply.github.com>
Date: Mon, 31 Jul 2023 12:15:34 +0530
Subject: [PATCH 058/285] Revert "chore: upgrade texttospeech samples to new
surface (#1880)" (#1902)
This reverts commit 18c687234b2c72b57ea7503fb4806df701308e26.
---
texttospeech/composer.json | 2 +-
texttospeech/quickstart.php | 9 ++-------
texttospeech/src/list_voices.php | 6 ++----
texttospeech/src/synthesize_ssml.php | 9 ++-------
texttospeech/src/synthesize_ssml_file.php | 9 ++-------
texttospeech/src/synthesize_text.php | 9 ++-------
texttospeech/src/synthesize_text_effects_profile.php | 9 ++-------
.../src/synthesize_text_effects_profile_file.php | 9 ++-------
texttospeech/src/synthesize_text_file.php | 9 ++-------
9 files changed, 17 insertions(+), 54 deletions(-)
diff --git a/texttospeech/composer.json b/texttospeech/composer.json
index 18aec934ff..bac8f0cb0b 100644
--- a/texttospeech/composer.json
+++ b/texttospeech/composer.json
@@ -1,5 +1,5 @@
{
"require": {
- "google/cloud-text-to-speech": "^1.7"
+ "google/cloud-text-to-speech": "^1.0.0"
}
}
diff --git a/texttospeech/quickstart.php b/texttospeech/quickstart.php
index 375781b657..cc9b75cb5e 100644
--- a/texttospeech/quickstart.php
+++ b/texttospeech/quickstart.php
@@ -22,10 +22,9 @@
// Imports the Cloud Client Library
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
-use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
+use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
// instantiates a client
@@ -51,11 +50,7 @@
// perform text-to-speech request on the text input with selected voice
// parameters and audio file type
-$request = (new SynthesizeSpeechRequest())
- ->setInput($synthesisInputText)
- ->setVoice($voice)
- ->setAudioConfig($audioConfig);
-$response = $client->synthesizeSpeech($request);
+$response = $client->synthesizeSpeech($synthesisInputText, $voice, $audioConfig);
$audioContent = $response->getAudioContent();
// the response's audioContent is binary
diff --git a/texttospeech/src/list_voices.php b/texttospeech/src/list_voices.php
index 9fdc773bac..8f2f014ecd 100644
--- a/texttospeech/src/list_voices.php
+++ b/texttospeech/src/list_voices.php
@@ -24,8 +24,7 @@
namespace Google\Cloud\Samples\TextToSpeech;
// [START tts_list_voices]
-use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
-use Google\Cloud\TextToSpeech\V1\ListVoicesRequest;
+use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
function list_voices(): void
{
@@ -33,8 +32,7 @@ function list_voices(): void
$client = new TextToSpeechClient();
// perform list voices request
- $request = (new ListVoicesRequest());
- $response = $client->listVoices($request);
+ $response = $client->listVoices();
$voices = $response->getVoices();
foreach ($voices as $voice) {
diff --git a/texttospeech/src/synthesize_ssml.php b/texttospeech/src/synthesize_ssml.php
index 2b58b786f4..7a0fe4469f 100644
--- a/texttospeech/src/synthesize_ssml.php
+++ b/texttospeech/src/synthesize_ssml.php
@@ -26,10 +26,9 @@
// [START tts_synthesize_ssml]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
-use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
+use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -51,12 +50,8 @@ function synthesize_ssml(string $ssml): void
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3);
- $request = (new SynthesizeSpeechRequest())
- ->setInput($input_text)
- ->setVoice($voice)
- ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($request);
+ $response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_ssml_file.php b/texttospeech/src/synthesize_ssml_file.php
index 0682429963..7ccd1e1290 100644
--- a/texttospeech/src/synthesize_ssml_file.php
+++ b/texttospeech/src/synthesize_ssml_file.php
@@ -26,10 +26,9 @@
// [START tts_synthesize_ssml_file]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
-use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
+use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -53,12 +52,8 @@ function synthesize_ssml_file(string $path): void
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3);
- $request = (new SynthesizeSpeechRequest())
- ->setInput($input_text)
- ->setVoice($voice)
- ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($request);
+ $response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_text.php b/texttospeech/src/synthesize_text.php
index be27fdaf79..ff441cf9f2 100644
--- a/texttospeech/src/synthesize_text.php
+++ b/texttospeech/src/synthesize_text.php
@@ -26,10 +26,9 @@
// [START tts_synthesize_text]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
-use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
+use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -51,12 +50,8 @@ function synthesize_text(string $text): void
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3);
- $request = (new SynthesizeSpeechRequest())
- ->setInput($input_text)
- ->setVoice($voice)
- ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($request);
+ $response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_text_effects_profile.php b/texttospeech/src/synthesize_text_effects_profile.php
index 2517961289..14acbf554c 100644
--- a/texttospeech/src/synthesize_text_effects_profile.php
+++ b/texttospeech/src/synthesize_text_effects_profile.php
@@ -26,10 +26,9 @@
// [START tts_synthesize_text_audio_profile]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
-use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
+use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -54,12 +53,8 @@ function synthesize_text_effects_profile(string $text, string $effectsProfileId)
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3)
->setEffectsProfileId(array($effectsProfileId));
- $request = (new SynthesizeSpeechRequest())
- ->setInput($inputText)
- ->setVoice($voice)
- ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($request);
+ $response = $client->synthesizeSpeech($inputText, $voice, $audioConfig);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_text_effects_profile_file.php b/texttospeech/src/synthesize_text_effects_profile_file.php
index a437bcd4bd..80fe8033eb 100644
--- a/texttospeech/src/synthesize_text_effects_profile_file.php
+++ b/texttospeech/src/synthesize_text_effects_profile_file.php
@@ -26,10 +26,9 @@
// [START tts_synthesize_text_audio_profile_file]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
-use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
+use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -55,12 +54,8 @@ function synthesize_text_effects_profile_file(string $path, string $effectsProfi
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3)
->setEffectsProfileId(array($effectsProfileId));
- $request = (new SynthesizeSpeechRequest())
- ->setInput($inputText)
- ->setVoice($voice)
- ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($request);
+ $response = $client->synthesizeSpeech($inputText, $voice, $audioConfig);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
diff --git a/texttospeech/src/synthesize_text_file.php b/texttospeech/src/synthesize_text_file.php
index 91df4bae23..db7067f254 100644
--- a/texttospeech/src/synthesize_text_file.php
+++ b/texttospeech/src/synthesize_text_file.php
@@ -26,10 +26,9 @@
// [START tts_synthesize_text_file]
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
-use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
-use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
+use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
/**
@@ -53,12 +52,8 @@ function synthesize_text_file(string $path): void
$audioConfig = (new AudioConfig())
->setAudioEncoding(AudioEncoding::MP3);
- $request = (new SynthesizeSpeechRequest())
- ->setInput($input_text)
- ->setVoice($voice)
- ->setAudioConfig($audioConfig);
- $response = $client->synthesizeSpeech($request);
+ $response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
$audioContent = $response->getAudioContent();
file_put_contents('output.mp3', $audioContent);
From e1c6ba4efebac487dc2570afed8e5476faeca479 Mon Sep 17 00:00:00 2001
From: minherz
Date: Tue, 1 Aug 2023 23:08:44 +0000
Subject: [PATCH 059/285] chore: retire IoT samples (#1905)
* chore: deprecate IoT samples
modify README with up to date deprecation message
remove sample tests
---
CODEOWNERS | 32 +++++++++----
iot/README.md | 48 ++-----------------
...t.xml.dist => phpunit.xml.dist.deprecated} | 0
.../{iotTest.php => iotTest.php.deprecated} | 0
4 files changed, 27 insertions(+), 53 deletions(-)
rename iot/{phpunit.xml.dist => phpunit.xml.dist.deprecated} (100%)
rename iot/test/{iotTest.php => iotTest.php.deprecated} (100%)
diff --git a/CODEOWNERS b/CODEOWNERS
index 879d0daddc..45d901e1f8 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -1,38 +1,47 @@
-# Code owners file.
-# This file controls who is tagged for review for any given pull request.
+# Code owners file
+
+# This file controls who is tagged for review for any given pull request
+
#
-# For syntax help see:
-# https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax
+# For syntax help see
+
+#
# The php-admins team is the default owner for anything not
-# explicitly taken by someone else.
-* @GoogleCloudPlatform/php-samples-reviewers
+
+# explicitly taken by someone else
+
+* @GoogleCloudPlatform/php-samples-reviewers
# Kokoro
+
.kokoro @GoogleCloudPlatform/php-admins
/bigtable/**/*.php @GoogleCloudPlatform/cloud-native-db-dpes @GoogleCloudPlatform/php-samples-reviewers
/cloud_sql/**/*.php @GoogleCloudPlatform/infra-db-dpes @GoogleCloudPlatform/php-samples-reviewers
/datastore/**/*.php @GoogleCloudPlatform/cloud-native-db-dpes @GoogleCloudPlatform/php-samples-reviewers
/firestore/**/*.php @GoogleCloudPlatform/cloud-native-db-dpes @GoogleCloudPlatform/php-samples-reviewers
-/iot/ @GoogleCloudPlatform/api-iot @GoogleCloudPlatform/php-samples-reviewers
/storage/ @GoogleCloudPlatform/cloud-storage-dpe @GoogleCloudPlatform/php-samples-reviewers
/spanner/ @GoogleCloudPlatform/api-spanner @GoogleCloudPlatform/php-samples-reviewers
# Serverless, Orchestration, DevOps
+
/appengine/ @GoogleCloudPlatform/torus-dpe @GoogleCloudPlatform/php-samples-reviewers
-/functions/ @GoogleCloudPlatform/torus-dpe @GoogleCloudPlatform/php-samples-reviewers
+/functions/ @GoogleCloudPlatform/torus-dpe @GoogleCloudPlatform/php-samples-reviewers
/run/ @GoogleCloudPlatform/torus-dpe @GoogleCloudPlatform/php-samples-reviewers
/eventarc/ @GoogleCloudPlatform/torus-dpe @GoogleCloudPlatform/php-samples-reviewers
# Functions samples owned by the Firebase team
-/functions/firebase_analytics @schandel
+
+/functions/firebase_analytics @schandel
# DLP samples owned by DLP team
+
/dlp/ @GoogleCloudPlatform/googleapis-dlp
# Brent is taking ownership of these samples as they are not supported by the ML team
+
/dialogflow/ @bshaffer
/language/ @bshaffer
/speech/ @bshaffer
@@ -42,4 +51,9 @@
/video/ @bshaffer
# Compute samples owned by Remik
+
/compute/cloud-client/ @rsamborski
+
+# Deprecated
+
+/iot/ @GoogleCloudPlatform/php-samples-reviewers
diff --git a/iot/README.md b/iot/README.md
index 00ef94dedc..cb74ef1206 100644
--- a/iot/README.md
+++ b/iot/README.md
@@ -1,47 +1,7 @@
-# Google IOT PHP Sample Application
+# Deprecation Notice
-[![Open in Cloud Shell][shell_img]][shell_link]
+*
-[shell_img]: http://gstatic.com/cloudssh/images/open-btn.svg
-[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googlecloudplatform/php-docs-samples&page=editor&working_dir=iot
+* Hence, the samples in this directory are archived and are no longer maintained.
-## Description
-
-This simple command-line application demonstrates how to invoke Google
-IOT API from PHP. These samples are best seen in the context of the
-[Official API Documentation](https://cloud.google.com/iot/docs).
-
-## Build and Run
-1. **Enable APIs** - [Enable the IOT API](
- https://console.cloud.google.com/flows/enableapi?apiid=iot.googleapis.com)
- and create a new project or select an existing project.
-2. **Download The Credentials** - Click "Go to credentials" after enabling the APIs. Click
- "New Credentials"
- and select "Service Account Key". Create a new service account, use the JSON key type, and
- select "Create". Once downloaded, set the environment variable `GOOGLE_APPLICATION_CREDENTIALS`
- to the path of the JSON key that was downloaded.
-3. **Clone the repo** and cd into this directory
-```
- $ git clone https://github.com/GoogleCloudPlatform/php-docs-samples
- $ cd php-docs-samples/iot
-```
-4. **Install dependencies** via [Composer](http://getcomposer.org/doc/00-intro.md).
- Run `php composer.phar install` (if composer is installed locally) or `composer install`
- (if composer is installed globally).
-5. To run the IOT Samples, run any of the files in `src/` on the CLI. Run them without arguments to print usage instructions:
-```
-$ php src/list_registries.php
-
-Usage: list_registries.php $projectId [$location='us-central1']
-
- @param string $projectId Google Cloud project ID
- @param string $location (Optional) Google Cloud region
-```
-
-## Contributing changes
-
-* See [CONTRIBUTING.md](../CONTRIBUTING.md)
-
-## Licensing
-
-* See [LICENSE](../LICENSE)
+* If you are customer with an assigned Google Cloud account team, contact your account team for more information.
diff --git a/iot/phpunit.xml.dist b/iot/phpunit.xml.dist.deprecated
similarity index 100%
rename from iot/phpunit.xml.dist
rename to iot/phpunit.xml.dist.deprecated
diff --git a/iot/test/iotTest.php b/iot/test/iotTest.php.deprecated
similarity index 100%
rename from iot/test/iotTest.php
rename to iot/test/iotTest.php.deprecated
From c5b6ce2b2f820551fdad706dbe3f7e6f7a868a35 Mon Sep 17 00:00:00 2001
From: Ajumal
Date: Wed, 2 Aug 2023 16:06:57 +0530
Subject: [PATCH 060/285] feat(Spanner): Add bit reversed sequence samples
(#1836)
---
spanner/src/alter_sequence.php | 85 +++++++++++++++++++++++++++++
spanner/src/create_sequence.php | 88 ++++++++++++++++++++++++++++++
spanner/src/drop_sequence.php | 65 ++++++++++++++++++++++
spanner/src/pg_alter_sequence.php | 85 +++++++++++++++++++++++++++++
spanner/src/pg_create_sequence.php | 88 ++++++++++++++++++++++++++++++
spanner/src/pg_drop_sequence.php | 65 ++++++++++++++++++++++
spanner/test/spannerPgTest.php | 40 ++++++++++++++
spanner/test/spannerTest.php | 40 ++++++++++++++
8 files changed, 556 insertions(+)
create mode 100644 spanner/src/alter_sequence.php
create mode 100644 spanner/src/create_sequence.php
create mode 100644 spanner/src/drop_sequence.php
create mode 100644 spanner/src/pg_alter_sequence.php
create mode 100644 spanner/src/pg_create_sequence.php
create mode 100644 spanner/src/pg_drop_sequence.php
diff --git a/spanner/src/alter_sequence.php b/spanner/src/alter_sequence.php
new file mode 100644
index 0000000000..05ea5bd84b
--- /dev/null
+++ b/spanner/src/alter_sequence.php
@@ -0,0 +1,85 @@
+instance($instanceId);
+ $database = $instance->database($databaseId);
+ $transaction = $database->transaction();
+
+ $operation = $database->updateDdl(
+ 'ALTER SEQUENCE Seq SET OPTIONS (skip_range_min = 1000, skip_range_max = 5000000)'
+ );
+
+ print('Waiting for operation to complete...' . PHP_EOL);
+ $operation->pollUntilComplete();
+
+ printf(
+ 'Altered Seq sequence to skip an inclusive range between 1000 and 5000000' .
+ PHP_EOL
+ );
+
+ $res = $transaction->execute(
+ 'INSERT INTO Customers (CustomerName) VALUES ' .
+ "('Lea'), ('Catalina'), ('Smith') THEN RETURN CustomerId"
+ );
+ $rows = $res->rows(Result::RETURN_ASSOCIATIVE);
+
+ foreach ($rows as $row) {
+ printf('Inserted customer record with CustomerId: %d %s',
+ $row['CustomerId'],
+ PHP_EOL
+ );
+ }
+ $transaction->commit();
+
+ printf(sprintf(
+ 'Number of customer records inserted is: %d %s',
+ $res->stats()['rowCountExact'],
+ PHP_EOL
+ ));
+}
+// [END spanner_alter_sequence]
+
+// 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/spanner/src/create_sequence.php b/spanner/src/create_sequence.php
new file mode 100644
index 0000000000..f4ff6d0cd0
--- /dev/null
+++ b/spanner/src/create_sequence.php
@@ -0,0 +1,88 @@
+instance($instanceId);
+ $database = $instance->database($databaseId);
+ $transaction = $database->transaction();
+
+ $operation = $database->updateDdlBatch([
+ "CREATE SEQUENCE Seq OPTIONS (sequence_kind = 'bit_reversed_positive')",
+ 'CREATE TABLE Customers (CustomerId INT64 DEFAULT (GET_NEXT_SEQUENCE_VALUE(' .
+ 'Sequence Seq)), CustomerName STRING(1024)) PRIMARY KEY (CustomerId)'
+ ]);
+
+ print('Waiting for operation to complete...' . PHP_EOL);
+ $operation->pollUntilComplete();
+
+ printf(
+ 'Created Seq sequence and Customers table, where ' .
+ 'the key column CustomerId uses the sequence as a default value' .
+ PHP_EOL
+ );
+
+ $res = $transaction->execute(
+ 'INSERT INTO Customers (CustomerName) VALUES ' .
+ "('Alice'), ('David'), ('Marc') THEN RETURN CustomerId"
+ );
+ $rows = $res->rows(Result::RETURN_ASSOCIATIVE);
+
+ foreach ($rows as $row) {
+ printf('Inserted customer record with CustomerId: %d %s',
+ $row['CustomerId'],
+ PHP_EOL
+ );
+ }
+ $transaction->commit();
+
+ printf(sprintf(
+ 'Number of customer records inserted is: %d %s',
+ $res->stats()['rowCountExact'],
+ PHP_EOL
+ ));
+}
+// [END spanner_create_sequence]
+
+// 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/spanner/src/drop_sequence.php b/spanner/src/drop_sequence.php
new file mode 100644
index 0000000000..a2faca07b1
--- /dev/null
+++ b/spanner/src/drop_sequence.php
@@ -0,0 +1,65 @@
+instance($instanceId);
+ $database = $instance->database($databaseId);
+
+ $operation = $database->updateDdlBatch([
+ 'ALTER TABLE Customers ALTER COLUMN CustomerId DROP DEFAULT',
+ 'DROP SEQUENCE Seq'
+ ]);
+
+ print('Waiting for operation to complete...' . PHP_EOL);
+ $operation->pollUntilComplete();
+
+ printf(
+ 'Altered Customers table to drop DEFAULT from CustomerId ' .
+ 'column and dropped the Seq sequence' .
+ PHP_EOL
+ );
+}
+// [END spanner_drop_sequence]
+
+// 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/spanner/src/pg_alter_sequence.php b/spanner/src/pg_alter_sequence.php
new file mode 100644
index 0000000000..19336abf5b
--- /dev/null
+++ b/spanner/src/pg_alter_sequence.php
@@ -0,0 +1,85 @@
+instance($instanceId);
+ $database = $instance->database($databaseId);
+ $transaction = $database->transaction();
+
+ $operation = $database->updateDdl(
+ 'ALTER SEQUENCE Seq SKIP RANGE 1000 5000000'
+ );
+
+ print('Waiting for operation to complete...' . PHP_EOL);
+ $operation->pollUntilComplete();
+
+ printf(
+ 'Altered Seq sequence to skip an inclusive range between 1000 and 5000000' .
+ PHP_EOL
+ );
+
+ $res = $transaction->execute(
+ 'INSERT INTO Customers (CustomerName) VALUES ' .
+ "('Lea'), ('Catalina'), ('Smith') RETURNING CustomerId"
+ );
+ $rows = $res->rows(Result::RETURN_ASSOCIATIVE);
+
+ foreach ($rows as $row) {
+ printf('Inserted customer record with CustomerId: %d %s',
+ $row['customerid'],
+ PHP_EOL
+ );
+ }
+ $transaction->commit();
+
+ printf(sprintf(
+ 'Number of customer records inserted is: %d %s',
+ $res->stats()['rowCountExact'],
+ PHP_EOL
+ ));
+}
+// [END spanner_postgresql_alter_sequence]
+
+// 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/spanner/src/pg_create_sequence.php b/spanner/src/pg_create_sequence.php
new file mode 100644
index 0000000000..2ab15f214f
--- /dev/null
+++ b/spanner/src/pg_create_sequence.php
@@ -0,0 +1,88 @@
+instance($instanceId);
+ $database = $instance->database($databaseId);
+ $transaction = $database->transaction();
+
+ $operation = $database->updateDdlBatch([
+ 'CREATE SEQUENCE Seq BIT_REVERSED_POSITIVE',
+ "CREATE TABLE Customers (CustomerId BIGINT DEFAULT nextval('Seq'), " .
+ 'CustomerName character varying(1024), PRIMARY KEY (CustomerId))'
+ ]);
+
+ print('Waiting for operation to complete...' . PHP_EOL);
+ $operation->pollUntilComplete();
+
+ printf(
+ 'Created Seq sequence and Customers table, where ' .
+ 'the key column CustomerId uses the sequence as a default value' .
+ PHP_EOL
+ );
+
+ $res = $transaction->execute(
+ 'INSERT INTO Customers (CustomerName) VALUES ' .
+ "('Alice'), ('David'), ('Marc') RETURNING CustomerId"
+ );
+ $rows = $res->rows(Result::RETURN_ASSOCIATIVE);
+
+ foreach ($rows as $row) {
+ printf('Inserted customer record with CustomerId: %d %s',
+ $row['customerid'],
+ PHP_EOL
+ );
+ }
+ $transaction->commit();
+
+ printf(sprintf(
+ 'Number of customer records inserted is: %d %s',
+ $res->stats()['rowCountExact'],
+ PHP_EOL
+ ));
+}
+// [END spanner_postgresql_create_sequence]
+
+// 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/spanner/src/pg_drop_sequence.php b/spanner/src/pg_drop_sequence.php
new file mode 100644
index 0000000000..9dc6274d59
--- /dev/null
+++ b/spanner/src/pg_drop_sequence.php
@@ -0,0 +1,65 @@
+instance($instanceId);
+ $database = $instance->database($databaseId);
+
+ $operation = $database->updateDdlBatch([
+ 'ALTER TABLE Customers ALTER COLUMN CustomerId DROP DEFAULT',
+ 'DROP SEQUENCE Seq'
+ ]);
+
+ print('Waiting for operation to complete...' . PHP_EOL);
+ $operation->pollUntilComplete();
+
+ printf(
+ 'Altered Customers table to drop DEFAULT from CustomerId ' .
+ 'column and dropped the Seq sequence' .
+ PHP_EOL
+ );
+}
+// [END spanner_postgresql_drop_sequence]
+
+// 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/spanner/test/spannerPgTest.php b/spanner/test/spannerPgTest.php
index 59d3051911..113e0eadc3 100644
--- a/spanner/test/spannerPgTest.php
+++ b/spanner/test/spannerPgTest.php
@@ -447,6 +447,46 @@ public function testDmlReturningDelete()
$this->assertStringContainsString($expectedOutput, $output);
}
+ /**
+ * @depends testCreateDatabase
+ */
+ public function testCreateSequence()
+ {
+ $output = $this->runFunctionSnippet('pg_create_sequence');
+ $this->assertStringContainsString(
+ 'Created Seq sequence and Customers table, where ' .
+ 'the key column CustomerId uses the sequence as a default value',
+ $output
+ );
+ $this->assertStringContainsString('Number of customer records inserted is: 3', $output);
+ }
+
+ /**
+ * @depends testCreateSequence
+ */
+ public function testAlterSequence()
+ {
+ $output = $this->runFunctionSnippet('pg_alter_sequence');
+ $this->assertStringContainsString(
+ 'Altered Seq sequence to skip an inclusive range between 1000 and 5000000',
+ $output
+ );
+ $this->assertStringContainsString('Number of customer records inserted is: 3', $output);
+ }
+
+ /**
+ * @depends testAlterSequence
+ */
+ public function testDropSequence()
+ {
+ $output = $this->runFunctionSnippet('pg_drop_sequence');
+ $this->assertStringContainsString(
+ 'Altered Customers table to drop DEFAULT from CustomerId ' .
+ 'column and dropped the Seq sequence',
+ $output
+ );
+ }
+
public static function tearDownAfterClass(): void
{
// Clean up
diff --git a/spanner/test/spannerTest.php b/spanner/test/spannerTest.php
index 52b5aa8a9a..74b9d347a3 100644
--- a/spanner/test/spannerTest.php
+++ b/spanner/test/spannerTest.php
@@ -1048,6 +1048,46 @@ public function testReadWriteRetry()
$this->assertStringContainsString('Transaction complete.', $output);
}
+ /**
+ * @depends testCreateDatabase
+ */
+ public function testCreateSequence()
+ {
+ $output = $this->runFunctionSnippet('create_sequence');
+ $this->assertStringContainsString(
+ 'Created Seq sequence and Customers table, where ' .
+ 'the key column CustomerId uses the sequence as a default value',
+ $output
+ );
+ $this->assertStringContainsString('Number of customer records inserted is: 3', $output);
+ }
+
+ /**
+ * @depends testCreateSequence
+ */
+ public function testAlterSequence()
+ {
+ $output = $this->runFunctionSnippet('alter_sequence');
+ $this->assertStringContainsString(
+ 'Altered Seq sequence to skip an inclusive range between 1000 and 5000000',
+ $output
+ );
+ $this->assertStringContainsString('Number of customer records inserted is: 3', $output);
+ }
+
+ /**
+ * @depends testAlterSequence
+ */
+ public function testDropSequence()
+ {
+ $output = $this->runFunctionSnippet('drop_sequence');
+ $this->assertStringContainsString(
+ 'Altered Customers table to drop DEFAULT from CustomerId ' .
+ 'column and dropped the Seq sequence',
+ $output
+ );
+ }
+
private function testGetInstanceConfig()
{
$output = $this->runFunctionSnippet('get_instance_config', [
From ac4062aa1d2fb3844e4edcb4b29577a77bb051a5 Mon Sep 17 00:00:00 2001
From: Nicholas Cook
Date: Wed, 2 Aug 2023 16:44:20 -0700
Subject: [PATCH 061/285] feat(Transcoder): add batch mode sample and test
(#1892)
---
media/transcoder/composer.json | 2 +-
.../src/create_job_from_preset_batch_mode.php | 65 +++++++++++++++++++
media/transcoder/test/transcoderTest.php | 43 +++++++++---
3 files changed, 101 insertions(+), 9 deletions(-)
create mode 100644 media/transcoder/src/create_job_from_preset_batch_mode.php
diff --git a/media/transcoder/composer.json b/media/transcoder/composer.json
index 2183bb528e..9c8c5930db 100644
--- a/media/transcoder/composer.json
+++ b/media/transcoder/composer.json
@@ -1,6 +1,6 @@
{
"require": {
- "google/cloud-video-transcoder": "^0.8.2",
+ "google/cloud-video-transcoder": "^0.9.0",
"google/cloud-storage": "^1.9",
"ext-bcmath": "*"
}
diff --git a/media/transcoder/src/create_job_from_preset_batch_mode.php b/media/transcoder/src/create_job_from_preset_batch_mode.php
new file mode 100644
index 0000000000..7bced91cda
--- /dev/null
+++ b/media/transcoder/src/create_job_from_preset_batch_mode.php
@@ -0,0 +1,65 @@
+locationName($projectId, $location);
+ $job = new Job();
+ $job->setInputUri($inputUri);
+ $job->setOutputUri($outputUri);
+ $job->setTemplateId($preset);
+ $job->setMode(Job\ProcessingMode::PROCESSING_MODE_BATCH);
+ $job->setBatchModePriority(10);
+ $request = (new CreateJobRequest())
+ ->setParent($formattedParent)
+ ->setJob($job);
+
+ $response = $transcoderServiceClient->createJob($request);
+
+ // Print job name.
+ printf('Job: %s' . PHP_EOL, $response->getName());
+}
+# [END transcoder_create_job_from_preset_batch_mode]
+
+require_once __DIR__ . '/../../../testing/sample_helpers.php';
+\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);
diff --git a/media/transcoder/test/transcoderTest.php b/media/transcoder/test/transcoderTest.php
index 039858fcd4..24717849d4 100644
--- a/media/transcoder/test/transcoderTest.php
+++ b/media/transcoder/test/transcoderTest.php
@@ -47,6 +47,7 @@ class transcoderTest extends TestCase
private static $inputConcatVideo2Uri;
private static $inputOverlayUri;
private static $outputUriForPreset;
+ private static $outputUriForPresetBatchMode;
private static $outputUriForAdHoc;
private static $outputUriForTemplate;
private static $outputUriForAnimatedOverlay;
@@ -96,6 +97,7 @@ public static function setUpBeforeClass(): void
self::$inputConcatVideo2Uri = sprintf('gs://%s/%s', $bucketName, self::$testConcatVideo2FileName);
self::$inputOverlayUri = sprintf('gs://%s/%s', $bucketName, self::$testOverlayImageFileName);
self::$outputUriForPreset = sprintf('gs://%s/test-output-preset/', $bucketName);
+ self::$outputUriForPresetBatchMode = sprintf('gs://%s/test-output-preset-batch-mode/', $bucketName);
self::$outputUriForAdHoc = sprintf('gs://%s/test-output-adhoc/', $bucketName);
self::$outputUriForTemplate = sprintf('gs://%s/test-output-template/', $bucketName);
self::$outputUriForAnimatedOverlay = sprintf('gs://%s/test-output-animated-overlay/', $bucketName);
@@ -172,7 +174,7 @@ public function testJobFromAdHoc()
$jobId = explode('/', $createOutput);
$jobId = trim($jobId[(count($jobId) - 1)]);
- sleep(30);
+ sleep(10);
$this->assertJobStateSucceeded($jobId);
// Test Get method
@@ -214,7 +216,7 @@ public function testJobFromPreset()
$jobId = explode('/', $output);
$jobId = trim($jobId[(count($jobId) - 1)]);
- sleep(30);
+ sleep(10);
$this->assertJobStateSucceeded($jobId);
$this->runFunctionSnippet('delete_job', [
@@ -224,6 +226,31 @@ public function testJobFromPreset()
]);
}
+ public function testJobFromPresetBatchMode()
+ {
+ $output = $this->runFunctionSnippet('create_job_from_preset_batch_mode', [
+ self::$projectId,
+ self::$location,
+ self::$inputVideoUri,
+ self::$outputUriForPresetBatchMode,
+ self::$preset
+ ]);
+
+ $this->assertMatchesRegularExpression(sprintf('%s', self::$jobIdRegex), $output);
+
+ $jobId = explode('/', $output);
+ $jobId = trim($jobId[(count($jobId) - 1)]);
+
+ sleep(10);
+ $this->assertJobStateSucceeded($jobId);
+
+ $this->runFunctionSnippet('delete_job', [
+ self::$projectId,
+ self::$location,
+ $jobId
+ ]);
+ }
+
public function testJobFromTemplate()
{
$jobTemplateId = sprintf('php-test-template-%s', time());
@@ -246,7 +273,7 @@ public function testJobFromTemplate()
$jobId = explode('/', $output);
$jobId = trim($jobId[(count($jobId) - 1)]);
- sleep(30);
+ sleep(10);
$this->assertJobStateSucceeded($jobId);
$this->runFunctionSnippet('delete_job', [
@@ -277,7 +304,7 @@ public function testJobAnimatedOverlay()
$jobId = explode('/', $output);
$jobId = trim($jobId[(count($jobId) - 1)]);
- sleep(30);
+ sleep(10);
$this->assertJobStateSucceeded($jobId);
$this->runFunctionSnippet('delete_job', [
@@ -302,7 +329,7 @@ public function testJobStaticOverlay()
$jobId = explode('/', $output);
$jobId = trim($jobId[(count($jobId) - 1)]);
- sleep(30);
+ sleep(10);
$this->assertJobStateSucceeded($jobId);
$this->runFunctionSnippet('delete_job', [
@@ -326,7 +353,7 @@ public function testJobPeriodicImagesSpritesheet()
$jobId = explode('/', $output);
$jobId = trim($jobId[(count($jobId) - 1)]);
- sleep(30);
+ sleep(10);
$this->assertJobStateSucceeded($jobId);
$this->runFunctionSnippet('delete_job', [
@@ -350,7 +377,7 @@ public function testJobSetNumberImagesSpritesheet()
$jobId = explode('/', $output);
$jobId = trim($jobId[(count($jobId) - 1)]);
- sleep(30);
+ sleep(10);
$this->assertJobStateSucceeded($jobId);
$this->runFunctionSnippet('delete_job', [
@@ -379,7 +406,7 @@ public function testJobConcat()
$jobId = explode('/', $output);
$jobId = trim($jobId[(count($jobId) - 1)]);
- sleep(30);
+ sleep(10);
$this->assertJobStateSucceeded($jobId);
$this->runFunctionSnippet('delete_job', [
From bc962f5b52c4f97b49ed0926c35723f8f0157bd6 Mon Sep 17 00:00:00 2001
From: Mend Renovate
Date: Tue, 15 Aug 2023 15:02:41 +0200
Subject: [PATCH 062/285] fix(deps): update dependency
google/cloud-error-reporting to ^0.21.0 (#1908)
---
error_reporting/composer.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/error_reporting/composer.json b/error_reporting/composer.json
index 7bedb46b9a..7cc049c1fe 100644
--- a/error_reporting/composer.json
+++ b/error_reporting/composer.json
@@ -1,5 +1,5 @@
{
"require": {
- "google/cloud-error-reporting": "^0.20.2"
+ "google/cloud-error-reporting": "^0.21.0"
}
}
From ad2b877cd02f065be4498b0315d079f205941aba Mon Sep 17 00:00:00 2001
From: Mend Renovate
Date: Tue, 15 Aug 2023 15:03:00 +0200
Subject: [PATCH 063/285] fix(deps): update dependency
google/cloud-error-reporting to ^0.21.0 (#1907)
---
appengine/standard/errorreporting/composer.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/appengine/standard/errorreporting/composer.json b/appengine/standard/errorreporting/composer.json
index 3ae499d7ff..e0a12eebb1 100644
--- a/appengine/standard/errorreporting/composer.json
+++ b/appengine/standard/errorreporting/composer.json
@@ -1,6 +1,6 @@
{
"require": {
- "google/cloud-error-reporting": "^0.20.0"
+ "google/cloud-error-reporting": "^0.21.0"
},
"autoload": {
"files": [
From 16f7498c2faba06a0a5c4fda4587ed5a74493830 Mon Sep 17 00:00:00 2001
From: Nicholas Cook
Date: Tue, 15 Aug 2023 06:04:18 -0700
Subject: [PATCH 064/285] feat(LiveStream): add samples and tests for assets
and pools (#1909)
---
media/livestream/composer.json | 2 +-
media/livestream/src/create_asset.php | 75 ++++++++++++++
media/livestream/src/delete_asset.php | 64 ++++++++++++
media/livestream/src/get_asset.php | 58 +++++++++++
media/livestream/src/get_pool.php | 58 +++++++++++
media/livestream/src/list_assets.php | 59 +++++++++++
media/livestream/src/update_pool.php | 81 +++++++++++++++
media/livestream/test/livestreamTest.php | 122 +++++++++++++++++++++++
8 files changed, 518 insertions(+), 1 deletion(-)
create mode 100644 media/livestream/src/create_asset.php
create mode 100644 media/livestream/src/delete_asset.php
create mode 100644 media/livestream/src/get_asset.php
create mode 100644 media/livestream/src/get_pool.php
create mode 100644 media/livestream/src/list_assets.php
create mode 100644 media/livestream/src/update_pool.php
diff --git a/media/livestream/composer.json b/media/livestream/composer.json
index 6946109888..ab584de13d 100644
--- a/media/livestream/composer.json
+++ b/media/livestream/composer.json
@@ -2,6 +2,6 @@
"name": "google/live-stream-sample",
"type": "project",
"require": {
- "google/cloud-video-live-stream": "^0.5.0"
+ "google/cloud-video-live-stream": "^0.6.0"
}
}
diff --git a/media/livestream/src/create_asset.php b/media/livestream/src/create_asset.php
new file mode 100644
index 0000000000..d88c0506bb
--- /dev/null
+++ b/media/livestream/src/create_asset.php
@@ -0,0 +1,75 @@
+locationName($callingProjectId, $location);
+ $asset = (new Asset())
+ ->setVideo(
+ (new Asset\VideoAsset())
+ ->setUri($assetUri));
+
+ // Run the asset creation request. The response is a long-running operation ID.
+ $request = (new CreateAssetRequest())
+ ->setParent($parent)
+ ->setAsset($asset)
+ ->setAssetId($assetId);
+ $operationResponse = $livestreamClient->createAsset($request);
+ $operationResponse->pollUntilComplete();
+ if ($operationResponse->operationSucceeded()) {
+ $result = $operationResponse->getResult();
+ // Print results
+ printf('Asset: %s' . PHP_EOL, $result->getName());
+ } else {
+ $error = $operationResponse->getError();
+ // handleError($error)
+ }
+}
+// [END livestream_create_asset]
+
+// 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/media/livestream/src/delete_asset.php b/media/livestream/src/delete_asset.php
new file mode 100644
index 0000000000..a93648db90
--- /dev/null
+++ b/media/livestream/src/delete_asset.php
@@ -0,0 +1,64 @@
+assetName($callingProjectId, $location, $assetId);
+
+ // Run the asset deletion request. The response is a long-running operation ID.
+ $request = (new DeleteAssetRequest())
+ ->setName($formattedName);
+ $operationResponse = $livestreamClient->deleteAsset($request);
+ $operationResponse->pollUntilComplete();
+ if ($operationResponse->operationSucceeded()) {
+ // Print status
+ printf('Deleted asset %s' . PHP_EOL, $assetId);
+ } else {
+ $error = $operationResponse->getError();
+ // handleError($error)
+ }
+}
+// [END livestream_delete_asset]
+
+// 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/media/livestream/src/get_asset.php b/media/livestream/src/get_asset.php
new file mode 100644
index 0000000000..c37a78dab1
--- /dev/null
+++ b/media/livestream/src/get_asset.php
@@ -0,0 +1,58 @@
+assetName($callingProjectId, $location, $assetId);
+
+ // Get the asset.
+ $request = (new GetAssetRequest())
+ ->setName($formattedName);
+ $response = $livestreamClient->getAsset($request);
+ // Print results
+ printf('Asset: %s' . PHP_EOL, $response->getName());
+}
+// [END livestream_get_asset]
+
+// 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/media/livestream/src/get_pool.php b/media/livestream/src/get_pool.php
new file mode 100644
index 0000000000..72f5401038
--- /dev/null
+++ b/media/livestream/src/get_pool.php
@@ -0,0 +1,58 @@
+poolName($callingProjectId, $location, $poolId);
+
+ // Get the pool.
+ $request = (new GetPoolRequest())
+ ->setName($formattedName);
+ $response = $livestreamClient->getPool($request);
+ // Print results
+ printf('Pool: %s' . PHP_EOL, $response->getName());
+}
+// [END livestream_get_pool]
+
+// 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/media/livestream/src/list_assets.php b/media/livestream/src/list_assets.php
new file mode 100644
index 0000000000..2bfc2f9709
--- /dev/null
+++ b/media/livestream/src/list_assets.php
@@ -0,0 +1,59 @@
+locationName($callingProjectId, $location);
+ $request = (new ListAssetsRequest())
+ ->setParent($parent);
+
+ $response = $livestreamClient->listAssets($request);
+ // Print the asset list.
+ $assets = $response->iterateAllElements();
+ print('Assets:' . PHP_EOL);
+ foreach ($assets as $asset) {
+ printf('%s' . PHP_EOL, $asset->getName());
+ }
+}
+// [END livestream_list_assets]
+
+// 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/media/livestream/src/update_pool.php b/media/livestream/src/update_pool.php
new file mode 100644
index 0000000000..2f6636ed8b
--- /dev/null
+++ b/media/livestream/src/update_pool.php
@@ -0,0 +1,81 @@
+poolName($callingProjectId, $location, $poolId);
+ $pool = (new Pool())
+ ->setName($formattedName)
+ ->setNetworkConfig(
+ (new Pool\NetworkConfig())
+ ->setPeeredNetwork($peeredNetwork));
+
+ $updateMask = new FieldMask([
+ 'paths' => ['network_config']
+ ]);
+
+ // Run the pool update request. The response is a long-running operation ID.
+ $request = (new UpdatePoolRequest())
+ ->setPool($pool)
+ ->setUpdateMask($updateMask);
+ $operationResponse = $livestreamClient->updatePool($request);
+
+ $operationResponse->pollUntilComplete();
+ if ($operationResponse->operationSucceeded()) {
+ $result = $operationResponse->getResult();
+ // Print results
+ printf('Updated pool: %s' . PHP_EOL, $result->getName());
+ } else {
+ $error = $operationResponse->getError();
+ // handleError($error)
+ }
+}
+// [END livestream_update_pool]
+
+// 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/media/livestream/test/livestreamTest.php b/media/livestream/test/livestreamTest.php
index a7dc2da675..3976ffb0ef 100644
--- a/media/livestream/test/livestreamTest.php
+++ b/media/livestream/test/livestreamTest.php
@@ -50,6 +50,14 @@ class livestreamTest extends TestCase
private static $eventId;
private static $eventName;
+ private static $assetIdPrefix = 'php-test-asset';
+ private static $assetId;
+ private static $assetName;
+ private static $assetUri = 'gs://cloud-samples-data/media/ForBiggerEscapes.mp4';
+
+ private static $poolId;
+ private static $poolName;
+
public static function setUpBeforeClass(): void
{
self::checkProjectEnvVars();
@@ -57,6 +65,7 @@ public static function setUpBeforeClass(): void
self::deleteOldChannels();
self::deleteOldInputs();
+ self::deleteOldAssets();
}
public function testCreateInput()
@@ -384,6 +393,93 @@ public function testDeleteChannelWithEvents()
]);
}
+ /** @depends testDeleteChannelWithEvents */
+ public function testCreateAsset()
+ {
+ self::$assetId = sprintf('%s-%s-%s', self::$assetIdPrefix, uniqid(), time());
+ self::$assetName = sprintf('projects/%s/locations/%s/assets/%s', self::$projectId, self::$location, self::$assetId);
+
+ $output = $this->runFunctionSnippet('create_asset', [
+ self::$projectId,
+ self::$location,
+ self::$assetId,
+ self::$assetUri
+ ]);
+ $this->assertStringContainsString(self::$assetName, $output);
+ }
+
+ /** @depends testCreateAsset */
+ public function testListAssets()
+ {
+ $output = $this->runFunctionSnippet('list_assets', [
+ self::$projectId,
+ self::$location
+ ]);
+ $this->assertStringContainsString(self::$assetName, $output);
+ }
+
+ /** @depends testListAssets */
+ public function testGetAsset()
+ {
+ $output = $this->runFunctionSnippet('get_asset', [
+ self::$projectId,
+ self::$location,
+ self::$assetId
+ ]);
+ $this->assertStringContainsString(self::$assetName, $output);
+ }
+
+ /** @depends testGetAsset */
+ public function testDeleteAsset()
+ {
+ $output = $this->runFunctionSnippet('delete_asset', [
+ self::$projectId,
+ self::$location,
+ self::$assetId
+ ]);
+ $this->assertStringContainsString('Deleted asset', $output);
+ }
+
+ /** @depends testDeleteAsset */
+ public function testGetPool()
+ {
+ self::$poolId = 'default'; # only 1 pool supported per location
+ self::$poolName = sprintf('projects/%s/locations/%s/pools/%s', self::$projectId, self::$location, self::$poolId);
+
+ $output = $this->runFunctionSnippet('get_pool', [
+ self::$projectId,
+ self::$location,
+ self::$poolId
+ ]);
+ $this->assertStringContainsString(self::$poolName, $output);
+ }
+
+ /** @depends testGetPool */
+ public function testUpdatePool()
+ {
+ # You can't update a pool if any channels are running. Updating a pool
+ # takes a long time to complete. If tests are running in parallel for
+ # different versions of PHP, this test will fail.
+ $this->markTestSkipped('Cannot be run if tests run in parallel.');
+
+ $output = $this->runFunctionSnippet('update_pool', [
+ self::$projectId,
+ self::$location,
+ self::$poolId,
+ ''
+ ]);
+ $this->assertStringContainsString(self::$poolName, $output);
+
+ $livestreamClient = new LivestreamServiceClient();
+ $formattedName = $livestreamClient->poolName(
+ self::$projectId,
+ self::$location,
+ self::$poolId
+ );
+ $pool = $livestreamClient->getPool($formattedName);
+ $this->assertEquals($pool->getNetworkConfig()->getPeeredNetwork(), '');
+ }
+
private static function deleteOldInputs(): void
{
$livestreamClient = new LivestreamServiceClient();
@@ -468,4 +564,30 @@ private static function deleteOldChannels(): void
}
}
}
+
+ private static function deleteOldAssets(): void
+ {
+ $livestreamClient = new LivestreamServiceClient();
+ $parent = $livestreamClient->locationName(self::$projectId, self::$location);
+ $response = $livestreamClient->listAssets($parent);
+ $assets = $response->iterateAllElements();
+
+ $currentTime = time();
+ $oneHourInSecs = 60 * 60 * 1;
+
+ foreach ($assets as $asset) {
+ $tmp = explode('/', $asset->getName());
+ $id = end($tmp);
+ $tmp = explode('-', $id);
+ $timestamp = intval(end($tmp));
+
+ if ($currentTime - $timestamp >= $oneHourInSecs) {
+ try {
+ $livestreamClient->deleteAsset($asset->getName());
+ } catch (ApiException $e) {
+ printf('Asset delete failed: %s.' . PHP_EOL, $e->getMessage());
+ }
+ }
+ }
+ }
}
From 286373142f96d347c7052af58ebd6a1f8e4ef41b Mon Sep 17 00:00:00 2001
From: Gareth
Date: Tue, 22 Aug 2023 13:12:56 -0700
Subject: [PATCH 065/285] feat(functions): samples for typed function signature
(#1866)
---
functions/typed_greeting/composer.json | 12 ++++
functions/typed_greeting/index.php | 84 ++++++++++++++++++++++
functions/typed_greeting/phpunit.xml.dist | 35 +++++++++
functions/typed_greeting/test/UnitTest.php | 67 +++++++++++++++++
4 files changed, 198 insertions(+)
create mode 100644 functions/typed_greeting/composer.json
create mode 100644 functions/typed_greeting/index.php
create mode 100644 functions/typed_greeting/phpunit.xml.dist
create mode 100644 functions/typed_greeting/test/UnitTest.php
diff --git a/functions/typed_greeting/composer.json b/functions/typed_greeting/composer.json
new file mode 100644
index 0000000000..6655c8e40e
--- /dev/null
+++ b/functions/typed_greeting/composer.json
@@ -0,0 +1,12 @@
+{
+ "require": {
+ "php": ">= 7.4",
+ "google/cloud-functions-framework": "^1.3"
+ },
+ "scripts": {
+ "start": [
+ "Composer\\Config::disableProcessTimeout",
+ "FUNCTION_TARGET=helloHttp php -S localhost:${PORT:-8080} vendor/google/cloud-functions-framework/router.php"
+ ]
+ }
+}
diff --git a/functions/typed_greeting/index.php b/functions/typed_greeting/index.php
new file mode 100644
index 0000000000..3a3b4d8426
--- /dev/null
+++ b/functions/typed_greeting/index.php
@@ -0,0 +1,84 @@
+first_name = $first_name;
+ $this->last_name = $last_name;
+ }
+
+ public function serializeToJsonString(): string
+ {
+ return json_encode([
+ 'first_name' => $this->first_name,
+ 'last_name' => $this->last_name,
+ ]);
+ }
+
+ public function mergeFromJsonString(string $body): void
+ {
+ $obj = json_decode($body);
+ $this->first_name = $obj['first_name'];
+ $this->last_name = $obj['last_name'];
+ }
+}
+
+class GreetingResponse
+{
+ /** @var string */
+ public $message;
+
+ public function __construct(string $message = '')
+ {
+ $this->message = $message;
+ }
+
+ public function serializeToJsonString(): string
+ {
+ return json_encode([
+ 'message' => $message,
+ ]);
+ }
+
+ public function mergeFromJsonString(string $body): void
+ {
+ $obj = json_decode($body);
+ $this->message = $obj['message'];
+ }
+};
+
+function greeting(GreetingRequest $req): GreetingResponse
+{
+ return new GreetingResponse("Hello $req->first_name $req->last_name!");
+};
+
+FunctionsFramework::typed('greeting', 'greeting');
+
+// [END functions_typed_greeting]
diff --git a/functions/typed_greeting/phpunit.xml.dist b/functions/typed_greeting/phpunit.xml.dist
new file mode 100644
index 0000000000..1a192330ff
--- /dev/null
+++ b/functions/typed_greeting/phpunit.xml.dist
@@ -0,0 +1,35 @@
+
+
+
+
+
+ .
+ vendor
+
+
+
+
+
+
+
+ .
+
+ ./vendor
+
+
+
+
diff --git a/functions/typed_greeting/test/UnitTest.php b/functions/typed_greeting/test/UnitTest.php
new file mode 100644
index 0000000000..5aa0d2f6e5
--- /dev/null
+++ b/functions/typed_greeting/test/UnitTest.php
@@ -0,0 +1,67 @@
+runFunction(self::$entryPoint, [new GreetingRequest($first_name, $last_name)]);
+ $this->assertEquals($expected_message, $actual->message, $label . ':');
+ }
+
+ private static function runFunction($functionName, array $params = []): GreetingResponse
+ {
+ return call_user_func_array($functionName, $params);
+ }
+
+ public static function cases(): array
+ {
+ return [
+ [
+ 'label' => 'Default',
+ 'first_name' => 'Jane',
+ 'last_name' => 'Doe',
+ 'expected_message' => 'Hello Jane Doe!',
+ ],
+ ];
+ }
+}
From 3438bdb407efb3a67e52b8d190e73d0f1fb6a7cc Mon Sep 17 00:00:00 2001
From: sameer-crest <129392897+sameer-crest@users.noreply.github.com>
Date: Wed, 23 Aug 2023 12:54:04 +0530
Subject: [PATCH 066/285] feat(dlp): sample for Hybrid Job Trigger ,
kAnonymity with entity id , and DeIdentify Replace InfoType (#1900)
---
dlp/src/deidentify_replace_infotype.php | 100 ++++++++
dlp/src/inspect_gcs.php | 9 +-
...nspect_send_data_to_hybrid_job_trigger.php | 136 ++++++++++
dlp/src/k_anonymity_with_entity_id.php | 172 +++++++++++++
dlp/test/dlpLongRunningTest.php | 121 ++++++++-
dlp/test/dlpTest.php | 241 ++++++++++++++++++
6 files changed, 764 insertions(+), 15 deletions(-)
create mode 100644 dlp/src/deidentify_replace_infotype.php
create mode 100644 dlp/src/inspect_send_data_to_hybrid_job_trigger.php
create mode 100644 dlp/src/k_anonymity_with_entity_id.php
diff --git a/dlp/src/deidentify_replace_infotype.php b/dlp/src/deidentify_replace_infotype.php
new file mode 100644
index 0000000000..46eb2d530c
--- /dev/null
+++ b/dlp/src/deidentify_replace_infotype.php
@@ -0,0 +1,100 @@
+setValue($string);
+
+ // The infoTypes of information to mask.
+ $phoneNumberinfoType = (new InfoType())
+ ->setName('PHONE_NUMBER');
+ $personNameinfoType = (new InfoType())
+ ->setName('PERSON_NAME');
+ $infoTypes = [$phoneNumberinfoType, $personNameinfoType];
+
+ // Create the configuration object.
+ $inspectConfig = (new InspectConfig())
+ ->setInfoTypes($infoTypes);
+
+ // Create the information transform configuration objects.
+ $primitiveTransformation = (new PrimitiveTransformation())
+ ->setReplaceWithInfoTypeConfig(new ReplaceWithInfoTypeConfig());
+
+ $infoTypeTransformation = (new InfoTypeTransformation())
+ ->setPrimitiveTransformation($primitiveTransformation);
+
+ $infoTypeTransformations = (new InfoTypeTransformations())
+ ->setTransformations([$infoTypeTransformation]);
+
+ // Create the deidentification configuration object.
+ $deidentifyConfig = (new DeidentifyConfig())
+ ->setInfoTypeTransformations($infoTypeTransformations);
+
+ // Run request.
+ $response = $dlp->deidentifyContent([
+ 'parent' => $parent,
+ 'deidentifyConfig' => $deidentifyConfig,
+ 'item' => $content,
+ 'inspectConfig' => $inspectConfig
+ ]);
+
+ // Print the results.
+ printf('Text after replace with infotype config: %s', $response->getItem()->getValue());
+}
+# [END dlp_deidentify_replace_infotype]
+
+// 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/dlp/src/inspect_gcs.php b/dlp/src/inspect_gcs.php
index 996199546c..59930d8e32 100644
--- a/dlp/src/inspect_gcs.php
+++ b/dlp/src/inspect_gcs.php
@@ -1,5 +1,4 @@
$callingProjectId,
- ]);
- $pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
- ]);
+ $dlp = new DlpServiceClient();
+ $pubsub = new PubSubClient();
$topic = $pubsub->topic($topicId);
// The infoTypes of information to match
diff --git a/dlp/src/inspect_send_data_to_hybrid_job_trigger.php b/dlp/src/inspect_send_data_to_hybrid_job_trigger.php
new file mode 100644
index 0000000000..6cec8978de
--- /dev/null
+++ b/dlp/src/inspect_send_data_to_hybrid_job_trigger.php
@@ -0,0 +1,136 @@
+setValue($string);
+
+ $container = (new Container())
+ ->setFullPath('10.0.0.2:logs1:app1')
+ ->setRelativePath('app1')
+ ->setRootPath('10.0.0.2:logs1')
+ ->setType('logging_sys')
+ ->setVersion('1.2');
+
+ $findingDetails = (new HybridFindingDetails())
+ ->setContainerDetails($container)
+ ->setLabels([
+ 'env' => 'prod',
+ 'appointment-bookings-comments' => ''
+ ]);
+
+ $hybridItem = (new HybridContentItem())
+ ->setItem($content)
+ ->setFindingDetails($findingDetails);
+
+ $parent = "projects/$callingProjectId/locations/global";
+ $name = "projects/$callingProjectId/locations/global/jobTriggers/" . $jobTriggerId;
+
+ $triggerJob = null;
+ try {
+ $triggerJob = $dlp->activateJobTrigger($name);
+ } catch (\InvalidArgumentException $e) {
+ $result = $dlp->listDlpJobs($parent, ['filter' => 'trigger_name=' . $name]);
+ foreach ($result as $job) {
+ $triggerJob = $job;
+ }
+ }
+
+ $dlp->hybridInspectJobTrigger($name, [
+ 'hybridItem' => $hybridItem,
+ ]);
+
+ $numOfAttempts = 10;
+ do {
+ printf('Waiting for job to complete' . PHP_EOL);
+ sleep(10);
+ $job = $dlp->getDlpJob($triggerJob->getName());
+ if ($job->getState() != JobState::RUNNING) {
+ break;
+ }
+ $numOfAttempts--;
+ } while ($numOfAttempts > 0);
+
+ // Print finding counts.
+ printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
+ switch ($job->getState()) {
+ case JobState::DONE:
+ $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
+ if (count($infoTypeStats) === 0) {
+ printf('No findings.' . PHP_EOL);
+ } else {
+ foreach ($infoTypeStats as $infoTypeStat) {
+ printf(
+ ' Found %s instance(s) of infoType %s' . PHP_EOL,
+ $infoTypeStat->getCount(),
+ $infoTypeStat->getInfoType()->getName()
+ );
+ }
+ }
+ break;
+ case JobState::FAILED:
+ printf('Job %s had errors:' . PHP_EOL, $job->getName());
+ $errors = $job->getErrors();
+ foreach ($errors as $error) {
+ var_dump($error->getDetails());
+ }
+ break;
+ case JobState::PENDING:
+ printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ break;
+ default:
+ printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
+}
+# [END dlp_inspect_send_data_to_hybrid_job_trigger]
+
+// 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/dlp/src/k_anonymity_with_entity_id.php b/dlp/src/k_anonymity_with_entity_id.php
new file mode 100644
index 0000000000..dd481a41be
--- /dev/null
+++ b/dlp/src/k_anonymity_with_entity_id.php
@@ -0,0 +1,172 @@
+setProjectId($callingProjectId)
+ ->setDatasetId($datasetId)
+ ->setTableId($tableId);
+
+ // Create a list of FieldId objects based on the provided list of column names.
+ $quasiIds = array_map(
+ function ($id) {
+ return (new FieldId())
+ ->setName($id);
+ },
+ $quasiIdNames
+ );
+
+ // Specify the unique identifier in the source table for the k-anonymity analysis.
+ $statsConfig = (new KAnonymityConfig())
+ ->setEntityId((new EntityId())
+ ->setField((new FieldId())
+ ->setName('Name')))
+ ->setQuasiIds($quasiIds);
+
+ // Configure the privacy metric to compute for re-identification risk analysis.
+ $privacyMetric = (new PrivacyMetric())
+ ->setKAnonymityConfig($statsConfig);
+
+ // Specify the bigquery table to store the findings.
+ // The "test_results" table in the given BigQuery dataset will be created if it doesn't
+ // already exist.
+ $outBigqueryTable = (new BigQueryTable())
+ ->setProjectId($callingProjectId)
+ ->setDatasetId($datasetId)
+ ->setTableId('test_results');
+
+ $outputStorageConfig = (new OutputStorageConfig())
+ ->setTable($outBigqueryTable);
+
+ $findings = (new SaveFindings())
+ ->setOutputConfig($outputStorageConfig);
+
+ $action = (new Action())
+ ->setSaveFindings($findings);
+
+ // Construct risk analysis job config to run.
+ $riskJob = (new RiskAnalysisJobConfig())
+ ->setPrivacyMetric($privacyMetric)
+ ->setSourceTable($bigqueryTable)
+ ->setActions([$action]);
+
+ // Submit request.
+ $parent = "projects/$callingProjectId/locations/global";
+ $job = $dlp->createDlpJob($parent, [
+ 'riskJob' => $riskJob
+ ]);
+
+ $numOfAttempts = 10;
+ do {
+ printf('Waiting for job to complete' . PHP_EOL);
+ sleep(10);
+ $job = $dlp->getDlpJob($job->getName());
+ if ($job->getState() == JobState::DONE) {
+ break;
+ }
+ $numOfAttempts--;
+ } while ($numOfAttempts > 0);
+
+ // Print finding counts
+ printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
+ switch ($job->getState()) {
+ case JobState::DONE:
+ $histBuckets = $job->getRiskDetails()->getKAnonymityResult()->getEquivalenceClassHistogramBuckets();
+
+ foreach ($histBuckets as $bucketIndex => $histBucket) {
+ // Print bucket stats.
+ printf('Bucket %s:' . PHP_EOL, $bucketIndex);
+ printf(
+ ' Bucket size range: [%s, %s]' . PHP_EOL,
+ $histBucket->getEquivalenceClassSizeLowerBound(),
+ $histBucket->getEquivalenceClassSizeUpperBound()
+ );
+
+ // Print bucket values.
+ foreach ($histBucket->getBucketValues() as $percent => $valueBucket) {
+ // Pretty-print quasi-ID values.
+ printf(' Quasi-ID values:' . PHP_EOL);
+ foreach ($valueBucket->getQuasiIdsValues() as $index => $value) {
+ print(' ' . $value->serializeToJsonString() . PHP_EOL);
+ }
+ printf(
+ ' Class size: %s' . PHP_EOL,
+ $valueBucket->getEquivalenceClassSize()
+ );
+ }
+ }
+
+ break;
+ case JobState::FAILED:
+ printf('Job %s had errors:' . PHP_EOL, $job->getName());
+ $errors = $job->getErrors();
+ foreach ($errors as $error) {
+ var_dump($error->getDetails());
+ }
+ break;
+ case JobState::PENDING:
+ printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ break;
+ default:
+ printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
+}
+# [END dlp_k_anonymity_with_entity_id]
+
+// 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/dlp/test/dlpLongRunningTest.php b/dlp/test/dlpLongRunningTest.php
index b2491b3a09..81ea7527ae 100644
--- a/dlp/test/dlpLongRunningTest.php
+++ b/dlp/test/dlpLongRunningTest.php
@@ -15,11 +15,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
namespace Google\Cloud\Samples\Dlp;
+use Google\Cloud\Dlp\V2\DlpJob;
+use Google\Cloud\Dlp\V2\DlpJob\JobState;
use Google\Cloud\TestUtils\TestTrait;
use PHPUnit\Framework\TestCase;
+use Prophecy\Argument;
+use Prophecy\PhpUnit\ProphecyTrait;
+use Google\Cloud\Dlp\V2\DlpServiceClient;
+use Google\Cloud\Dlp\V2\InfoType;
+use Google\Cloud\Dlp\V2\InfoTypeStats;
+use Google\Cloud\Dlp\V2\InspectDataSourceDetails;
+use Google\Cloud\Dlp\V2\InspectDataSourceDetails\Result;
+use Google\Cloud\PubSub\Message;
use Google\Cloud\PubSub\PubSubClient;
+use Google\Cloud\PubSub\Subscription;
+use Google\Cloud\PubSub\Topic;
/**
* Unit Tests for dlp commands.
@@ -27,6 +40,7 @@
class dlpLongRunningTest extends TestCase
{
use TestTrait;
+ use ProphecyTrait;
private static $dataset = 'integration_tests_dlp';
private static $table = 'harmful';
@@ -82,15 +96,106 @@ public function testInspectGCS()
{
$bucketName = $this->requireEnv('GOOGLE_STORAGE_BUCKET');
$objectName = 'dlp/harmful.csv';
+ $topicId = self::$topic->name();
+ $subscriptionId = self::$subscription->name();
- $output = $this->runFunctionSnippet('inspect_gcs', [
- self::$projectId,
- self::$topic->name(),
- self::$subscription->name(),
- $bucketName,
- $objectName,
- ]);
- $this->assertStringContainsString('PERSON_NAME', $output);
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $createDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/job-name-123')
+ ->setState(JobState::PENDING);
+
+ $getDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/job-name-123')
+ ->setState(JobState::DONE)
+ ->setInspectDetails((new InspectDataSourceDetails())
+ ->setResult((new Result())
+ ->setInfoTypeStats([
+ (new InfoTypeStats())
+ ->setInfoType((new InfoType())->setName('PERSON_NAME'))
+ ->setCount(3),
+ (new InfoTypeStats())
+ ->setInfoType((new InfoType())->setName('CREDIT_CARD_NUMBER'))
+ ->setCount(3)
+ ])));
+
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($createDlpJobResponse);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($getDlpJobResponse);
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic($topicId)
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . $topicId);
+
+ $topicMock->subscription($subscriptionId)
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/job-name-123']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $sampleFile = __DIR__ . '/../src/inspect_gcs.php';
+ $tmpFileName = basename($sampleFile, '.php') . '_temp';
+ $tmpFilePath = __DIR__ . '/../src/' . $tmpFileName . '.php';
+
+ $fileContent = file_get_contents($sampleFile);
+ $replacements = [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ 'inspect_gcs' => $tmpFileName
+ ];
+ $fileContent = strtr($fileContent, $replacements);
+ $tmpFile = file_put_contents(
+ $tmpFilePath,
+ $fileContent
+ );
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+
+ // Call the method under test
+ $output = $this->runFunctionSnippet($tmpFileName, [
+ self::$projectId,
+ $topicId,
+ $subscriptionId,
+ $bucketName,
+ $objectName,
+ ]);
+
+ // delete topic , subscription , and temp file
+ unlink($tmpFilePath);
+
+ // Assert the expected behavior or outcome
+ $this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
+ $this->assertStringContainsString('infoType PERSON_NAME', $output);
+ $this->assertStringContainsString('infoType CREDIT_CARD_NUMBER', $output);
}
public function testNumericalStats()
diff --git a/dlp/test/dlpTest.php b/dlp/test/dlpTest.php
index 36e0bca185..38c4d63318 100644
--- a/dlp/test/dlpTest.php
+++ b/dlp/test/dlpTest.php
@@ -30,6 +30,20 @@
use Google\Cloud\Dlp\V2\InfoTypeStats;
use Google\Cloud\Dlp\V2\InspectDataSourceDetails;
use Google\Cloud\Dlp\V2\InspectDataSourceDetails\Result;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KAnonymityResult;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KAnonymityResult\KAnonymityEquivalenceClass;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KAnonymityResult\KAnonymityHistogramBucket;
+use Google\Cloud\Dlp\V2\Value;
+use Google\Cloud\Dlp\V2\HybridInspectResponse;
+use Google\Cloud\Dlp\V2\HybridOptions;
+use Google\Cloud\Dlp\V2\InspectConfig;
+use Google\Cloud\Dlp\V2\InspectJobConfig;
+use Google\Cloud\Dlp\V2\JobTrigger;
+use Google\Cloud\Dlp\V2\JobTrigger\Status;
+use Google\Cloud\Dlp\V2\JobTrigger\Trigger;
+use Google\Cloud\Dlp\V2\Manual;
+use Google\Cloud\Dlp\V2\StorageConfig;
/**
* Unit Tests for dlp commands.
@@ -1082,4 +1096,231 @@ public function testDeidentifyCloudStorage()
$this->assertStringContainsString('infoType PERSON_NAME', $output);
$this->assertStringContainsString('infoType EMAIL_ADDRESS', $output);
}
+
+ public function testDeidentifyReplaceInfotype()
+ {
+ $inputString = 'Please call Steve Smith. His number is (555) 253-0000.';
+ $output = $this->runFunctionSnippet('deidentify_replace_infotype', [
+ self::$projectId,
+ $inputString
+ ]);
+ $this->assertStringContainsString('[PHONE_NUMBER]', $output);
+ $this->assertStringContainsString('[PERSON_NAME]', $output);
+ }
+
+ public function testKAnonymityWithEntityId()
+ {
+ $datasetId = $this->requireEnv('DLP_DATASET_ID');
+ $tableId = $this->requireEnv('DLP_TABLE_ID');
+
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $createDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/job-name-123')
+ ->setState(JobState::PENDING);
+
+ $getDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/job-name-123')
+ ->setState(JobState::DONE)
+ ->setRiskDetails((new AnalyzeDataSourceRiskDetails())
+ ->setKAnonymityResult((new KAnonymityResult())
+ ->setEquivalenceClassHistogramBuckets([(new KAnonymityHistogramBucket())
+ ->setEquivalenceClassSizeLowerBound(1)
+ ->setEquivalenceClassSizeUpperBound(1)
+ ->setBucketValues([
+ (new KAnonymityEquivalenceClass())
+ ->setQuasiIdsValues([(new Value())
+ ->setStringValue('{"stringValue":"[\"19\",\"8291 3627 8250 1234\"]"}')])
+ ->setEquivalenceClassSize(1),
+ (new KAnonymityEquivalenceClass())
+ ->setQuasiIdsValues([(new Value())
+ ->setStringValue('{"stringValue":"[\"27\",\"4231 5555 6781 9876\"]"}')])
+ ->setEquivalenceClassSize(1)
+
+ ])])
+ )
+ );
+
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($createDlpJobResponse);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($getDlpJobResponse);
+
+ // Creating a temp file for testing.
+ $sampleFile = __DIR__ . '/../src/k_anonymity_with_entity_id.php';
+ $tmpFileName = basename($sampleFile, '.php') . '_temp';
+ $tmpFilePath = __DIR__ . '/../src/' . $tmpFileName . '.php';
+
+ $fileContent = file_get_contents($sampleFile);
+ $replacements = [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ 'k_anonymity_with_entity_id' => $tmpFileName
+ ];
+ $fileContent = strtr($fileContent, $replacements);
+ $tmpFile = file_put_contents(
+ $tmpFilePath,
+ $fileContent,
+ );
+ global $dlp;
+
+ $dlp = $dlpServiceClientMock->reveal();
+
+ // Call the method under test
+ $output = $this->runFunctionSnippet($tmpFileName, [
+ self::$projectId,
+ $datasetId,
+ $tableId,
+ ['Age', 'Mystery']
+ ]);
+ // delete temp file
+ unlink($tmpFilePath);
+
+ // Assert the expected behavior or outcome
+ $this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
+ $this->assertStringContainsString('Bucket size range: [1, 1]', $output);
+ }
+
+ public function create_hybrid_job_trigger(
+ string $triggerId,
+ string $displayName,
+ string $description
+ ): string {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // Create the inspectConfig object.
+ $inspectConfig = (new InspectConfig())
+ ->setInfoTypes([
+ (new InfoType())
+ ->setName('PERSON_NAME'),
+ (new InfoType())
+ ->setName('PHONE_NUMBER')
+ ])
+ ->setIncludeQuote(true);
+
+ $storageConfig = (new StorageConfig())
+ ->setHybridOptions((new HybridOptions())
+ ->setRequiredFindingLabelKeys(
+ ['appointment-bookings-comments']
+ )
+ ->setLabels([
+ 'env' => 'prod'
+ ]));
+
+ // Construct the insJobConfig object.
+ $inspectJobConfig = (new InspectJobConfig())
+ ->setInspectConfig($inspectConfig)
+ ->setStorageConfig($storageConfig);
+
+ // Create triggers
+ $triggerObject = (new Trigger())
+ ->setManual(new Manual());
+
+ // ----- Construct trigger object -----
+ $jobTriggerObject = (new JobTrigger())
+ ->setTriggers([$triggerObject])
+ ->setInspectJob($inspectJobConfig)
+ ->setStatus(Status::HEALTHY)
+ ->setDisplayName($displayName)
+ ->setDescription($description);
+
+ // Run trigger creation request
+ $parent = 'projects/' . self::$projectId . '/locations/global';
+ $trigger = $dlp->createJobTrigger($parent, $jobTriggerObject, [
+ 'triggerId' => $triggerId
+ ]);
+
+ return $trigger->getName();
+ }
+
+ public function testInspectSendDataToHybridJobTrigger()
+ {
+ $displayName = uniqid('My trigger display name ');
+ $description = uniqid('My trigger description ');
+ $triggerId = uniqid('my-php-test-trigger-');
+ $string = 'My email is test@example.org';
+
+ $fullTriggerId = $this->create_hybrid_job_trigger(
+ $triggerId,
+ $displayName,
+ $description
+ );
+
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $getDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::DONE)
+ ->setInspectDetails((new InspectDataSourceDetails())
+ ->setResult((new Result())
+ ->setInfoTypeStats([
+ (new InfoTypeStats())
+ ->setInfoType((new InfoType())->setName('PERSON_NAME'))
+ ->setCount(13),
+ (new InfoTypeStats())
+ ->setInfoType((new InfoType())->setName('PHONE_NUMBER'))
+ ->setCount(5)
+ ])));
+
+ $dlpServiceClientMock
+ ->activateJobTrigger($fullTriggerId)
+ ->shouldBeCalled()
+ ->willReturn($getDlpJobResponse);
+
+ $dlpServiceClientMock
+ ->listDlpJobs(Argument::any(), Argument::type('array'))
+ ->willReturn([$getDlpJobResponse]);
+
+ $dlpServiceClientMock
+ ->hybridInspectJobTrigger(Argument::any(), Argument::type('array'))
+ ->shouldBeCalledTimes(1)
+ ->willReturn(new HybridInspectResponse());
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($getDlpJobResponse);
+
+ // Creating a temp file for testing.
+ $sampleFile = __DIR__ . '/../src/inspect_send_data_to_hybrid_job_trigger.php';
+ $tmpFileName = basename($sampleFile, '.php') . '_temp';
+ $tmpFilePath = __DIR__ . '/../src/' . $tmpFileName . '.php';
+
+ $fileContent = file_get_contents($sampleFile);
+ $replacements = [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ 'inspect_send_data_to_hybrid_job_trigger' => $tmpFileName
+ ];
+ $fileContent = strtr($fileContent, $replacements);
+ $tmpFile = file_put_contents(
+ $tmpFilePath,
+ $fileContent
+ );
+ global $dlp;
+
+ $dlp = $dlpServiceClientMock->reveal();
+
+ $output = $this->runFunctionSnippet($tmpFileName, [
+ self::$projectId,
+ $triggerId,
+ $string
+ ]);
+
+ // delete a temp file.
+ unlink($tmpFilePath);
+
+ $this->assertStringContainsString('projects/' . self::$projectId . '/dlpJobs', $output);
+ $this->assertStringContainsString('infoType PERSON_NAME', $output);
+ $this->assertStringContainsString('infoType PHONE_NUMBER', $output);
+
+ $output = $this->runFunctionSnippet('delete_trigger', [
+ self::$projectId,
+ $triggerId
+ ]);
+ $this->assertStringContainsString('Successfully deleted trigger ' . $fullTriggerId, $output);
+ }
}
From c4da9944c604ddb3bfc6f31eb5bebef4bd7c8fc2 Mon Sep 17 00:00:00 2001
From: Patti Shin
Date: Thu, 24 Aug 2023 18:25:48 -0700
Subject: [PATCH 067/285] feat: initial commit of run mc php nginx sample
(#1901)
* feat: initial commit of run mc php nginx sample
* chore: upgrade texttospeech samples to new surface (#1880)
* Revert "chore: upgrade texttospeech samples to new surface (#1880)" (#1902)
This reverts commit 18c687234b2c72b57ea7503fb4806df701308e26.
* test: update php mc test and check deployment logs
* test: updating test and clean up
* chore: clean up
* refactor: rename test
* Update run/multi-container/hello-php-nginx-sample/nginx/nginx.conf
Co-authored-by: Julien Breux
* Update run/multi-container/hello-php-nginx-sample/Makefile
Co-authored-by: Julien Breux
* fix: flip container deps
* Update run/multi-container/hello-php-nginx-sample/php-app/Dockerfile
Co-authored-by: Adam Ross
* Update run/multi-container/hello-php-nginx-sample/php-app/opcache.ini
Co-authored-by: Adam Ross
* Update run/multi-container/hello-php-nginx-sample/README.md
Co-authored-by: Adam Ross
* refactor: updating with suggestions (updating readme, Cloud Run memory limit updates, rm makefile, add composer)
* fix: resolve snippet-bot failures about lack of product name
* refactor: update .ini and readme with concurrency/memory info
* chore: clean up readme
* refactor: updating comment about dockerfile context
---------
Co-authored-by: Brent Shaffer
Co-authored-by: Yash Sahu <54198301+yash30201@users.noreply.github.com>
Co-authored-by: Julien Breux
Co-authored-by: Adam Ross
---
run/README.md | 2 +
.../hello-php-nginx-sample/README.md | 81 +++++++
.../hello-php-nginx-sample/composer.json | 5 +
.../hello-php-nginx-sample/nginx/Dockerfile | 28 +++
.../hello-php-nginx-sample/nginx/index.php | 19 ++
.../hello-php-nginx-sample/nginx/nginx.conf | 49 +++++
.../hello-php-nginx-sample/php-app/Dockerfile | 35 ++++
.../hello-php-nginx-sample/php-app/index.php | 22 ++
.../php-app/opcache.ini | 11 +
.../hello-php-nginx-sample/phpunit.xml.dist | 36 ++++
.../hello-php-nginx-sample/service.yaml | 59 ++++++
.../hello-php-nginx-sample/test/TestCase.php | 198 ++++++++++++++++++
12 files changed, 545 insertions(+)
create mode 100644 run/multi-container/hello-php-nginx-sample/README.md
create mode 100644 run/multi-container/hello-php-nginx-sample/composer.json
create mode 100644 run/multi-container/hello-php-nginx-sample/nginx/Dockerfile
create mode 100644 run/multi-container/hello-php-nginx-sample/nginx/index.php
create mode 100644 run/multi-container/hello-php-nginx-sample/nginx/nginx.conf
create mode 100644 run/multi-container/hello-php-nginx-sample/php-app/Dockerfile
create mode 100644 run/multi-container/hello-php-nginx-sample/php-app/index.php
create mode 100644 run/multi-container/hello-php-nginx-sample/php-app/opcache.ini
create mode 100644 run/multi-container/hello-php-nginx-sample/phpunit.xml.dist
create mode 100644 run/multi-container/hello-php-nginx-sample/service.yaml
create mode 100644 run/multi-container/hello-php-nginx-sample/test/TestCase.php
diff --git a/run/README.md b/run/README.md
index 1fb9a51837..ed7e5fea4d 100644
--- a/run/README.md
+++ b/run/README.md
@@ -10,6 +10,7 @@
| --------------------------------------- | ------------------------ | ------------- |
|[Hello World][helloworld] | Quickstart | [
][run_button_helloworld] |
|[Laravel][laravel] | Deploy Laravel on Cloud Run | -|
+|[Multi-container][multicontainer] | Multi-container samples (i.e nginx) | -|
For more Cloud Run samples beyond PHP, see the main list in the [Cloud Run Samples repository](https://github.com/GoogleCloudPlatform/cloud-run-samples).
@@ -90,4 +91,5 @@ for more information.
[run_deploy]: https://cloud.google.com/run/docs/deploying
[helloworld]: helloworld/
[laravel]: laravel/
+[multicontainer]: multi-container/
[run_button_helloworld]: https://deploy.cloud.run/?dir=run/helloworld
diff --git a/run/multi-container/hello-php-nginx-sample/README.md b/run/multi-container/hello-php-nginx-sample/README.md
new file mode 100644
index 0000000000..be1c8c4685
--- /dev/null
+++ b/run/multi-container/hello-php-nginx-sample/README.md
@@ -0,0 +1,81 @@
+# Deploy simple nginx multi-container service NGINX/PHP-FPM
+
+A Google Cloud Project is required in order to run the sample.
+
+## Enable required APIs
+
+The project should have the following API's enabled:
+
+* Cloud Run
+* Artifact Registry
+
+```bash
+gcloud services enable run.googleapis.com artifactregistry.googleapis.com
+```
+
+## Getting started
+
+Declare the following environment variables.
+```bash
+# References your Google Cloud Project
+export PROJECT_ID=
+# References your Artifact Registry repo name
+export REPO_NAME="default"
+# References your resource location
+export REGION="us-west1"
+# References final Cloud Run multi-contaienr service name
+export MC_SERVICE_NAME="mc-php-example"
+```
+
+1. Authenticate in [gcloud cli](https://cloud.google.com/sdk/gcloud).
+
+```bash
+gcloud auth login
+```
+
+2. Create a repository within [Artifact Registry](https://cloud.google.com/artifact-registry).
+
+```bash
+gcloud artifacts repositories create ${REPO_NAME} --repository-format=docker
+```
+
+3. Build the `nginx` and `hellophp` container images for our multi-container service.
+
+```bash
+# Creating image from the Dockerfile within nginx/ dir.
+gcloud builds submit --tag=${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO_NAME}/nginx ./nginx
+
+# Creating image from the Dockerfile within php-app/ dir.
+gcloud builds submit --tag=${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO_NAME}/php ./php-app
+```
+
+4. Configure the service with the appropriate memory limit.
+
+You will see as you read through `service.yaml`, that the memory limit has been explicitly
+set to `320Mi` due to container concurrency of `1` with a single `fpm` worker.
+See how we got [here](https://cloud.google.com/run/docs/configuring/services/memory-limits#optimizing) and read more about how to [optimize for concurrency](https://cloud.google.com/run/docs/tips/general#optimize_concurrency).
+
+5. Deploy the multi-container service.
+
+From within `service.yaml`, customize the `service.yaml` file with your own project values by replacing
+the following `PROJECT_ID`, `MC_SERVICE_NAME`, `REGION`, and `REPO_NAME`.
+
+Once you've replaced the values, you can deploy from root directory (`hello-php-nginx-sample/`).
+
+```sh
+gcloud run services replace service.yaml
+```
+
+By default, the above command will deploy the following containers into a single service:
+
+* `nginx`: `serving` ingress container (entrypoint)
+* `hellophp`: `application` container
+
+The Cloud Run Multi-container service will default access to port `8080`,
+where `nginx` container will be listening and proxy request over to `hellophp` container at port `9000`.
+
+Verify by using curl to send an authenticated request:
+
+```bash
+curl --header "Authorization: Bearer $(gcloud auth print-identity-token)"
+```
diff --git a/run/multi-container/hello-php-nginx-sample/composer.json b/run/multi-container/hello-php-nginx-sample/composer.json
new file mode 100644
index 0000000000..41d1aef360
--- /dev/null
+++ b/run/multi-container/hello-php-nginx-sample/composer.json
@@ -0,0 +1,5 @@
+{
+ "require": {
+ "google/cloud-run": "^0.6.0"
+ }
+}
diff --git a/run/multi-container/hello-php-nginx-sample/nginx/Dockerfile b/run/multi-container/hello-php-nginx-sample/nginx/Dockerfile
new file mode 100644
index 0000000000..ee5d606a3a
--- /dev/null
+++ b/run/multi-container/hello-php-nginx-sample/nginx/Dockerfile
@@ -0,0 +1,28 @@
+# Copyright 2023 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# [START cloudrun_hello_mc_nginx_dockerfile]
+
+# Context: ./
+# Read more about context: https://docs.docker.com/build/building/context/
+# We assume here that required file paths are getting copied
+# from the perspective of this directory.
+
+FROM nginx:1-alpine
+
+COPY ./nginx.conf /etc/nginx/conf.d
+
+COPY index.php /var/www/html/index.php
+
+# [END cloudrun_hello_mc_nginx_dockerfile]
diff --git a/run/multi-container/hello-php-nginx-sample/nginx/index.php b/run/multi-container/hello-php-nginx-sample/nginx/index.php
new file mode 100644
index 0000000000..945c0cb24a
--- /dev/null
+++ b/run/multi-container/hello-php-nginx-sample/nginx/index.php
@@ -0,0 +1,19 @@
+// Copyright 2023 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+
+
+
+
+ ./php-app
+ ./nginx
+
+
+ ./vendor
+
+
+
+
+
+
+
+ test
+
+
+
+
+
+
+
diff --git a/run/multi-container/hello-php-nginx-sample/service.yaml b/run/multi-container/hello-php-nginx-sample/service.yaml
new file mode 100644
index 0000000000..eef61bffb5
--- /dev/null
+++ b/run/multi-container/hello-php-nginx-sample/service.yaml
@@ -0,0 +1,59 @@
+# Copyright 2023 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# [START cloudrun_mc_hello_php_nginx_mc]
+apiVersion: serving.knative.dev/v1
+kind: Service
+metadata:
+ name: "MC_SERVICE_NAME"
+ labels:
+ cloud.googleapis.com/location: "REGION"
+ annotations:
+ run.googleapis.com/launch-stage: BETA
+ run.googleapis.com/description: sample tutorial service
+ run.googleapis.com/ingress: all
+spec:
+ template:
+ metadata:
+ annotations:
+ run.googleapis.com/execution-environment: gen2
+ # Defines container startup order within multi-container service.
+ # Below requires side-car "hellophp" container to spin up before nginx proxy (entrypoint).
+ # https://cloud.google.com/run/docs/configuring/containers#container-ordering
+ run.googleapis.com/container-dependencies: '{"nginx":["hellophp"]}'
+ spec:
+ containerConcurrency: 1
+ containers:
+ - name: nginx
+ image: "REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/nginx"
+ ports:
+ - name: http1
+ containerPort: 8080
+ resources:
+ limits:
+ cpu: 500m
+ memory: 256Mi
+ - name: hellophp
+ image: "REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/php"
+ env:
+ - name: PORT
+ value: "9000"
+ resources:
+ limits:
+ cpu: 1000m
+ # Explore more how to set memory limits in Cloud Run
+ # https://cloud.google.com/run/docs/tips/general#optimize_concurrency
+ # https://cloud.google.com/run/docs/configuring/services/memory-limits#optimizing
+ memory: 320Mi
+# [END cloudrun_mc_hello_php_nginx_mc]
diff --git a/run/multi-container/hello-php-nginx-sample/test/TestCase.php b/run/multi-container/hello-php-nginx-sample/test/TestCase.php
new file mode 100644
index 0000000000..5d353a7a05
--- /dev/null
+++ b/run/multi-container/hello-php-nginx-sample/test/TestCase.php
@@ -0,0 +1,198 @@
+ self::$region, 'service' => self::$mcServiceName]);
+
+ // Declaring Cloud Build image tags
+ self::$nginxImage = sprintf('%s-docker.pkg.dev/%s/%s/nginx', self::$region, self::$projectId, self::$repoName);
+ self::$appImage = sprintf('%s-docker.pkg.dev/%s/%s/php', self::$region, self::$projectId, self::$repoName);
+ }
+
+ /**
+ * Execute yaml substitution
+ */
+ private static function doYamlSubstitution()
+ {
+ $subCmd = sprintf(
+ 'sed -i -e s/MC_SERVICE_NAME/%s/g -e s/REGION/%s/g -e s/REPO_NAME/%s/g -e s/PROJECT_ID/%s/g service.yaml',
+ self::$mcServiceName,
+ self::$region,
+ self::$repoName,
+ self::$projectId
+ );
+
+ return self::execCmd($subCmd);
+ }
+
+ /**
+ * Build both nginx + hello php container images
+ * Return true/false if image builds were successful
+ */
+ private static function buildImages()
+ {
+ if (false === self::$mcService->build(self::$nginxImage, [], './nginx')) {
+ return false;
+ }
+ if (false === self::$mcService->build(self::$appImage, [], './php-app')) {
+ return false;
+ }
+ }
+
+ /**
+ * Instatiate and build necessary resources
+ * required before multi-container deployment
+ */
+ private static function beforeDeploy()
+ {
+ self::setUpDeploymentVars();
+ self::buildImages();
+ self::doYamlSubstitution();
+
+ // Suppress gcloud prompts during deployment.
+ putenv('CLOUDSDK_CORE_DISABLE_PROMPTS=1');
+ }
+
+ /**
+ * Deploy the Cloud Run services (nginx, php app)
+ */
+ private static function doDeploy()
+ {
+ // Execute multi-container service deployment
+ $mcCmd = sprintf('gcloud run services replace service.yaml --region %s --quiet', self::$region);
+
+ return self::execCmd($mcCmd);
+ }
+
+ /**
+ * Delete a deployed Cloud Run MC service and related images.
+ */
+ private static function doDelete()
+ {
+ self::$mcService->delete();
+ self::$mcService->deleteImage(self::$nginxImage);
+ self::$mcService->deleteImage(self::$appImage);
+ }
+
+ /**
+ * Test that the multi-container is running with both
+ * serving and sidecar running as expected
+ */
+ public function testService()
+ {
+ $baseUri = self::getBaseUri();
+ $mcStatusCmd = sprintf(
+ 'gcloud run services describe %s --region %s --format "value(status.conditions[0].type)"',
+ self::$mcServiceName,
+ self::$region
+ );
+ $mcStatus = self::execCmd($mcStatusCmd);
+
+ if (empty($baseUri) or $mcStatus != 'Ready') {
+ return false;
+ }
+
+ // create middleware
+ $middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($baseUri);
+ $stack = HandlerStack::create();
+ $stack->push($middleware);
+
+ // create the HTTP client
+ $client = new Client([
+ 'handler' => $stack,
+ 'auth' => 'google_auth',
+ 'base_uri' => $baseUri,
+ ]);
+
+ // Check that the page renders default phpinfo html and indications it is the main php app
+ $resp = $client->get('/');
+ $this->assertEquals('200', $resp->getStatusCode());
+ $this->assertStringContainsString('This is main php app. Hello PHP World!', (string) $resp->getBody());
+ }
+
+ /**
+ * Retrieve Cloud Run multi-container service url
+ */
+ public function getBaseUri()
+ {
+ $mcUrlCmd = sprintf(
+ 'gcloud run services describe %s --region %s --format "value(status.url)"',
+ self::$mcServiceName,
+ self::$region
+ );
+ $mcUrl = self::execCmd($mcUrlCmd);
+
+ return $mcUrl;
+ }
+}
From e6661e81b4b27d9786d337091e424dc75cd63e23 Mon Sep 17 00:00:00 2001
From: Patti Shin
Date: Fri, 25 Aug 2023 12:56:29 -0700
Subject: [PATCH 068/285] fix: updates cloud run mc php nginx sample (#1913)
---
.../hello-php-nginx-sample/README.md | 5 ++--
.../hello-php-nginx-sample/php-app/Dockerfile | 25 +++++++++++++------
.../php-app/opcache.ini | 11 --------
.../hello-php-nginx-sample/service.yaml | 4 +--
4 files changed, 23 insertions(+), 22 deletions(-)
delete mode 100644 run/multi-container/hello-php-nginx-sample/php-app/opcache.ini
diff --git a/run/multi-container/hello-php-nginx-sample/README.md b/run/multi-container/hello-php-nginx-sample/README.md
index be1c8c4685..939e894fd3 100644
--- a/run/multi-container/hello-php-nginx-sample/README.md
+++ b/run/multi-container/hello-php-nginx-sample/README.md
@@ -51,10 +51,11 @@ gcloud builds submit --tag=${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO_NAME}/p
4. Configure the service with the appropriate memory limit.
-You will see as you read through `service.yaml`, that the memory limit has been explicitly
-set to `320Mi` due to container concurrency of `1` with a single `fpm` worker.
+You will see as you read through `service.yaml`, that the memory limit has been explicitly set to `335M`. This leaves ~143M for PHP processes after allocating 192M for opcache.
See how we got [here](https://cloud.google.com/run/docs/configuring/services/memory-limits#optimizing) and read more about how to [optimize for concurrency](https://cloud.google.com/run/docs/tips/general#optimize_concurrency).
+**Note:** This sample does not contain extra configuration to tune php-fpm settings to specify the number of workers to correlate with the container concurrency.
+
5. Deploy the multi-container service.
From within `service.yaml`, customize the `service.yaml` file with your own project values by replacing
diff --git a/run/multi-container/hello-php-nginx-sample/php-app/Dockerfile b/run/multi-container/hello-php-nginx-sample/php-app/Dockerfile
index 6ba5fd2263..3f329813c2 100644
--- a/run/multi-container/hello-php-nginx-sample/php-app/Dockerfile
+++ b/run/multi-container/hello-php-nginx-sample/php-app/Dockerfile
@@ -22,14 +22,25 @@
FROM php:8-fpm-alpine
-# Use the default production configuration
-RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
-
-RUN docker-php-ext-install opcache
-
-# COPY php.ini /usr/local/etc/php
-COPY opcache.ini /usr/local/etc/php/conf.d/opcache.ini
+# Configure PHP for Cloud Run.
+# Precompile PHP code with opcache.
+RUN docker-php-ext-install -j "$(nproc)" opcache
+RUN set -ex; \
+ { \
+ echo "; Cloud Run enforces memory & timeouts"; \
+ echo "memory_limit = -1"; \
+ echo "; Configure Opcache for Containers"; \
+ echo "opcache.enable = 1"; \
+ echo "opcache.validate_timestamps = 0"; \
+ echo "opcache.memory_consumption = 192"; \
+ echo "opcache.max_accelerated_files = 10000"; \
+ echo "opcache.max_wasted_percentage = 10"; \
+ echo "opcache.interned_strings_buffer = 16";\
+ } > "$PHP_INI_DIR/conf.d/cloud-run.ini"
COPY . /var/www/html/
+# Use the default production configuration
+RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
+
# [END cloudrun_hello_mc_nginx_app_dockerfile]
diff --git a/run/multi-container/hello-php-nginx-sample/php-app/opcache.ini b/run/multi-container/hello-php-nginx-sample/php-app/opcache.ini
deleted file mode 100644
index d75f772c5f..0000000000
--- a/run/multi-container/hello-php-nginx-sample/php-app/opcache.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-; Configure Cloud Run memory
-memory_limit = -1
-
-; Configure Opcache for containers
-[opcache]
-opcache.enable=1
-opcache.validate_timestamps=0
-opcache.max_accelerated_files=10000
-opcache.memory_consumption=192
-opcache.max_wasted_percentage=10
-opcache.interned_strings_buffer=16
diff --git a/run/multi-container/hello-php-nginx-sample/service.yaml b/run/multi-container/hello-php-nginx-sample/service.yaml
index eef61bffb5..685e25252a 100644
--- a/run/multi-container/hello-php-nginx-sample/service.yaml
+++ b/run/multi-container/hello-php-nginx-sample/service.yaml
@@ -43,7 +43,7 @@ spec:
resources:
limits:
cpu: 500m
- memory: 256Mi
+ memory: 256M
- name: hellophp
image: "REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/php"
env:
@@ -55,5 +55,5 @@ spec:
# Explore more how to set memory limits in Cloud Run
# https://cloud.google.com/run/docs/tips/general#optimize_concurrency
# https://cloud.google.com/run/docs/configuring/services/memory-limits#optimizing
- memory: 320Mi
+ memory: 335M
# [END cloudrun_mc_hello_php_nginx_mc]
From 24de8f1781a84419c1b4dd33ff33500dacc6ace1 Mon Sep 17 00:00:00 2001
From: Tatiane Tosta <91583351+ttosta-google@users.noreply.github.com>
Date: Wed, 30 Aug 2023 17:06:13 +0000
Subject: [PATCH 069/285] chore: update code owners to infra-db-sdk (#1912)
---
.github/blunderbuss.yml | 4 ++--
CODEOWNERS | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/.github/blunderbuss.yml b/.github/blunderbuss.yml
index a0aaa1d312..a5f6f2b49e 100644
--- a/.github/blunderbuss.yml
+++ b/.github/blunderbuss.yml
@@ -8,7 +8,7 @@ assign_issues_by:
- labels:
- 'api: cloudsql'
to:
- - GoogleCloudPlatform/infra-db-dpes
+ - GoogleCloudPlatform/infra-db-sdk
- labels:
- 'api: cloudiot'
to:
@@ -28,7 +28,7 @@ assign_prs_by:
- labels:
- 'api: cloudsql'
to:
- - GoogleCloudPlatform/infra-db-dpes
+ - GoogleCloudPlatform/infra-db-sdk
- labels:
- 'api: cloudiot'
to:
diff --git a/CODEOWNERS b/CODEOWNERS
index 45d901e1f8..d51342f6ae 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -19,7 +19,7 @@
.kokoro @GoogleCloudPlatform/php-admins
/bigtable/**/*.php @GoogleCloudPlatform/cloud-native-db-dpes @GoogleCloudPlatform/php-samples-reviewers
-/cloud_sql/**/*.php @GoogleCloudPlatform/infra-db-dpes @GoogleCloudPlatform/php-samples-reviewers
+/cloud_sql/**/*.php @GoogleCloudPlatform/infra-db-sdk @GoogleCloudPlatform/php-samples-reviewers
/datastore/**/*.php @GoogleCloudPlatform/cloud-native-db-dpes @GoogleCloudPlatform/php-samples-reviewers
/firestore/**/*.php @GoogleCloudPlatform/cloud-native-db-dpes @GoogleCloudPlatform/php-samples-reviewers
/storage/ @GoogleCloudPlatform/cloud-storage-dpe @GoogleCloudPlatform/php-samples-reviewers
From fee6e59a9ef14920b34e9fcefae8e84d8bea6806 Mon Sep 17 00:00:00 2001
From: sameer-crest <129392897+sameer-crest@users.noreply.github.com>
Date: Fri, 1 Sep 2023 04:01:26 +0530
Subject: [PATCH 070/285] feat(dlp): Sample for Inspect BigQuery for sensitive
data with sampling (#1835)
---
dlp/src/inspect_bigquery_with_sampling.php | 178 +++++++++++++
dlp/test/dlpLongRunningTest.php | 106 ++++----
dlp/test/dlpTest.php | 295 ++++++++++++++-------
3 files changed, 433 insertions(+), 146 deletions(-)
create mode 100644 dlp/src/inspect_bigquery_with_sampling.php
diff --git a/dlp/src/inspect_bigquery_with_sampling.php b/dlp/src/inspect_bigquery_with_sampling.php
new file mode 100644
index 0000000000..ca8c911947
--- /dev/null
+++ b/dlp/src/inspect_bigquery_with_sampling.php
@@ -0,0 +1,178 @@
+topic($topicId);
+
+ // Specify the BigQuery table to be inspected.
+ $bigqueryTable = (new BigQueryTable())
+ ->setProjectId($projectId)
+ ->setDatasetId($datasetId)
+ ->setTableId($tableId);
+
+ $bigQueryOptions = (new BigQueryOptions())
+ ->setTableReference($bigqueryTable)
+ ->setRowsLimit(1000)
+ ->setSampleMethod(SampleMethod::RANDOM_START)
+ ->setIdentifyingFields([
+ (new FieldId())
+ ->setName('name')
+ ]);
+
+ $storageConfig = (new StorageConfig())
+ ->setBigQueryOptions($bigQueryOptions);
+
+ // Specify the type of info the inspection will look for.
+ // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
+ $personNameInfoType = (new InfoType())
+ ->setName('PERSON_NAME');
+ $infoTypes = [$personNameInfoType];
+
+ // Specify how the content should be inspected.
+ $inspectConfig = (new InspectConfig())
+ ->setInfoTypes($infoTypes)
+ ->setIncludeQuote(true);
+
+ // Specify the action that is triggered when the job completes.
+ $pubSubAction = (new PublishToPubSub())
+ ->setTopic($topic->name());
+
+ $action = (new Action())
+ ->setPubSub($pubSubAction);
+
+ // Configure the long running job we want the service to perform.
+ $inspectJob = (new InspectJobConfig())
+ ->setInspectConfig($inspectConfig)
+ ->setStorageConfig($storageConfig)
+ ->setActions([$action]);
+
+ // Listen for job notifications via an existing topic/subscription.
+ $subscription = $topic->subscription($subscriptionId);
+
+ // Submit request
+ $parent = "projects/$callingProjectId/locations/global";
+ $job = $dlp->createDlpJob($parent, [
+ 'inspectJob' => $inspectJob
+ ]);
+
+ // Poll Pub/Sub using exponential backoff until job finishes
+ // Consider using an asynchronous execution model such as Cloud Functions
+ $attempt = 1;
+ $startTime = time();
+ do {
+ foreach ($subscription->pull() as $message) {
+ if (
+ isset($message->attributes()['DlpJobName']) &&
+ $message->attributes()['DlpJobName'] === $job->getName()
+ ) {
+ $subscription->acknowledge($message);
+ // Get the updated job. Loop to avoid race condition with DLP API.
+ do {
+ $job = $dlp->getDlpJob($job->getName());
+ } while ($job->getState() == JobState::RUNNING);
+ break 2; // break from parent do while
+ }
+ }
+ printf('Waiting for job to complete' . PHP_EOL);
+ // Exponential backoff with max delay of 60 seconds
+ sleep(min(60, pow(2, ++$attempt)));
+ } while (time() - $startTime < 600); // 10 minute timeout
+
+ // Print finding counts
+ printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
+ switch ($job->getState()) {
+ case JobState::DONE:
+ $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
+ if (count($infoTypeStats) === 0) {
+ printf('No findings.' . PHP_EOL);
+ } else {
+ foreach ($infoTypeStats as $infoTypeStat) {
+ printf(
+ ' Found %s instance(s) of infoType %s' . PHP_EOL,
+ $infoTypeStat->getCount(),
+ $infoTypeStat->getInfoType()->getName()
+ );
+ }
+ }
+ break;
+ case JobState::FAILED:
+ printf('Job %s had errors:' . PHP_EOL, $job->getName());
+ $errors = $job->getErrors();
+ foreach ($errors as $error) {
+ var_dump($error->getDetails());
+ }
+ break;
+ case JobState::PENDING:
+ printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ break;
+ default:
+ printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
+}
+# [END dlp_inspect_bigquery_with_sampling]
+
+// 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/dlp/test/dlpLongRunningTest.php b/dlp/test/dlpLongRunningTest.php
index 81ea7527ae..3f32563a18 100644
--- a/dlp/test/dlpLongRunningTest.php
+++ b/dlp/test/dlpLongRunningTest.php
@@ -63,6 +63,47 @@ public static function tearDownAfterClass(): void
self::$subscription->delete();
}
+ private function writeTempSample(string $sampleName, array $replacements): string
+ {
+ $sampleFile = sprintf('%s/../src/%s.php', __DIR__, $sampleName);
+ $tmpFileName = 'dlp_' . basename($sampleFile, '.php');
+ $tmpFilePath = sys_get_temp_dir() . '/' . $tmpFileName . '.php';
+
+ $fileContent = file_get_contents($sampleFile);
+ $replacements[$sampleName] = $tmpFileName;
+ $fileContent = strtr($fileContent, $replacements);
+
+ $tmpFile = file_put_contents(
+ $tmpFilePath,
+ $fileContent
+ );
+
+ return $tmpFilePath;
+ }
+
+ public function dlpJobResponse()
+ {
+ $createDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::PENDING);
+
+ $result = $this->prophesize(Result::class);
+ $infoTypeStats1 = $this->prophesize(InfoTypeStats::class);
+ $infoTypeStats1->getInfoType()->shouldBeCalled()->willReturn((new InfoType())->setName('PERSON_NAME'));
+ $infoTypeStats1->getCount()->shouldBeCalled()->willReturn(5);
+ $result->getInfoTypeStats()->shouldBeCalled()->willReturn([$infoTypeStats1->reveal()]);
+
+ $inspectDetails = $this->prophesize(InspectDataSourceDetails::class);
+ $inspectDetails->getResult()->shouldBeCalled()->willReturn($result->reveal());
+
+ $getDlpJobResponse = $this->prophesize(DlpJob::class);
+ $getDlpJobResponse->getName()->shouldBeCalled()->willReturn('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812');
+ $getDlpJobResponse->getState()->shouldBeCalled()->willReturn(JobState::DONE);
+ $getDlpJobResponse->getInspectDetails()->shouldBeCalled()->willReturn($inspectDetails->reveal());
+
+ return ['createDlpJob' => $createDlpJobResponse, 'getDlpJob' => $getDlpJobResponse];
+ }
+
public function testInspectDatastore()
{
$kind = 'Person';
@@ -102,31 +143,14 @@ public function testInspectGCS()
// Mock the necessary objects and methods
$dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
- $createDlpJobResponse = (new DlpJob())
- ->setName('projects/' . self::$projectId . '/dlpJobs/job-name-123')
- ->setState(JobState::PENDING);
-
- $getDlpJobResponse = (new DlpJob())
- ->setName('projects/' . self::$projectId . '/dlpJobs/job-name-123')
- ->setState(JobState::DONE)
- ->setInspectDetails((new InspectDataSourceDetails())
- ->setResult((new Result())
- ->setInfoTypeStats([
- (new InfoTypeStats())
- ->setInfoType((new InfoType())->setName('PERSON_NAME'))
- ->setCount(3),
- (new InfoTypeStats())
- ->setInfoType((new InfoType())->setName('CREDIT_CARD_NUMBER'))
- ->setCount(3)
- ])));
-
+ $dlpJobResponse = $this->dlpJobResponse();
$dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
->shouldBeCalled()
- ->willReturn($createDlpJobResponse);
+ ->willReturn($dlpJobResponse['createDlpJob']);
$dlpServiceClientMock->getDlpJob(Argument::any())
->shouldBeCalled()
- ->willReturn($getDlpJobResponse);
+ ->willReturn($dlpJobResponse['getDlpJob']);
$pubSubClientMock = $this->prophesize(PubSubClient::class);
$topicMock = $this->prophesize(Topic::class);
@@ -152,50 +176,42 @@ public function testInspectGCS()
$messageMock->attributes()
->shouldBeCalledTimes(2)
- ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/job-name-123']);
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
$subscriptionMock->acknowledge(Argument::any())
->shouldBeCalled()
->willReturn($messageMock->reveal());
// Creating a temp file for testing.
- $sampleFile = __DIR__ . '/../src/inspect_gcs.php';
- $tmpFileName = basename($sampleFile, '.php') . '_temp';
- $tmpFilePath = __DIR__ . '/../src/' . $tmpFileName . '.php';
+ $callFunction = sprintf(
+ "dlp_inspect_gcs('%s','%s','%s','%s','%s');",
+ self::$projectId,
+ $topicId,
+ $subscriptionId,
+ $bucketName,
+ $objectName,
+ );
- $fileContent = file_get_contents($sampleFile);
- $replacements = [
+ $tmpFile = $this->writeTempSample('inspect_gcs', [
'$dlp = new DlpServiceClient();' => 'global $dlp;',
'$pubsub = new PubSubClient();' => 'global $pubsub;',
- 'inspect_gcs' => $tmpFileName
- ];
- $fileContent = strtr($fileContent, $replacements);
- $tmpFile = file_put_contents(
- $tmpFilePath,
- $fileContent
- );
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
global $dlp;
global $pubsub;
$dlp = $dlpServiceClientMock->reveal();
$pubsub = $pubSubClientMock->reveal();
- // Call the method under test
- $output = $this->runFunctionSnippet($tmpFileName, [
- self::$projectId,
- $topicId,
- $subscriptionId,
- $bucketName,
- $objectName,
- ]);
-
- // delete topic , subscription , and temp file
- unlink($tmpFilePath);
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
// Assert the expected behavior or outcome
$this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
$this->assertStringContainsString('infoType PERSON_NAME', $output);
- $this->assertStringContainsString('infoType CREDIT_CARD_NUMBER', $output);
}
public function testNumericalStats()
diff --git a/dlp/test/dlpTest.php b/dlp/test/dlpTest.php
index 38c4d63318..59921d9365 100644
--- a/dlp/test/dlpTest.php
+++ b/dlp/test/dlpTest.php
@@ -30,6 +30,10 @@
use Google\Cloud\Dlp\V2\InfoTypeStats;
use Google\Cloud\Dlp\V2\InspectDataSourceDetails;
use Google\Cloud\Dlp\V2\InspectDataSourceDetails\Result;
+use Google\Cloud\PubSub\Message;
+use Google\Cloud\PubSub\PubSubClient;
+use Google\Cloud\PubSub\Subscription;
+use Google\Cloud\PubSub\Topic;
use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails;
use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KAnonymityResult;
use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KAnonymityResult\KAnonymityEquivalenceClass;
@@ -53,6 +57,65 @@ class dlpTest extends TestCase
use TestTrait;
use RetryTrait;
use ProphecyTrait;
+ private static $topic;
+ private static $subscription;
+
+ public static function setUpBeforeClass(): void
+ {
+ $uniqueName = sprintf('dlp-%s', microtime(true));
+ $pubsub = new PubSubClient();
+ self::$topic = $pubsub->topic($uniqueName);
+ self::$topic->create();
+ self::$subscription = self::$topic->subscription($uniqueName);
+ self::$subscription->create();
+ }
+
+ public static function tearDownAfterClass(): void
+ {
+ self::$topic->delete();
+ self::$subscription->delete();
+ }
+
+ private function writeTempSample(string $sampleName, array $replacements): string
+ {
+ $sampleFile = sprintf('%s/../src/%s.php', __DIR__, $sampleName);
+ $tmpFileName = 'dlp_' . basename($sampleFile, '.php');
+ $tmpFilePath = sys_get_temp_dir() . '/' . $tmpFileName . '.php';
+
+ $fileContent = file_get_contents($sampleFile);
+ $replacements[$sampleName] = $tmpFileName;
+ $fileContent = strtr($fileContent, $replacements);
+
+ $tmpFile = file_put_contents(
+ $tmpFilePath,
+ $fileContent
+ );
+
+ return $tmpFilePath;
+ }
+
+ public function dlpJobResponse()
+ {
+ $createDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::PENDING);
+
+ $result = $this->prophesize(Result::class);
+ $infoTypeStats1 = $this->prophesize(InfoTypeStats::class);
+ $infoTypeStats1->getInfoType()->shouldBeCalled()->willReturn((new InfoType())->setName('PERSON_NAME'));
+ $infoTypeStats1->getCount()->shouldBeCalled()->willReturn(5);
+ $result->getInfoTypeStats()->shouldBeCalled()->willReturn([$infoTypeStats1->reveal()]);
+
+ $inspectDetails = $this->prophesize(InspectDataSourceDetails::class);
+ $inspectDetails->getResult()->shouldBeCalled()->willReturn($result->reveal());
+
+ $getDlpJobResponse = $this->prophesize(DlpJob::class);
+ $getDlpJobResponse->getName()->shouldBeCalled()->willReturn('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812');
+ $getDlpJobResponse->getState()->shouldBeCalled()->willReturn(JobState::DONE);
+ $getDlpJobResponse->getInspectDetails()->shouldBeCalled()->willReturn($inspectDetails->reveal());
+
+ return ['createDlpJob' => $createDlpJobResponse, 'getDlpJob' => $getDlpJobResponse];
+ }
public function testInspectImageFile()
{
@@ -1033,52 +1096,18 @@ public function testDeidentifyCloudStorage()
$dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
- $createDlpJobResponse = (new DlpJob())
- ->setName('projects/' . self::$projectId . '/dlpJobs/1234')
- ->setState(JobState::PENDING);
-
- $getDlpJobResponse = (new DlpJob())
- ->setName('projects/' . self::$projectId . '/dlpJobs/1234')
- ->setState(JobState::DONE)
- ->setInspectDetails((new InspectDataSourceDetails())
- ->setResult((new Result())
- ->setInfoTypeStats([
- (new InfoTypeStats())
- ->setInfoType((new InfoType())->setName('PERSON_NAME'))
- ->setCount(6),
- (new InfoTypeStats())
- ->setInfoType((new InfoType())->setName('EMAIL_ADDRESS'))
- ->setCount(9)
- ])));
-
+ $dlpJobResponse = $this->dlpJobResponse();
$dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
->shouldBeCalled()
- ->willReturn($createDlpJobResponse);
+ ->willReturn($dlpJobResponse['createDlpJob']);
$dlpServiceClientMock->getDlpJob(Argument::any())
->shouldBeCalled()
- ->willReturn($getDlpJobResponse);
+ ->willReturn($dlpJobResponse['getDlpJob']);
// Creating a temp file for testing.
- $sampleFile = __DIR__ . '/../src/deidentify_cloud_storage.php';
- $tmpFileName = basename($sampleFile, '.php') . '_temp';
- $tmpFilePath = __DIR__ . '/../src/' . $tmpFileName . '.php';
-
- $fileContent = file_get_contents($sampleFile);
- $replacements = [
- '$dlp = new DlpServiceClient();' => 'global $dlp;',
- 'deidentify_cloud_storage' => $tmpFileName
- ];
- $fileContent = strtr($fileContent, $replacements);
- $tmpFile = file_put_contents(
- $tmpFilePath,
- $fileContent
- );
- global $dlp;
-
- $dlp = $dlpServiceClientMock->reveal();
-
- $output = $this->runFunctionSnippet($tmpFileName, [
+ $callFunction = sprintf(
+ "dlp_deidentify_cloud_storage('%s','%s','%s','%s','%s','%s','%s','%s');",
self::$projectId,
$inputgcsPath,
$outgcsPath,
@@ -1087,14 +1116,24 @@ public function testDeidentifyCloudStorage()
$imageRedactTemplateName,
$datasetId,
$tableId
+ );
+
+ $tmpFile = $this->writeTempSample('deidentify_cloud_storage', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
]);
+ global $dlp;
- // delete a temp file.
- unlink($tmpFilePath);
+ $dlp = $dlpServiceClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
$this->assertStringContainsString('projects/' . self::$projectId . '/dlpJobs', $output);
$this->assertStringContainsString('infoType PERSON_NAME', $output);
- $this->assertStringContainsString('infoType EMAIL_ADDRESS', $output);
}
public function testDeidentifyReplaceInfotype()
@@ -1151,33 +1190,27 @@ public function testKAnonymityWithEntityId()
->willReturn($getDlpJobResponse);
// Creating a temp file for testing.
- $sampleFile = __DIR__ . '/../src/k_anonymity_with_entity_id.php';
- $tmpFileName = basename($sampleFile, '.php') . '_temp';
- $tmpFilePath = __DIR__ . '/../src/' . $tmpFileName . '.php';
+ $callFunction = sprintf(
+ "dlp_k_anonymity_with_entity_id('%s','%s','%s',%s);",
+ self::$projectId,
+ $datasetId,
+ $tableId,
+ "['Age', 'Mystery']"
+ );
- $fileContent = file_get_contents($sampleFile);
- $replacements = [
+ $tmpFile = $this->writeTempSample('k_anonymity_with_entity_id', [
'$dlp = new DlpServiceClient();' => 'global $dlp;',
- 'k_anonymity_with_entity_id' => $tmpFileName
- ];
- $fileContent = strtr($fileContent, $replacements);
- $tmpFile = file_put_contents(
- $tmpFilePath,
- $fileContent,
- );
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
global $dlp;
$dlp = $dlpServiceClientMock->reveal();
- // Call the method under test
- $output = $this->runFunctionSnippet($tmpFileName, [
- self::$projectId,
- $datasetId,
- $tableId,
- ['Age', 'Mystery']
- ]);
- // delete temp file
- unlink($tmpFilePath);
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
// Assert the expected behavior or outcome
$this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
@@ -1252,29 +1285,16 @@ public function testInspectSendDataToHybridJobTrigger()
// Mock the necessary objects and methods
$dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
-
- $getDlpJobResponse = (new DlpJob())
- ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
- ->setState(JobState::DONE)
- ->setInspectDetails((new InspectDataSourceDetails())
- ->setResult((new Result())
- ->setInfoTypeStats([
- (new InfoTypeStats())
- ->setInfoType((new InfoType())->setName('PERSON_NAME'))
- ->setCount(13),
- (new InfoTypeStats())
- ->setInfoType((new InfoType())->setName('PHONE_NUMBER'))
- ->setCount(5)
- ])));
+ $dlpJobResponse = $this->dlpJobResponse();
$dlpServiceClientMock
->activateJobTrigger($fullTriggerId)
->shouldBeCalled()
- ->willReturn($getDlpJobResponse);
+ ->willReturn($dlpJobResponse['getDlpJob']);
$dlpServiceClientMock
->listDlpJobs(Argument::any(), Argument::type('array'))
- ->willReturn([$getDlpJobResponse]);
+ ->willReturn([$dlpJobResponse['getDlpJob']]);
$dlpServiceClientMock
->hybridInspectJobTrigger(Argument::any(), Argument::type('array'))
@@ -1283,39 +1303,32 @@ public function testInspectSendDataToHybridJobTrigger()
$dlpServiceClientMock->getDlpJob(Argument::any())
->shouldBeCalled()
- ->willReturn($getDlpJobResponse);
+ ->willReturn($dlpJobResponse['getDlpJob']);
// Creating a temp file for testing.
- $sampleFile = __DIR__ . '/../src/inspect_send_data_to_hybrid_job_trigger.php';
- $tmpFileName = basename($sampleFile, '.php') . '_temp';
- $tmpFilePath = __DIR__ . '/../src/' . $tmpFileName . '.php';
+ $callFunction = sprintf(
+ "dlp_inspect_send_data_to_hybrid_job_trigger('%s','%s','%s');",
+ self::$projectId,
+ $triggerId,
+ $string
+ );
- $fileContent = file_get_contents($sampleFile);
- $replacements = [
+ $tmpFile = $this->writeTempSample('inspect_send_data_to_hybrid_job_trigger', [
'$dlp = new DlpServiceClient();' => 'global $dlp;',
- 'inspect_send_data_to_hybrid_job_trigger' => $tmpFileName
- ];
- $fileContent = strtr($fileContent, $replacements);
- $tmpFile = file_put_contents(
- $tmpFilePath,
- $fileContent
- );
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
global $dlp;
$dlp = $dlpServiceClientMock->reveal();
- $output = $this->runFunctionSnippet($tmpFileName, [
- self::$projectId,
- $triggerId,
- $string
- ]);
-
- // delete a temp file.
- unlink($tmpFilePath);
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
$this->assertStringContainsString('projects/' . self::$projectId . '/dlpJobs', $output);
$this->assertStringContainsString('infoType PERSON_NAME', $output);
- $this->assertStringContainsString('infoType PHONE_NUMBER', $output);
$output = $this->runFunctionSnippet('delete_trigger', [
self::$projectId,
@@ -1323,4 +1336,84 @@ public function testInspectSendDataToHybridJobTrigger()
]);
$this->assertStringContainsString('Successfully deleted trigger ' . $fullTriggerId, $output);
}
+
+ public function testInspectBigQueryWithSampling()
+ {
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $dlpJobResponse = $this->dlpJobResponse();
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['createDlpJob']);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['getDlpJob']);
+
+ $topicId = self::$topic->name();
+ $subscriptionId = self::$subscription->name();
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic($topicId)
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . $topicId);
+
+ $topicMock->subscription($subscriptionId)
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_inspect_bigquery_with_sampling('%s','%s','%s','%s','%s','%s');",
+ self::$projectId,
+ $topicId,
+ $subscriptionId,
+ 'bigquery-public-data',
+ 'usa_names',
+ 'usa_1910_current'
+ );
+
+ $tmpFile = $this->writeTempSample('inspect_bigquery_with_sampling', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ // Assert the expected behavior or outcome
+ $this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
+ $this->assertStringContainsString('infoType PERSON_NAME', $output);
+ }
}
From 338fab35a356fecfb70823b1b231a9a069e1716a Mon Sep 17 00:00:00 2001
From: sameer-crest <129392897+sameer-crest@users.noreply.github.com>
Date: Fri, 1 Sep 2023 21:15:57 +0530
Subject: [PATCH 071/285] feat(dlp): Sample for inspect GCS, BigQuery, and
Datastore send to scc (#1867)
---
dlp/README.md | 62 +++++++
dlp/src/inspect_bigquery_send_to_scc.php | 147 +++++++++++++++
dlp/src/inspect_datastore_send_to_scc.php | 145 +++++++++++++++
dlp/src/inspect_gcs_send_to_scc.php | 140 +++++++++++++++
dlp/src/inspect_gcs_with_sampling.php | 166 +++++++++++++++++
dlp/test/dlpTest.php | 206 ++++++++++++++++++++++
6 files changed, 866 insertions(+)
create mode 100644 dlp/src/inspect_bigquery_send_to_scc.php
create mode 100644 dlp/src/inspect_datastore_send_to_scc.php
create mode 100644 dlp/src/inspect_gcs_send_to_scc.php
create mode 100644 dlp/src/inspect_gcs_with_sampling.php
diff --git a/dlp/README.md b/dlp/README.md
index b7e1e59abd..b5c09d3157 100644
--- a/dlp/README.md
+++ b/dlp/README.md
@@ -45,6 +45,68 @@ This simple command-line application demonstrates how to invoke
See the [DLP Documentation](https://cloud.google.com/dlp/docs/inspecting-text) for more information.
+## Testing
+
+### Setup
+- Ensure that `GOOGLE_APPLICATION_CREDENTIALS` points to authorized service account credentials file.
+- [Create a Google Cloud Project](https://console.cloud.google.com/projectcreate) and set the `GOOGLE_PROJECT_ID` environment variable.
+ ```
+ export GOOGLE_PROJECT_ID=YOUR_PROJECT_ID
+ ```
+- [Create a Google Cloud Storage bucket](https://console.cloud.google.com/storage) and upload [test.txt](src/test/data/test.txt).
+ - Set the `GOOGLE_STORAGE_BUCKET` environment variable.
+ - Set the `GCS_PATH` environment variable to point to the path for the bucket file.
+ ```
+ export GOOGLE_STORAGE_BUCKET=YOUR_BUCKET
+ export GCS_PATH=gs://GOOGLE_STORAGE_BUCKET/test.txt
+ ```
+- Set the `DLP_DEID_WRAPPED_KEY` environment variable to an AES-256 key encrypted ('wrapped') [with a Cloud Key Management Service (KMS) key](https://cloud.google.com/kms/docs/encrypt-decrypt).
+- Set the `DLP_DEID_KEY_NAME` environment variable to the path-name of the Cloud KMS key you wrapped `DLP_DEID_WRAPPED_KEY` with.
+ ```
+ export DLP_DEID_WRAPPED_KEY=YOUR_ENCRYPTED_AES_256_KEY
+ export DLP_DEID_KEY_NAME=projects/GOOGLE_PROJECT_ID/locations/YOUR_LOCATION/keyRings/YOUR_KEYRING_NAME/cryptoKeys/YOUR_KEY_NAME
+ ```
+- [Create a De-identify templates](https://console.cloud.google.com/security/dlp/create/template;template=deidentifyTemplate)
+ - Create default de-identify template for unstructured file.
+ - Create a de-identify template for structured files.
+ - Create image redaction template for images.
+ ```
+ export DLP_DEIDENTIFY_TEMPLATE=YOUR_DEFAULT_DEIDENTIFY_TEMPLATE
+ export DLP_STRUCTURED_DEIDENTIFY_TEMPLATE=YOUR_STRUCTURED_DEIDENTIFY_TEMPLATE
+ export DLP_IMAGE_REDACT_DEIDENTIFY_TEMPLATE=YOUR_IMAGE_REDACT_TEMPLATE
+ ```
+- Copy and paste the data below into a CSV file and [create a BigQuery table](https://cloud.google.com/bigquery/docs/loading-data-local) from the file:
+ ```$xslt
+ Name,TelephoneNumber,Mystery,Age,Gender
+ James,(567) 890-1234,8291 3627 8250 1234,19,Male
+ Gandalf,(223) 456-7890,4231 5555 6781 9876,27,Male
+ Dumbledore,(313) 337-1337,6291 8765 1095 7629,27,Male
+ Joe,(452) 223-1234,3782 2288 1166 3030,35,Male
+ Marie,(452) 223-1234,8291 3627 8250 1234,35,Female
+ Carrie,(567) 890-1234,2253 5218 4251 4526,35,Female
+ ```
+ Set the `DLP_DATASET_ID` and `DLP_TABLE_ID` environment values.
+ ```
+ export DLP_DATASET_ID=YOUR_BIGQUERY_DATASET_ID
+ export DLP_TABLE_ID=YOUR_TABLE_ID
+ ```
+- [Create a Google Cloud Datastore](https://console.cloud.google.com/datastore) kind and add an entity with properties:
+ ```
+ Email : john@doe.com
+ Person Name : John
+ Phone Number : 343-343-3435
+
+ Email : gary@doe.com
+ Person Name : Gary
+ Phone Number : 343-443-3136
+ ```
+ Provide namespace and kind values.
+ - Set the environment variables `DLP_NAMESPACE_ID` and `DLP_DATASTORE_KIND` with the values provided in above step.
+ ```
+ export DLP_NAMESPACE_ID=YOUR_NAMESPACE_ID
+ export DLP_DATASTORE_KIND=YOUR_DATASTORE_KIND
+ ```
+
## Troubleshooting
### bcmath extension missing
diff --git a/dlp/src/inspect_bigquery_send_to_scc.php b/dlp/src/inspect_bigquery_send_to_scc.php
new file mode 100644
index 0000000000..e7b6a3ec54
--- /dev/null
+++ b/dlp/src/inspect_bigquery_send_to_scc.php
@@ -0,0 +1,147 @@
+setProjectId($projectId)
+ ->setDatasetId($datasetId)
+ ->setTableId($tableId);
+ $bigQueryOptions = (new BigQueryOptions())
+ ->setTableReference($bigqueryTable);
+
+ $storageConfig = (new StorageConfig())
+ ->setBigQueryOptions(($bigQueryOptions));
+
+ // Specify the type of info the inspection will look for.
+ $infoTypes = [
+ (new InfoType())->setName('EMAIL_ADDRESS'),
+ (new InfoType())->setName('PERSON_NAME'),
+ (new InfoType())->setName('LOCATION'),
+ (new InfoType())->setName('PHONE_NUMBER')
+ ];
+
+ // Specify how the content should be inspected.
+ $inspectConfig = (new InspectConfig())
+ ->setMinLikelihood(likelihood::UNLIKELY)
+ ->setLimits((new FindingLimits())
+ ->setMaxFindingsPerRequest(100))
+ ->setInfoTypes($infoTypes)
+ ->setIncludeQuote(true);
+
+ // Specify the action that is triggered when the job completes.
+ $action = (new Action())
+ ->setPublishSummaryToCscc(new PublishSummaryToCscc());
+
+ // Configure the inspection job we want the service to perform.
+ $inspectJobConfig = (new InspectJobConfig())
+ ->setInspectConfig($inspectConfig)
+ ->setStorageConfig($storageConfig)
+ ->setActions([$action]);
+
+ // Send the job creation request and process the response.
+ $parent = "projects/$callingProjectId/locations/global";
+ $job = $dlp->createDlpJob($parent, [
+ 'inspectJob' => $inspectJobConfig
+ ]);
+
+ $numOfAttempts = 10;
+ do {
+ printf('Waiting for job to complete' . PHP_EOL);
+ sleep(10);
+ $job = $dlp->getDlpJob($job->getName());
+ if ($job->getState() == JobState::DONE) {
+ break;
+ }
+ $numOfAttempts--;
+ } while ($numOfAttempts > 0);
+
+ // Print finding counts.
+ printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
+ switch ($job->getState()) {
+ case JobState::DONE:
+ $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
+ if (count($infoTypeStats) === 0) {
+ printf('No findings.' . PHP_EOL);
+ } else {
+ foreach ($infoTypeStats as $infoTypeStat) {
+ printf(
+ ' Found %s instance(s) of infoType %s' . PHP_EOL,
+ $infoTypeStat->getCount(),
+ $infoTypeStat->getInfoType()->getName()
+ );
+ }
+ }
+ break;
+ case JobState::FAILED:
+ printf('Job %s had errors:' . PHP_EOL, $job->getName());
+ $errors = $job->getErrors();
+ foreach ($errors as $error) {
+ var_dump($error->getDetails());
+ }
+ break;
+ case JobState::PENDING:
+ printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ break;
+ default:
+ printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
+}
+# [END dlp_inspect_bigquery_send_to_scc]
+// 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/dlp/src/inspect_datastore_send_to_scc.php b/dlp/src/inspect_datastore_send_to_scc.php
new file mode 100644
index 0000000000..4dbb8ab5d8
--- /dev/null
+++ b/dlp/src/inspect_datastore_send_to_scc.php
@@ -0,0 +1,145 @@
+setKind((new KindExpression())
+ ->setName($kindName))
+ ->setPartitionId((new PartitionId())
+ ->setNamespaceId($namespaceId)
+ ->setProjectId($callingProjectId));
+
+ $storageConfig = (new StorageConfig())
+ ->setDatastoreOptions(($datastoreOptions));
+
+ // Specify the type of info the inspection will look for.
+ $infoTypes = [
+ (new InfoType())->setName('EMAIL_ADDRESS'),
+ (new InfoType())->setName('PERSON_NAME'),
+ (new InfoType())->setName('LOCATION'),
+ (new InfoType())->setName('PHONE_NUMBER')
+ ];
+
+ // Specify how the content should be inspected.
+ $inspectConfig = (new InspectConfig())
+ ->setMinLikelihood(likelihood::UNLIKELY)
+ ->setLimits((new FindingLimits())
+ ->setMaxFindingsPerRequest(100))
+ ->setInfoTypes($infoTypes)
+ ->setIncludeQuote(true);
+
+ // Specify the action that is triggered when the job completes.
+ $action = (new Action())
+ ->setPublishSummaryToCscc(new PublishSummaryToCscc());
+
+ // Construct inspect job config to run.
+ $inspectJobConfig = (new InspectJobConfig())
+ ->setInspectConfig($inspectConfig)
+ ->setStorageConfig($storageConfig)
+ ->setActions([$action]);
+
+ // Send the job creation request and process the response.
+ $parent = "projects/$callingProjectId/locations/global";
+ $job = $dlp->createDlpJob($parent, [
+ 'inspectJob' => $inspectJobConfig
+ ]);
+
+ $numOfAttempts = 10;
+ do {
+ printf('Waiting for job to complete' . PHP_EOL);
+ sleep(10);
+ $job = $dlp->getDlpJob($job->getName());
+ if ($job->getState() == JobState::DONE) {
+ break;
+ }
+ $numOfAttempts--;
+ } while ($numOfAttempts > 0);
+
+ // Print finding counts.
+ printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
+ switch ($job->getState()) {
+ case JobState::DONE:
+ $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
+ if (count($infoTypeStats) === 0) {
+ printf('No findings.' . PHP_EOL);
+ } else {
+ foreach ($infoTypeStats as $infoTypeStat) {
+ printf(
+ ' Found %s instance(s) of infoType %s' . PHP_EOL,
+ $infoTypeStat->getCount(),
+ $infoTypeStat->getInfoType()->getName()
+ );
+ }
+ }
+ break;
+ case JobState::FAILED:
+ printf('Job %s had errors:' . PHP_EOL, $job->getName());
+ $errors = $job->getErrors();
+ foreach ($errors as $error) {
+ var_dump($error->getDetails());
+ }
+ break;
+ case JobState::PENDING:
+ printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ break;
+ default:
+ printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
+}
+# [END dlp_inspect_datastore_send_to_scc]
+// 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/dlp/src/inspect_gcs_send_to_scc.php b/dlp/src/inspect_gcs_send_to_scc.php
new file mode 100644
index 0000000000..5c1e830479
--- /dev/null
+++ b/dlp/src/inspect_gcs_send_to_scc.php
@@ -0,0 +1,140 @@
+setFileSet((new FileSet())
+ ->setUrl($gcsUri));
+
+ $storageConfig = (new StorageConfig())
+ ->setCloudStorageOptions(($cloudStorageOptions));
+
+ // Specify the type of info the inspection will look for.
+ $infoTypes = [
+ (new InfoType())->setName('EMAIL_ADDRESS'),
+ (new InfoType())->setName('PERSON_NAME'),
+ (new InfoType())->setName('LOCATION'),
+ (new InfoType())->setName('PHONE_NUMBER')
+ ];
+
+ // Specify how the content should be inspected.
+ $inspectConfig = (new InspectConfig())
+ ->setMinLikelihood(likelihood::UNLIKELY)
+ ->setLimits((new FindingLimits())
+ ->setMaxFindingsPerRequest(100))
+ ->setInfoTypes($infoTypes)
+ ->setIncludeQuote(true);
+
+ // Specify the action that is triggered when the job completes.
+ $action = (new Action())
+ ->setPublishSummaryToCscc(new PublishSummaryToCscc());
+
+ // Construct inspect job config to run.
+ $inspectJobConfig = (new InspectJobConfig())
+ ->setInspectConfig($inspectConfig)
+ ->setStorageConfig($storageConfig)
+ ->setActions([$action]);
+
+ // Send the job creation request and process the response.
+ $parent = "projects/$callingProjectId/locations/global";
+ $job = $dlp->createDlpJob($parent, [
+ 'inspectJob' => $inspectJobConfig
+ ]);
+
+ $numOfAttempts = 10;
+ do {
+ printf('Waiting for job to complete' . PHP_EOL);
+ sleep(10);
+ $job = $dlp->getDlpJob($job->getName());
+ if ($job->getState() == JobState::DONE) {
+ break;
+ }
+ $numOfAttempts--;
+ } while ($numOfAttempts > 0);
+
+ // Print finding counts.
+ printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
+ switch ($job->getState()) {
+ case JobState::DONE:
+ $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
+ if (count($infoTypeStats) === 0) {
+ printf('No findings.' . PHP_EOL);
+ } else {
+ foreach ($infoTypeStats as $infoTypeStat) {
+ printf(
+ ' Found %s instance(s) of infoType %s' . PHP_EOL,
+ $infoTypeStat->getCount(),
+ $infoTypeStat->getInfoType()->getName()
+ );
+ }
+ }
+ break;
+ case JobState::FAILED:
+ printf('Job %s had errors:' . PHP_EOL, $job->getName());
+ $errors = $job->getErrors();
+ foreach ($errors as $error) {
+ var_dump($error->getDetails());
+ }
+ break;
+ case JobState::PENDING:
+ printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ break;
+ default:
+ printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
+}
+# [END dlp_inspect_gcs_send_to_scc]
+// 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/dlp/src/inspect_gcs_with_sampling.php b/dlp/src/inspect_gcs_with_sampling.php
new file mode 100644
index 0000000000..173947d32c
--- /dev/null
+++ b/dlp/src/inspect_gcs_with_sampling.php
@@ -0,0 +1,166 @@
+topic($topicId);
+
+ // Construct the items to be inspected.
+ $cloudStorageOptions = (new CloudStorageOptions())
+ ->setFileSet((new FileSet())
+ ->setUrl($gcsUri))
+ ->setBytesLimitPerFile(200)
+ ->setFilesLimitPercent(90)
+ ->setSampleMethod(SampleMethod::RANDOM_START);
+
+ $storageConfig = (new StorageConfig())
+ ->setCloudStorageOptions($cloudStorageOptions);
+
+ // Specify the type of info the inspection will look for.
+ $phoneNumberInfoType = (new InfoType())
+ ->setName('PHONE_NUMBER');
+ $emailAddressInfoType = (new InfoType())
+ ->setName('EMAIL_ADDRESS');
+ $cardNumberInfoType = (new InfoType())
+ ->setName('CREDIT_CARD_NUMBER');
+ $infoTypes = [$phoneNumberInfoType, $emailAddressInfoType, $cardNumberInfoType];
+
+ // Specify how the content should be inspected.
+ $inspectConfig = (new InspectConfig())
+ ->setInfoTypes($infoTypes)
+ ->setIncludeQuote(true);
+
+ // Construct the action to run when job completes.
+ $action = (new Action())
+ ->setPubSub((new PublishToPubSub())
+ ->setTopic($topic->name()));
+
+ // Construct inspect job config to run.
+ $inspectJob = (new InspectJobConfig())
+ ->setInspectConfig($inspectConfig)
+ ->setStorageConfig($storageConfig)
+ ->setActions([$action]);
+
+ // Listen for job notifications via an existing topic/subscription.
+ $subscription = $topic->subscription($subscriptionId);
+
+ // Submit request.
+ $parent = "projects/$callingProjectId/locations/global";
+ $job = $dlp->createDlpJob($parent, [
+ 'inspectJob' => $inspectJob
+ ]);
+
+ // Poll Pub/Sub using exponential backoff until job finishes.
+ // Consider using an asynchronous execution model such as Cloud Functions.
+ $attempt = 1;
+ $startTime = time();
+ do {
+ foreach ($subscription->pull() as $message) {
+ if (
+ isset($message->attributes()['DlpJobName']) &&
+ $message->attributes()['DlpJobName'] === $job->getName()
+ ) {
+ $subscription->acknowledge($message);
+ // Get the updated job. Loop to avoid race condition with DLP API.
+ do {
+ $job = $dlp->getDlpJob($job->getName());
+ } while ($job->getState() == JobState::RUNNING);
+ break 2; // break from parent do while.
+ }
+ }
+ printf('Waiting for job to complete' . PHP_EOL);
+ // Exponential backoff with max delay of 60 seconds.
+ sleep(min(60, pow(2, ++$attempt)));
+ } while (time() - $startTime < 600); // 10 minute timeout.
+
+ // Print finding counts.
+ printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
+ switch ($job->getState()) {
+ case JobState::DONE:
+ $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
+ if (count($infoTypeStats) === 0) {
+ printf('No findings.' . PHP_EOL);
+ } else {
+ foreach ($infoTypeStats as $infoTypeStat) {
+ printf(
+ ' Found %s instance(s) of infoType %s' . PHP_EOL,
+ $infoTypeStat->getCount(),
+ $infoTypeStat->getInfoType()->getName()
+ );
+ }
+ }
+ break;
+ case JobState::FAILED:
+ printf('Job %s had errors:' . PHP_EOL, $job->getName());
+ $errors = $job->getErrors();
+ foreach ($errors as $error) {
+ var_dump($error->getDetails());
+ }
+ break;
+ case JobState::PENDING:
+ printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ break;
+ default:
+ printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
+}
+# [END dlp_inspect_gcs_with_sampling]
+
+// 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/dlp/test/dlpTest.php b/dlp/test/dlpTest.php
index 59921d9365..c839ae6504 100644
--- a/dlp/test/dlpTest.php
+++ b/dlp/test/dlpTest.php
@@ -1416,4 +1416,210 @@ public function testInspectBigQueryWithSampling()
$this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
$this->assertStringContainsString('infoType PERSON_NAME', $output);
}
+
+ public function testInspectGcsWithSampling()
+ {
+ $gcsUri = $this->requireEnv('GCS_PATH');
+
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $dlpJobResponse = $this->dlpJobResponse();
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['createDlpJob']);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['getDlpJob']);
+
+ $topicId = self::$topic->name();
+ $subscriptionId = self::$subscription->name();
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic($topicId)
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . $topicId);
+
+ $topicMock->subscription($subscriptionId)
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_inspect_gcs_with_sampling('%s','%s','%s','%s');",
+ self::$projectId,
+ $gcsUri,
+ $topicId,
+ $subscriptionId
+ );
+
+ $tmpFile = $this->writeTempSample('inspect_gcs_with_sampling', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ // Assert the expected behavior or outcome
+ $this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
+ $this->assertStringContainsString('infoType PERSON_NAME', $output);
+ }
+
+ public function testInspectGcsSendToScc()
+ {
+ $gcsPath = $this->requireEnv('GCS_PATH');
+
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $dlpJobResponse = $this->dlpJobResponse();
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['createDlpJob']);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['getDlpJob']);
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_inspect_gcs_send_to_scc('%s','%s');",
+ self::$projectId,
+ $gcsPath
+ );
+
+ $tmpFile = $this->writeTempSample('inspect_gcs_send_to_scc', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
+ global $dlp;
+
+ $dlp = $dlpServiceClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ $this->assertStringContainsString('projects/' . self::$projectId . '/dlpJobs', $output);
+ $this->assertStringContainsString('infoType PERSON_NAME', $output);
+ }
+
+ public function testInspectDatastoreSendToScc()
+ {
+ $datastorename = $this->requireEnv('DLP_DATASTORE_KIND');
+ $namespaceId = $this->requireEnv('DLP_NAMESPACE_ID');
+
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $dlpJobResponse = $this->dlpJobResponse();
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['createDlpJob']);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['getDlpJob']);
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_inspect_datastore_send_to_scc('%s','%s','%s');",
+ self::$projectId,
+ $datastorename,
+ $namespaceId
+ );
+
+ $tmpFile = $this->writeTempSample('inspect_datastore_send_to_scc', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
+ global $dlp;
+
+ $dlp = $dlpServiceClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ $this->assertStringContainsString('projects/' . self::$projectId . '/dlpJobs', $output);
+ $this->assertStringContainsString('infoType PERSON_NAME', $output);
+ }
+
+ public function testInspectBigquerySendToScc()
+ {
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $dlpJobResponse = $this->dlpJobResponse();
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['createDlpJob']);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['getDlpJob']);
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_inspect_bigquery_send_to_scc('%s','%s','%s','%s');",
+ self::$projectId,
+ 'bigquery-public-data',
+ 'usa_names',
+ 'usa_1910_current'
+ );
+
+ $tmpFile = $this->writeTempSample('inspect_bigquery_send_to_scc', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
+
+ global $dlp;
+
+ $dlp = $dlpServiceClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ $this->assertStringContainsString('projects/' . self::$projectId . '/dlpJobs', $output);
+ $this->assertStringContainsString('infoType PERSON_NAME', $output);
+ }
}
From b4e44899eb9a3a52472202caac9de6a2704b6ce9 Mon Sep 17 00:00:00 2001
From: minherz
Date: Tue, 12 Sep 2023 15:13:21 +0000
Subject: [PATCH 072/285] fix: update write log sample to setup severity
(#1915)
---
logging/src/write_log.php | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/logging/src/write_log.php b/logging/src/write_log.php
index 889c4a910a..68e2a3e17d 100644
--- a/logging/src/write_log.php
+++ b/logging/src/write_log.php
@@ -19,6 +19,7 @@
// [START logging_write_log_entry]
use Google\Cloud\Logging\LoggingClient;
+use Google\Cloud\Logging\Logger;
/** Write a log message via the Stackdriver Logging API.
*
@@ -37,7 +38,9 @@ function write_log($projectId, $loggerName, $message)
]
]
]);
- $entry = $logger->entry($message);
+ $entry = $logger->entry($message, [
+ 'severity' => Logger::INFO
+ ]);
$logger->write($entry);
printf("Wrote a log to a logger '%s'." . PHP_EOL, $loggerName);
}
From fe53920436169c918e6242bf25eb696832e6dcc1 Mon Sep 17 00:00:00 2001
From: sameer-crest <129392897+sameer-crest@users.noreply.github.com>
Date: Wed, 13 Sep 2023 11:35:34 +0530
Subject: [PATCH 073/285] feat(dlp): sample for Stored infoType and Trigger
(#1894)
* Implemented Stored infoType and Trigger
* Removed dlp_delete_stored_infotype region tag
* Resolved
* Applied mocking on stored infotype
* Addressed the review comments
---------
Co-authored-by: Yash Sahu <54198301+yash30201@users.noreply.github.com>
---
dlp/src/create_stored_infotype.php | 90 +++++++++++++++
dlp/src/create_trigger.php | 24 ++--
dlp/src/inspect_with_stored_infotype.php | 93 +++++++++++++++
dlp/src/update_stored_infotype.php | 88 ++++++++++++++
dlp/src/update_trigger.php | 84 ++++++++++++++
dlp/test/data/term-list.txt | 2 +
dlp/test/dlpTest.php | 140 +++++++++++++++++++++++
7 files changed, 509 insertions(+), 12 deletions(-)
create mode 100644 dlp/src/create_stored_infotype.php
create mode 100644 dlp/src/inspect_with_stored_infotype.php
create mode 100644 dlp/src/update_stored_infotype.php
create mode 100644 dlp/src/update_trigger.php
create mode 100644 dlp/test/data/term-list.txt
diff --git a/dlp/src/create_stored_infotype.php b/dlp/src/create_stored_infotype.php
new file mode 100644
index 0000000000..c37853f3ed
--- /dev/null
+++ b/dlp/src/create_stored_infotype.php
@@ -0,0 +1,90 @@
+setTable((new BigQueryTable())
+ ->setDatasetId('samples')
+ ->setProjectId('bigquery-public-data')
+ ->setTableId('github_nested'))
+ ->setField((new FieldId())
+ ->setName('actor'));
+
+ $largeCustomDictionaryConfig = (new LargeCustomDictionaryConfig())
+ // The output path where the custom dictionary containing the GitHub usernames will be stored.
+ ->setOutputPath((new CloudStoragePath())
+ ->setPath($outputgcsPath))
+ ->setBigQueryField($bigQueryField);
+
+ // Configure the StoredInfoType we want the service to perform.
+ $storedInfoTypeConfig = (new StoredInfoTypeConfig())
+ ->setDisplayName($displayName)
+ ->setDescription($description)
+ ->setLargeCustomDictionary($largeCustomDictionaryConfig);
+
+ // Send the stored infoType creation request and process the response.
+ $parent = "projects/$callingProjectId/locations/global";
+ $response = $dlp->createStoredInfoType($parent, $storedInfoTypeConfig, [
+ 'storedInfoTypeId' => $storedInfoTypeId
+ ]);
+
+ // Print results.
+ printf('Successfully created Stored InfoType : %s', $response->getName());
+}
+# [END dlp_create_stored_infotype]
+// 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/dlp/src/create_trigger.php b/dlp/src/create_trigger.php
index a01bc4afd4..cbbc0e2612 100644
--- a/dlp/src/create_trigger.php
+++ b/dlp/src/create_trigger.php
@@ -1,5 +1,4 @@
setSchedule($schedule);
// Create the storageConfig object
- $fileSet = (new CloudStorageOptions_FileSet())
+ $fileSet = (new FileSet())
->setUrl('gs://' . $bucketName . '/*');
$storageOptions = (new CloudStorageOptions())
->setFileSet($fileSet);
// Auto-populate start and end times in order to scan new objects only.
- $timespanConfig = (new StorageConfig_TimespanConfig())
+ $timespanConfig = (new TimespanConfig())
->setEnableAutoPopulationOfTimespanConfig($autoPopulateTimespan);
$storageConfig = (new StorageConfig())
@@ -126,7 +125,8 @@ function create_trigger(
->setDescription($description);
// Run trigger creation request
- $parent = "projects/$callingProjectId/locations/global";
+ // $parent = "projects/$callingProjectId/locations/global";
+ $parent = $dlp->locationName($callingProjectId, 'global');
$trigger = $dlp->createJobTrigger($parent, $jobTriggerObject, [
'triggerId' => $triggerId
]);
diff --git a/dlp/src/inspect_with_stored_infotype.php b/dlp/src/inspect_with_stored_infotype.php
new file mode 100644
index 0000000000..d73770bbbb
--- /dev/null
+++ b/dlp/src/inspect_with_stored_infotype.php
@@ -0,0 +1,93 @@
+setValue($textToInspect);
+
+ // Reference to the existing StoredInfoType to inspect the data.
+ $customInfoType = (new CustomInfoType())
+ ->setInfoType((new InfoType())
+ ->setName('STORED_TYPE'))
+ ->setStoredType((new StoredType())
+ ->setName($storedInfoTypeName));
+
+ // Construct the configuration for the Inspect request.
+ $inspectConfig = (new InspectConfig())
+ ->setCustomInfoTypes([$customInfoType])
+ ->setIncludeQuote(true);
+
+ // Run request.
+ $response = $dlp->inspectContent([
+ 'parent' => $parent,
+ 'inspectConfig' => $inspectConfig,
+ 'item' => $item
+ ]);
+
+ // Print the results.
+ $findings = $response->getResult()->getFindings();
+ if (count($findings) == 0) {
+ printf('No findings.' . PHP_EOL);
+ } else {
+ printf('Findings:' . PHP_EOL);
+ foreach ($findings as $finding) {
+ printf(' Quote: %s' . PHP_EOL, $finding->getQuote());
+ printf(' Info type: %s' . PHP_EOL, $finding->getInfoType()->getName());
+ printf(' Likelihood: %s' . PHP_EOL, Likelihood::name($finding->getLikelihood()));
+ }
+ }
+}
+# [END dlp_inspect_with_stored_infotype]
+// 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/dlp/src/update_stored_infotype.php b/dlp/src/update_stored_infotype.php
new file mode 100644
index 0000000000..22ee174315
--- /dev/null
+++ b/dlp/src/update_stored_infotype.php
@@ -0,0 +1,88 @@
+setUrl($gcsPath);
+
+ // Configuration for a custom dictionary created from a data source of any size
+ $largeCustomDictionaryConfig = (new LargeCustomDictionaryConfig())
+ ->setOutputPath((new CloudStoragePath())
+ ->setPath($outputgcsPath))
+ ->setCloudStorageFileSet($cloudStorageFileSet);
+
+ // Set configuration for stored infoTypes.
+ $storedInfoTypeConfig = (new StoredInfoTypeConfig())
+ ->setLargeCustomDictionary($largeCustomDictionaryConfig);
+
+ // Send the stored infoType creation request and process the response.
+
+ $name = "projects/$callingProjectId/locations/global/storedInfoTypes/" . $storedInfoTypeId;
+ // Set mask to control which fields get updated.
+ // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
+ $fieldMask = (new FieldMask())
+ ->setPaths([
+ 'large_custom_dictionary.cloud_storage_file_set.url'
+ ]);
+
+ // Run request
+ $response = $dlp->updateStoredInfoType($name, [
+ 'config' => $storedInfoTypeConfig,
+ 'updateMask' => $fieldMask
+ ]);
+
+ // Print results
+ printf('Successfully update Stored InforType : %s' . PHP_EOL, $response->getName());
+}
+# [END dlp_update_stored_infotype]
+// 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/dlp/src/update_trigger.php b/dlp/src/update_trigger.php
new file mode 100644
index 0000000000..9a3adc1f8e
--- /dev/null
+++ b/dlp/src/update_trigger.php
@@ -0,0 +1,84 @@
+setInfoTypes([
+ (new InfoType())
+ ->setName('US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER')
+ ])
+ ->setMinLikelihood(Likelihood::LIKELY);
+
+ // Configure the Job Trigger we want the service to perform.
+ $jobTrigger = (new JobTrigger())
+ ->setInspectJob((new InspectJobConfig())
+ ->setInspectConfig($inspectConfig));
+
+ // Specify fields of the jobTrigger resource to be updated when the job trigger is modified.
+ // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
+ $fieldMask = (new FieldMask())
+ ->setPaths([
+ 'inspect_job.inspect_config.info_types',
+ 'inspect_job.inspect_config.min_likelihood'
+ ]);
+
+ // Send the update job trigger request and process the response.
+ $name = "projects/$callingProjectId/locations/global/jobTriggers/" . $jobTriggerName;
+
+ $response = $dlp->updateJobTrigger($name, [
+ 'jobTrigger' => $jobTrigger,
+ 'updateMask' => $fieldMask
+ ]);
+
+ // Print results.
+ printf('Successfully update trigger %s' . PHP_EOL, $response->getName());
+}
+# [END dlp_update_trigger]
+// 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/dlp/test/data/term-list.txt b/dlp/test/data/term-list.txt
new file mode 100644
index 0000000000..e5f7fb187c
--- /dev/null
+++ b/dlp/test/data/term-list.txt
@@ -0,0 +1,2 @@
+test@gmail.com
+gary@example.com
\ No newline at end of file
diff --git a/dlp/test/dlpTest.php b/dlp/test/dlpTest.php
index c839ae6504..a7275bb875 100644
--- a/dlp/test/dlpTest.php
+++ b/dlp/test/dlpTest.php
@@ -26,8 +26,10 @@
use Prophecy\PhpUnit\ProphecyTrait;
use PHPUnitRetry\RetryTrait;
use Google\Cloud\Dlp\V2\DlpServiceClient;
+use Google\Cloud\Dlp\V2\Finding;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InfoTypeStats;
+use Google\Cloud\Dlp\V2\InspectContentResponse;
use Google\Cloud\Dlp\V2\InspectDataSourceDetails;
use Google\Cloud\Dlp\V2\InspectDataSourceDetails\Result;
use Google\Cloud\PubSub\Message;
@@ -43,11 +45,16 @@
use Google\Cloud\Dlp\V2\HybridOptions;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectJobConfig;
+use Google\Cloud\Dlp\V2\InspectResult;
use Google\Cloud\Dlp\V2\JobTrigger;
use Google\Cloud\Dlp\V2\JobTrigger\Status;
use Google\Cloud\Dlp\V2\JobTrigger\Trigger;
+use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\Manual;
use Google\Cloud\Dlp\V2\StorageConfig;
+use Google\Cloud\Dlp\V2\StoredInfoType;
+use Google\Cloud\Dlp\V2\StoredInfoTypeState;
+use Google\Cloud\Dlp\V2\StoredInfoTypeVersion;
/**
* Unit Tests for dlp commands.
@@ -266,6 +273,7 @@ public function testTriggers()
$triggerId = uniqid('my-php-test-trigger-');
$scanPeriod = 1;
$autoPopulateTimespan = true;
+ $maxFindings = 10;
$output = $this->runFunctionSnippet('create_trigger', [
self::$projectId,
@@ -275,6 +283,7 @@ public function testTriggers()
$description,
$scanPeriod,
$autoPopulateTimespan,
+ $maxFindings
]);
$fullTriggerId = sprintf('projects/%s/locations/global/jobTriggers/%s', self::$projectId, $triggerId);
$this->assertStringContainsString('Successfully created trigger ' . $fullTriggerId, $output);
@@ -285,6 +294,12 @@ public function testTriggers()
$this->assertStringContainsString('Description: ' . $description, $output);
$this->assertStringContainsString('Auto-populates timespan config: yes', $output);
+ $updateOutput = $this->runFunctionSnippet('update_trigger', [
+ self::$projectId,
+ $triggerId
+ ]);
+ $this->assertStringContainsString('Successfully update trigger ' . $fullTriggerId, $updateOutput);
+
$output = $this->runFunctionSnippet('delete_trigger', [
self::$projectId,
$triggerId
@@ -1622,4 +1637,129 @@ public function testInspectBigquerySendToScc()
$this->assertStringContainsString('projects/' . self::$projectId . '/dlpJobs', $output);
$this->assertStringContainsString('infoType PERSON_NAME', $output);
}
+
+ public function testStoredInfotype()
+ {
+ $bucketName = $this->requireEnv('GOOGLE_STORAGE_BUCKET');
+ $outputgcsPath = 'gs://' . $bucketName;
+ $storedInfoTypeId = uniqid('github-usernames-');
+ $gcsPath = 'gs://' . $bucketName . '/term-list.txt';
+ // Optionally set a display name and a description.
+ $description = 'Dictionary of GitHub usernames used in commits';
+ $displayName = 'GitHub usernames';
+
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock1 = $this->prophesize(DlpServiceClient::class);
+
+ $createStoredInfoTypeResponse = (new StoredInfoType())
+ ->setName('projects/' . self::$projectId . '/locations/global/storedInfoTypes/' . $storedInfoTypeId)
+ ->setCurrentVersion((new StoredInfoTypeVersion())
+ ->setState(StoredInfoTypeState::READY)
+ );
+
+ $inspectContentResponse = (new InspectContentResponse())
+ ->setResult((new InspectResult())
+ ->setFindings([
+ (new Finding())
+ ->setQuote('The')
+ ->setInfoType((new InfoType())->setName('STORED_TYPE'))
+ ->setLikelihood(Likelihood::VERY_LIKELY)
+ ]));
+
+ $dlpServiceClientMock1->createStoredInfoType(Argument::any(), Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($createStoredInfoTypeResponse);
+
+ $dlpServiceClientMock1->inspectContent(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($inspectContentResponse);
+
+ $dlpServiceClientMock1->updateStoredInfoType(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($createStoredInfoTypeResponse);
+
+ // Test create stored infotype.
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_create_stored_infotype('%s','%s','%s','%s','%s');",
+ self::$projectId,
+ $outputgcsPath,
+ $storedInfoTypeId,
+ $displayName,
+ $description
+ );
+
+ $tmpFile1 = $this->writeTempSample('create_stored_infotype', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
+
+ global $dlp;
+
+ $dlp = $dlpServiceClientMock1->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile1;
+ $output = ob_get_clean();
+
+ $this->assertStringContainsString('projects/' . self::$projectId . '/locations/global/storedInfoTypes/', $output);
+ $storedInfoTypeName = explode('Successfully created Stored InfoType : ', $output)[1];
+
+ // Test inspect stored infotype.
+ // Creating a temp file for testing.
+ $textToInspect = 'The commit was made by test@gmail.com.';
+
+ $callFunction = sprintf(
+ "dlp_inspect_with_stored_infotype('%s','%s','%s');",
+ self::$projectId,
+ $storedInfoTypeName,
+ $textToInspect
+ );
+
+ $tmpFile2 = $this->writeTempSample('inspect_with_stored_infotype', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
+ global $dlp;
+
+ $dlp = $dlpServiceClientMock1->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile2;
+ $inspectOutput = ob_get_clean();
+
+ $this->assertStringContainsString('Quote: The', $inspectOutput);
+ $this->assertStringContainsString('Info type: STORED_TYPE', $inspectOutput);
+ $this->assertStringContainsString('Likelihood: VERY_LIKELY', $inspectOutput);
+
+ // Test update stored infotype.
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_update_stored_infotype('%s','%s','%s','%s');",
+ self::$projectId,
+ $gcsPath,
+ $outputgcsPath,
+ $storedInfoTypeId
+ );
+
+ $tmpFile3 = $this->writeTempSample('update_stored_infotype', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
+ ]);
+
+ global $dlp;
+ $dlp = $dlpServiceClientMock1->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile3;
+ $updateOutput = ob_get_clean();
+
+ $this->assertStringContainsString('projects/' . self::$projectId . '/locations/global/storedInfoTypes/' . $storedInfoTypeId, $updateOutput);
+ }
}
From f45f710099e64ec40455be8dc82dfdd04dde3cf5 Mon Sep 17 00:00:00 2001
From: sameer-crest <129392897+sameer-crest@users.noreply.github.com>
Date: Mon, 18 Sep 2023 18:14:30 +0530
Subject: [PATCH 074/285] test(dlp): Implemented mocking approach in an
existing unit test case (#1906)
* Implemented mocking approach in existing unit test case
---
dlp/src/categorical_stats.php | 21 +-
dlp/src/inspect_bigquery.php | 7 +-
dlp/src/inspect_datastore.php | 11 +-
dlp/src/inspect_gcs.php | 10 +-
dlp/src/k_anonymity.php | 21 +-
dlp/src/k_map.php | 19 +-
dlp/src/l_diversity.php | 23 +-
dlp/src/numerical_stats.php | 19 +-
dlp/test/dlpLongRunningTest.php | 698 +++++++++++++++++++++++++++++++-
dlp/test/dlpTest.php | 58 +--
10 files changed, 754 insertions(+), 133 deletions(-)
diff --git a/dlp/src/categorical_stats.php b/dlp/src/categorical_stats.php
index c95e7c2c14..3533cd5fa2 100644
--- a/dlp/src/categorical_stats.php
+++ b/dlp/src/categorical_stats.php
@@ -1,5 +1,4 @@
$callingProjectId,
- ]);
- $pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
- ]);
+ $dlp = new DlpServiceClient();
+ $pubsub = new PubSubClient();
$topic = $pubsub->topic($topicId);
// Construct risk analysis config
@@ -109,8 +104,10 @@ function categorical_stats(
$startTime = time();
do {
foreach ($subscription->pull() as $message) {
- if (isset($message->attributes()['DlpJobName']) &&
- $message->attributes()['DlpJobName'] === $job->getName()) {
+ if (
+ isset($message->attributes()['DlpJobName']) &&
+ $message->attributes()['DlpJobName'] === $job->getName()
+ ) {
$subscription->acknowledge($message);
// Get the updated job. Loop to avoid race condition with DLP API.
do {
@@ -119,7 +116,7 @@ function categorical_stats(
break 2; // break from parent do while
}
}
- printf('Waiting for job to complete' . PHP_EOL);
+ print('Waiting for job to complete' . PHP_EOL);
// Exponential backoff with max delay of 60 seconds
sleep(min(60, pow(2, ++$attempt)));
} while (time() - $startTime < 600); // 10 minute timeout
@@ -156,10 +153,10 @@ function categorical_stats(
}
break;
case JobState::PENDING:
- printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ print('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
break;
default:
- printf('Unexpected job state.');
+ print('Unexpected job state.');
}
}
# [END dlp_categorical_stats]
diff --git a/dlp/src/inspect_bigquery.php b/dlp/src/inspect_bigquery.php
index 8381b2bb8c..e54f386ebb 100644
--- a/dlp/src/inspect_bigquery.php
+++ b/dlp/src/inspect_bigquery.php
@@ -1,5 +1,4 @@
pull() as $message) {
- if (isset($message->attributes()['DlpJobName']) &&
- $message->attributes()['DlpJobName'] === $job->getName()) {
+ if (
+ isset($message->attributes()['DlpJobName']) &&
+ $message->attributes()['DlpJobName'] === $job->getName()
+ ) {
$subscription->acknowledge($message);
// Get the updated job. Loop to avoid race condition with DLP API.
do {
@@ -139,7 +140,7 @@ function inspect_datastore(
break 2; // break from parent do while
}
}
- printf('Waiting for job to complete' . PHP_EOL);
+ print('Waiting for job to complete' . PHP_EOL);
// Exponential backoff with max delay of 60 seconds
sleep(min(60, pow(2, ++$attempt)));
} while (time() - $startTime < 600); // 10 minute timeout
@@ -165,7 +166,7 @@ function inspect_datastore(
}
break;
case JobState::PENDING:
- printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ print('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
break;
default:
print('Unexpected job state.');
diff --git a/dlp/src/inspect_gcs.php b/dlp/src/inspect_gcs.php
index 59930d8e32..73fad59b24 100644
--- a/dlp/src/inspect_gcs.php
+++ b/dlp/src/inspect_gcs.php
@@ -119,8 +119,10 @@ function inspect_gcs(
$startTime = time();
do {
foreach ($subscription->pull() as $message) {
- if (isset($message->attributes()['DlpJobName']) &&
- $message->attributes()['DlpJobName'] === $job->getName()) {
+ if (
+ isset($message->attributes()['DlpJobName']) &&
+ $message->attributes()['DlpJobName'] === $job->getName()
+ ) {
$subscription->acknowledge($message);
// Get the updated job. Loop to avoid race condition with DLP API.
do {
@@ -129,7 +131,7 @@ function inspect_gcs(
break 2; // break from parent do while
}
}
- printf('Waiting for job to complete' . PHP_EOL);
+ print('Waiting for job to complete' . PHP_EOL);
// Exponential backoff with max delay of 60 seconds
sleep(min(60, pow(2, ++$attempt)));
} while (time() - $startTime < 600); // 10 minute timeout
@@ -155,7 +157,7 @@ function inspect_gcs(
}
break;
case JobState::PENDING:
- printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ print('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
break;
default:
print('Unexpected job state. Most likely, the job is either running or has not yet started.');
diff --git a/dlp/src/k_anonymity.php b/dlp/src/k_anonymity.php
index 1b00f83c52..449ad3a7e7 100644
--- a/dlp/src/k_anonymity.php
+++ b/dlp/src/k_anonymity.php
@@ -1,5 +1,4 @@
$callingProjectId,
- ]);
- $pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
- ]);
+ $dlp = new DlpServiceClient();
+ $pubsub = new PubSubClient();
$topic = $pubsub->topic($topicId);
// Construct risk analysis config
@@ -113,8 +108,10 @@ function ($id) {
$startTime = time();
do {
foreach ($subscription->pull() as $message) {
- if (isset($message->attributes()['DlpJobName']) &&
- $message->attributes()['DlpJobName'] === $job->getName()) {
+ if (
+ isset($message->attributes()['DlpJobName']) &&
+ $message->attributes()['DlpJobName'] === $job->getName()
+ ) {
$subscription->acknowledge($message);
// Get the updated job. Loop to avoid race condition with DLP API.
do {
@@ -123,7 +120,7 @@ function ($id) {
break 2; // break from parent do while
}
}
- printf('Waiting for job to complete' . PHP_EOL);
+ print('Waiting for job to complete' . PHP_EOL);
// Exponential backoff with max delay of 60 seconds
sleep(min(60, pow(2, ++$attempt)));
} while (time() - $startTime < 600); // 10 minute timeout
@@ -166,10 +163,10 @@ function ($id) {
}
break;
case JobState::PENDING:
- printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ print('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
break;
default:
- printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ print('Unexpected job state. Most likely, the job is either running or has not yet started.');
}
}
# [END dlp_k_anomymity]
diff --git a/dlp/src/k_map.php b/dlp/src/k_map.php
index efb37fd654..61a515b404 100644
--- a/dlp/src/k_map.php
+++ b/dlp/src/k_map.php
@@ -1,5 +1,4 @@
$callingProjectId,
- ]);
- $pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
- ]);
+ $dlp = new DlpServiceClient();
+ $pubsub = new PubSubClient();
$topic = $pubsub->topic($topicId);
// Verify input
@@ -134,8 +129,10 @@ function k_map(
$startTime = time();
do {
foreach ($subscription->pull() as $message) {
- if (isset($message->attributes()['DlpJobName']) &&
- $message->attributes()['DlpJobName'] === $job->getName()) {
+ if (
+ isset($message->attributes()['DlpJobName']) &&
+ $message->attributes()['DlpJobName'] === $job->getName()
+ ) {
$subscription->acknowledge($message);
// Get the updated job. Loop to avoid race condition with DLP API.
do {
@@ -144,7 +141,7 @@ function k_map(
break 2; // break from parent do while
}
}
- printf('Waiting for job to complete' . PHP_EOL);
+ print('Waiting for job to complete' . PHP_EOL);
// Exponential backoff with max delay of 60 seconds
sleep(min(60, pow(2, ++$attempt)));
} while (time() - $startTime < 600); // 10 minute timeout
@@ -188,7 +185,7 @@ function k_map(
}
break;
case JobState::PENDING:
- printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ print('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
break;
default:
print('Unexpected job state. Most likely, the job is either running or has not yet started.');
diff --git a/dlp/src/l_diversity.php b/dlp/src/l_diversity.php
index 6bdcf5a176..95a4ef2f6a 100644
--- a/dlp/src/l_diversity.php
+++ b/dlp/src/l_diversity.php
@@ -1,5 +1,4 @@
$callingProjectId,
- ]);
- $pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
- ]);
+ $dlp = new DlpServiceClient();
+ $pubsub = new PubSubClient();
$topic = $pubsub->topic($topicId);
// Construct risk analysis config
@@ -119,8 +114,10 @@ function ($id) {
$startTime = time();
do {
foreach ($subscription->pull() as $message) {
- if (isset($message->attributes()['DlpJobName']) &&
- $message->attributes()['DlpJobName'] === $job->getName()) {
+ if (
+ isset($message->attributes()['DlpJobName']) &&
+ $message->attributes()['DlpJobName'] === $job->getName()
+ ) {
$subscription->acknowledge($message);
// Get the updated job. Loop to avoid race condition with DLP API.
do {
@@ -129,7 +126,7 @@ function ($id) {
break 2; // break from parent do while
}
}
- printf('Waiting for job to complete' . PHP_EOL);
+ print('Waiting for job to complete' . PHP_EOL);
// Exponential backoff with max delay of 60 seconds
sleep(min(60, pow(2, ++$attempt)));
} while (time() - $startTime < 600); // 10 minute timeout
@@ -182,10 +179,10 @@ function ($id) {
}
break;
case JobState::PENDING:
- printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ print('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
break;
default:
- printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ print('Unexpected job state. Most likely, the job is either running or has not yet started.');
}
}
# [END dlp_l_diversity]
diff --git a/dlp/src/numerical_stats.php b/dlp/src/numerical_stats.php
index 2559f9fd64..2dbb1e3327 100644
--- a/dlp/src/numerical_stats.php
+++ b/dlp/src/numerical_stats.php
@@ -1,5 +1,4 @@
$callingProjectId
- ]);
- $pubsub = new PubSubClient([
- 'projectId' => $callingProjectId
- ]);
+ $dlp = new DlpServiceClient();
+ $pubsub = new PubSubClient();
$topic = $pubsub->topic($topicId);
// Construct risk analysis config
@@ -109,8 +104,10 @@ function numerical_stats(
$startTime = time();
do {
foreach ($subscription->pull() as $message) {
- if (isset($message->attributes()['DlpJobName']) &&
- $message->attributes()['DlpJobName'] === $job->getName()) {
+ if (
+ isset($message->attributes()['DlpJobName']) &&
+ $message->attributes()['DlpJobName'] === $job->getName()
+ ) {
$subscription->acknowledge($message);
// Get the updated job. Loop to avoid race condition with DLP API.
do {
@@ -119,7 +116,7 @@ function numerical_stats(
break 2; // break from parent do while
}
}
- printf('Waiting for job to complete' . PHP_EOL);
+ print('Waiting for job to complete' . PHP_EOL);
// Exponential backoff with max delay of 60 seconds
sleep(min(60, pow(2, ++$attempt)));
} while (time() - $startTime < 600); // 10 minute timeout
@@ -160,7 +157,7 @@ function numerical_stats(
}
break;
case JobState::PENDING:
- printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
+ print('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
break;
default:
print('Unexpected job state. Most likely, the job is either running or has not yet started.');
diff --git a/dlp/test/dlpLongRunningTest.php b/dlp/test/dlpLongRunningTest.php
index 3f32563a18..e8e0cd9953 100644
--- a/dlp/test/dlpLongRunningTest.php
+++ b/dlp/test/dlpLongRunningTest.php
@@ -28,7 +28,22 @@
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InfoTypeStats;
use Google\Cloud\Dlp\V2\InspectDataSourceDetails;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\CategoricalStatsResult;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\CategoricalStatsResult\CategoricalStatsHistogramBucket;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KAnonymityResult;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KAnonymityResult\KAnonymityEquivalenceClass;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KAnonymityResult\KAnonymityHistogramBucket;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KMapEstimationResult;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KMapEstimationResult\KMapEstimationHistogramBucket;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\KMapEstimationResult\KMapEstimationQuasiIdValues;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\LDiversityResult;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\LDiversityResult\LDiversityEquivalenceClass;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\LDiversityResult\LDiversityHistogramBucket;
+use Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails\NumericalStatsResult;
use Google\Cloud\Dlp\V2\InspectDataSourceDetails\Result;
+use Google\Cloud\Dlp\V2\Value;
+use Google\Cloud\Dlp\V2\ValueFrequency;
use Google\Cloud\PubSub\Message;
use Google\Cloud\PubSub\PubSubClient;
use Google\Cloud\PubSub\Subscription;
@@ -109,27 +124,155 @@ public function testInspectDatastore()
$kind = 'Person';
$namespace = 'DLP';
- $output = $this->runFunctionSnippet('inspect_datastore', [
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $dlpJobResponse = $this->dlpJobResponse();
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['createDlpJob']);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['getDlpJob']);
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic(self::$topic->name())
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . self::$topic->name());
+
+ $topicMock->subscription(self::$subscription->name())
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_inspect_datastore('%s','%s','%s','%s','%s','%s');",
self::$projectId,
self::$projectId,
self::$topic->name(),
self::$subscription->name(),
$kind,
$namespace
+ );
+
+ $tmpFile = $this->writeTempSample('inspect_datastore', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
]);
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ // Assert the expected behavior or outcome
+ $this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
$this->assertStringContainsString('PERSON_NAME', $output);
}
public function testInspectBigquery()
{
- $output = $this->runFunctionSnippet('inspect_bigquery', [
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $dlpJobResponse = $this->dlpJobResponse();
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['createDlpJob']);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($dlpJobResponse['getDlpJob']);
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic(self::$topic->name())
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . self::$topic->name());
+
+ $topicMock->subscription(self::$subscription->name())
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_inspect_bigquery('%s','%s','%s','%s','%s','%s');",
self::$projectId,
self::$projectId,
self::$topic->name(),
self::$subscription->name(),
self::$dataset,
self::$table,
+ );
+
+ $tmpFile = $this->writeTempSample('inspect_bigquery', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
]);
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ // Assert the expected behavior or outcome
+ $this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
$this->assertStringContainsString('PERSON_NAME', $output);
}
@@ -218,7 +361,75 @@ public function testNumericalStats()
{
$columnName = 'Age';
- $output = $this->runFunctionSnippet('numerical_stats', [
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $createDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::PENDING);
+
+ $getDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::DONE)
+ ->setRiskDetails((new AnalyzeDataSourceRiskDetails())
+ ->setNumericalStatsResult((new NumericalStatsResult())
+ ->setMinValue((new Value())->setIntegerValue(1231))
+ ->setMaxValue((new Value())->setIntegerValue(9999))
+ ->setQuantileValues([
+ (new Value())->setIntegerValue(1231),
+ (new Value())->setIntegerValue(1231),
+ (new Value())->setIntegerValue(1231),
+ (new Value())->setIntegerValue(1234),
+ (new Value())->setIntegerValue(1234),
+ (new Value())->setIntegerValue(3412),
+ (new Value())->setIntegerValue(3412),
+ (new Value())->setIntegerValue(4444),
+ (new Value())->setIntegerValue(9999),
+ ])
+ )
+ );
+
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($createDlpJobResponse);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($getDlpJobResponse);
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic(self::$topic->name())
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . self::$topic->name());
+
+ $topicMock->subscription(self::$subscription->name())
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_numerical_stats('%s','%s','%s','%s','%s','%s','%s');",
self::$projectId, // calling project
self::$projectId, // data project
self::$topic->name(),
@@ -226,8 +437,26 @@ public function testNumericalStats()
self::$dataset,
self::$table,
$columnName,
+ );
+
+ $tmpFile = $this->writeTempSample('numerical_stats', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
]);
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ // Assert the expected behavior or outcome
$this->assertMatchesRegularExpression('/Value range: \[\d+, \d+\]/', $output);
$this->assertMatchesRegularExpression('/Value at \d+ quantile: \d+/', $output);
}
@@ -236,7 +465,73 @@ public function testCategoricalStats()
{
$columnName = 'Gender';
- $output = $this->runFunctionSnippet('categorical_stats', [
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $createDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::PENDING);
+
+ $getDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::DONE)
+ ->setRiskDetails((new AnalyzeDataSourceRiskDetails())
+ ->setCategoricalStatsResult((new CategoricalStatsResult())
+ ->setValueFrequencyHistogramBuckets([
+ (new CategoricalStatsHistogramBucket())
+ ->setValueFrequencyUpperBound(1)
+ ->setValueFrequencyLowerBound(1)
+ ->setBucketSize(1)
+ ->setBucketValues([
+ (new ValueFrequency())
+ ->setValue((new Value())->setStringValue('{"stringValue":"19"}'))
+ ->setCount(1),
+ ]),
+ ])
+ )
+ );
+
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($createDlpJobResponse);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($getDlpJobResponse);
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic(self::$topic->name())
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . self::$topic->name());
+
+ $topicMock->subscription(self::$subscription->name())
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_categorical_stats('%s','%s','%s','%s','%s','%s','%s');",
self::$projectId, // calling project
self::$projectId, // data project
self::$topic->name(),
@@ -244,8 +539,26 @@ public function testCategoricalStats()
self::$dataset,
self::$table,
$columnName,
+ );
+
+ $tmpFile = $this->writeTempSample('categorical_stats', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
]);
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+ // Assert the expected behavior or outcome
$this->assertMatchesRegularExpression('/Most common value occurs \d+ time\(s\)/', $output);
$this->assertMatchesRegularExpression('/Least common value occurs \d+ time\(s\)/', $output);
$this->assertMatchesRegularExpression('/\d+ unique value\(s\) total/', $output);
@@ -253,27 +566,246 @@ public function testCategoricalStats()
public function testKAnonymity()
{
- $quasiIds = 'Age,Gender';
- $output = $this->runFunctionSnippet('k_anonymity', [
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $createDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::PENDING);
+
+ $getDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::DONE)
+ ->setRiskDetails((new AnalyzeDataSourceRiskDetails())
+ ->setKAnonymityResult((new KAnonymityResult())
+ ->setEquivalenceClassHistogramBuckets([
+ (new KAnonymityHistogramBucket())
+ ->setEquivalenceClassSizeLowerBound(1)
+ ->setEquivalenceClassSizeUpperBound(1)
+ ->setBucketValues([
+ (new KAnonymityEquivalenceClass())
+ ->setQuasiIdsValues([
+ (new Value())
+ ->setStringValue('{"stringValue":"19"}'),
+ (new Value())
+ ->setStringValue('{"stringValue":"Male"}')
+ ])
+ ->setEquivalenceClassSize(1),
+ (new KAnonymityEquivalenceClass())
+ ->setQuasiIdsValues([
+ (new Value())
+ ->setStringValue('{"stringValue":"35"}'),
+ (new Value())
+ ->setStringValue('{"stringValue":"Male"}')
+ ])
+ ->setEquivalenceClassSize(1)
+
+ ]),
+ (new KAnonymityHistogramBucket())
+ ->setEquivalenceClassSizeLowerBound(2)
+ ->setEquivalenceClassSizeUpperBound(2)
+ ->setBucketValues([
+ (new KAnonymityEquivalenceClass())
+ ->setQuasiIdsValues([
+ (new Value())
+ ->setStringValue('{"stringValue":"35"}'),
+ (new Value())
+ ->setStringValue('{"stringValue":"Female"}')
+ ])
+ ->setEquivalenceClassSize(2)
+ ])
+ ])
+ )
+ );
+
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($createDlpJobResponse);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($getDlpJobResponse);
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic(self::$topic->name())
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . self::$topic->name());
+
+ $topicMock->subscription(self::$subscription->name())
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_k_anonymity('%s','%s','%s','%s','%s','%s',%s);",
self::$projectId, // calling project
self::$projectId, // data project
self::$topic->name(),
self::$subscription->name(),
self::$dataset,
self::$table,
- $quasiIds,
+ "['Age', 'Mystery']"
+ );
+
+ $tmpFile = $this->writeTempSample('k_anonymity', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
]);
- $this->assertStringContainsString('{"stringValue":"Female"}', $output);
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ // Assert the expected behavior or outcome
+ $this->assertStringContainsString('Job projects/' . self::$projectId . '/dlpJobs/', $output);
+ $this->assertStringContainsString('{\"stringValue\":\"Female\"}', $output);
$this->assertMatchesRegularExpression('/Class size: \d/', $output);
}
public function testLDiversity()
{
$sensitiveAttribute = 'Name';
- $quasiIds = 'Age,Gender';
- $output = $this->runFunctionSnippet('l_diversity', [
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $createDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::PENDING);
+
+ $getDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::DONE)
+ ->setRiskDetails((new AnalyzeDataSourceRiskDetails())
+ ->setLDiversityResult((new LDiversityResult())
+ ->setSensitiveValueFrequencyHistogramBuckets([
+ (new LDiversityHistogramBucket())
+ ->setSensitiveValueFrequencyLowerBound(1)
+ ->setSensitiveValueFrequencyUpperBound(1)
+ ->setBucketValues([
+ (new LDiversityEquivalenceClass())
+ ->setQuasiIdsValues([
+ (new Value())
+ ->setStringValue('{"stringValue":"19"}'),
+ (new Value())
+ ->setStringValue('{"stringValue":"Male"}')
+ ])
+ ->setEquivalenceClassSize(1)
+ ->setTopSensitiveValues([
+ (new ValueFrequency())
+ ->setValue((new Value())->setStringValue('{"stringValue":"James"}'))
+ ->setCount(1)
+ ]),
+ (new LDiversityEquivalenceClass())
+ ->setQuasiIdsValues([
+ (new Value())
+ ->setStringValue('{"stringValue":"35"}'),
+ (new Value())
+ ->setStringValue('{"stringValue":"Male"}')
+ ])
+ ->setEquivalenceClassSize(1)
+ ->setTopSensitiveValues([
+ (new ValueFrequency())
+ ->setValue((new Value())->setStringValue('{"stringValue":"Joe"}'))
+ ->setCount(1)
+ ]),
+ ]),
+ (new LDiversityHistogramBucket())
+ ->setSensitiveValueFrequencyLowerBound(2)
+ ->setSensitiveValueFrequencyUpperBound(2)
+ ->setBucketValues([
+ (new LDiversityEquivalenceClass())
+ ->setQuasiIdsValues([
+ (new Value())
+ ->setStringValue('{"stringValue":"35"}'),
+ (new Value())
+ ->setStringValue('{"stringValue":"Female"}')
+ ])
+ ->setEquivalenceClassSize(1)
+ ->setTopSensitiveValues([
+ (new ValueFrequency())
+ ->setValue((new Value())->setStringValue('{"stringValue":"Carrie"}'))
+ ->setCount(2),
+ (new ValueFrequency())
+ ->setValue((new Value())->setStringValue('{"stringValue":"Marie"}'))
+ ->setCount(1)
+ ]),
+ ]),
+ ])
+ )
+ );
+
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($createDlpJobResponse);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($getDlpJobResponse);
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic(self::$topic->name())
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . self::$topic->name());
+
+ $topicMock->subscription(self::$subscription->name())
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_l_diversity('%s','%s','%s','%s','%s','%s','%s',%s);",
self::$projectId, // calling project
self::$projectId, // data project
self::$topic->name(),
@@ -281,20 +813,129 @@ public function testLDiversity()
self::$dataset,
self::$table,
$sensitiveAttribute,
- $quasiIds,
+ "['Age', 'Gender']"
+ );
+
+ $tmpFile = $this->writeTempSample('l_diversity', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
]);
- $this->assertStringContainsString('{"stringValue":"Female"}', $output);
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ // Assert the expected behavior or outcome
+ $this->assertStringContainsString('{\"stringValue\":\"Female\"}', $output);
$this->assertMatchesRegularExpression('/Class size: \d/', $output);
- $this->assertStringContainsString('{"stringValue":"James"}', $output);
+ $this->assertStringContainsString('{\"stringValue\":\"James\"}', $output);
}
public function testKMap()
{
$regionCode = 'US';
- $quasiIds = 'Age,Gender';
- $infoTypes = 'AGE,GENDER';
+ // Mock the necessary objects and methods
+ $dlpServiceClientMock = $this->prophesize(DlpServiceClient::class);
+
+ $createDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::PENDING);
+
+ $getDlpJobResponse = (new DlpJob())
+ ->setName('projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812')
+ ->setState(JobState::DONE)
+ ->setRiskDetails((new AnalyzeDataSourceRiskDetails())
+ ->setKMapEstimationResult((new KMapEstimationResult())
+ ->setKMapEstimationHistogram([
+ (new KMapEstimationHistogramBucket())
+ ->setMinAnonymity(3)
+ ->setMaxAnonymity(3)
+ ->setBucketSize(3)
+ ->setBucketValues([
+ (new KMapEstimationQuasiIdValues())
+ ->setQuasiIdsValues([
+ (new Value())
+ ->setStringValue('{"integerValue":"35"}'),
+ (new Value())
+ ->setStringValue('{"stringValue":"Female"}')
+ ])
+ ->setEstimatedAnonymity(3),
+ ]),
+ (new KMapEstimationHistogramBucket())
+ ->setMinAnonymity(1)
+ ->setMaxAnonymity(1)
+ ->setBucketSize(2)
+ ->setBucketValues([
+ (new KMapEstimationQuasiIdValues())
+ ->setQuasiIdsValues([
+ (new Value())
+ ->setStringValue('{"integerValue":"19"}'),
+ (new Value())
+ ->setStringValue('{"stringValue":"Male"}')
+ ])
+ ->setEstimatedAnonymity(1),
+ (new KMapEstimationQuasiIdValues())
+ ->setQuasiIdsValues([
+ (new Value())
+ ->setStringValue('{"integerValue":"35"}'),
+ (new Value())
+ ->setStringValue('{"stringValue":"Male"}')
+ ])
+ ->setEstimatedAnonymity(1),
+ ]),
+ ])
+ )
+ );
- $output = $this->runFunctionSnippet('k_map', [
+ $dlpServiceClientMock->createDlpJob(Argument::any(), Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($createDlpJobResponse);
+
+ $dlpServiceClientMock->getDlpJob(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($getDlpJobResponse);
+
+ $pubSubClientMock = $this->prophesize(PubSubClient::class);
+ $topicMock = $this->prophesize(Topic::class);
+ $subscriptionMock = $this->prophesize(Subscription::class);
+ $messageMock = $this->prophesize(Message::class);
+
+ // Set up the mock expectations for the Pub/Sub functions
+ $pubSubClientMock->topic(self::$topic->name())
+ ->shouldBeCalled()
+ ->willReturn($topicMock->reveal());
+
+ $topicMock->name()
+ ->shouldBeCalled()
+ ->willReturn('projects/' . self::$projectId . '/topics/' . self::$topic->name());
+
+ $topicMock->subscription(self::$subscription->name())
+ ->shouldBeCalled()
+ ->willReturn($subscriptionMock->reveal());
+
+ $subscriptionMock->pull()
+ ->shouldBeCalled()
+ ->willReturn([$messageMock->reveal()]);
+
+ $messageMock->attributes()
+ ->shouldBeCalledTimes(2)
+ ->willReturn(['DlpJobName' => 'projects/' . self::$projectId . '/dlpJobs/i-3208317104051988812']);
+
+ $subscriptionMock->acknowledge(Argument::any())
+ ->shouldBeCalled()
+ ->willReturn($messageMock->reveal());
+
+ // Creating a temp file for testing.
+ $callFunction = sprintf(
+ "dlp_k_map('%s','%s','%s','%s','%s','%s','%s',%s,%s);",
self::$projectId,
self::$projectId,
self::$topic->name(),
@@ -302,11 +943,30 @@ public function testKMap()
self::$dataset,
self::$table,
$regionCode,
- $quasiIds,
- $infoTypes,
+ "['Age','Gender']",
+ "['AGE','GENDER']",
+ );
+
+ $tmpFile = $this->writeTempSample('k_map', [
+ '$dlp = new DlpServiceClient();' => 'global $dlp;',
+ '$pubsub = new PubSubClient();' => 'global $pubsub;',
+ "require_once __DIR__ . '/../../testing/sample_helpers.php';" => '',
+ '\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);' => $callFunction
]);
+ global $dlp;
+ global $pubsub;
+
+ $dlp = $dlpServiceClientMock->reveal();
+ $pubsub = $pubSubClientMock->reveal();
+
+ // Invoke file and capture output
+ ob_start();
+ include $tmpFile;
+ $output = ob_get_clean();
+
+ // Assert the expected behavior or outcome
$this->assertMatchesRegularExpression('/Anonymity range: \[\d, \d\]/', $output);
$this->assertMatchesRegularExpression('/Size: \d/', $output);
- $this->assertStringContainsString('{"stringValue":"Female"}', $output);
+ $this->assertStringContainsString('{\"stringValue\":\"Female\"}', $output);
}
}
diff --git a/dlp/test/dlpTest.php b/dlp/test/dlpTest.php
index a7275bb875..c682660f09 100644
--- a/dlp/test/dlpTest.php
+++ b/dlp/test/dlpTest.php
@@ -339,22 +339,34 @@ public function testInspectTemplates()
*/
public function testJobs()
{
+ $gcsPath = $this->requireEnv('GCS_PATH');
+ $jobIdRegex = "~projects/.*/dlpJobs/i-\d+~";
// Set filter to only go back a day, so that we do not pull every job.
$filter = sprintf(
'state=DONE AND end_time>"%sT00:00:00+00:00"',
date('Y-m-d', strtotime('-1 day'))
);
- $jobIdRegex = "~projects/.*/dlpJobs/i-\d+~";
- $output = $this->runFunctionSnippet('list_jobs', [
+ $jobName = $this->runFunctionSnippet('create_job', [
+ self::$projectId,
+ $gcsPath
+ ]);
+ $this->assertMatchesRegularExpression($jobIdRegex, $jobName);
+
+ $listOutput = $this->runFunctionSnippet('list_jobs', [
self::$projectId,
$filter,
]);
- $this->assertMatchesRegularExpression($jobIdRegex, $output);
- preg_match($jobIdRegex, $output, $jobIds);
+ $this->assertMatchesRegularExpression($jobIdRegex, $listOutput);
+ preg_match($jobIdRegex, $listOutput, $jobIds);
$jobId = $jobIds[0];
+ $getJobOutput = $this->runFunctionSnippet('get_job', [
+ $jobId
+ ]);
+ $this->assertStringContainsString('Job ' . $jobId . ' status:', $getJobOutput);
+
$output = $this->runFunctionSnippet(
'delete_job',
[$jobId]
@@ -875,44 +887,6 @@ public function testDeidReidTextFPE()
$this->assertEquals($string, $reidOutput);
}
- public function testGetJob()
- {
-
- // Set filter to only go back a day, so that we do not pull every job.
- $filter = sprintf(
- 'state=DONE AND end_time>"%sT00:00:00+00:00"',
- date('Y-m-d', strtotime('-1 day'))
- );
- $jobIdRegex = "~projects/.*/dlpJobs/i-\d+~";
- $getJobName = $this->runFunctionSnippet('list_jobs', [
- self::$projectId,
- $filter,
- ]);
- preg_match($jobIdRegex, $getJobName, $jobIds);
- $jobName = $jobIds[0];
-
- $output = $this->runFunctionSnippet('get_job', [
- $jobName
- ]);
- $this->assertStringContainsString('Job ' . $jobName . ' status:', $output);
- }
-
- public function testCreateJob()
- {
- $gcsPath = $this->requireEnv('GCS_PATH');
- $jobIdRegex = "~projects/.*/dlpJobs/i-\d+~";
- $jobName = $this->runFunctionSnippet('create_job', [
- self::$projectId,
- $gcsPath
- ]);
- $this->assertRegExp($jobIdRegex, $jobName);
- $output = $this->runFunctionSnippet(
- 'delete_job',
- [$jobName]
- );
- $this->assertStringContainsString('Successfully deleted job ' . $jobName, $output);
- }
-
public function testRedactImageListedInfotypes()
{
$imagePath = __DIR__ . '/data/test.png';
From 7f4be92568d05633457fc403a9a953b796dec151 Mon Sep 17 00:00:00 2001
From: minherz
Date: Thu, 21 Sep 2023 22:26:07 +0000
Subject: [PATCH 075/285] chore: refactor error reporting code sample (#1917)
---
error_reporting/quickstart.php | 4 ++--
error_reporting/test/quickstartTest.php | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/error_reporting/quickstart.php b/error_reporting/quickstart.php
index 6704ea00c0..06144dd550 100644
--- a/error_reporting/quickstart.php
+++ b/error_reporting/quickstart.php
@@ -11,7 +11,7 @@
// These variables are set by the App Engine environment. To test locally,
// ensure these are set or manually change their values.
-$projectId = getenv('GCLOUD_PROJECT') ?: 'YOUR_PROJECT_ID';
+$projectId = getenv('GOOGLE_CLOUD_PROJECT') ?: 'YOUR_PROJECT_ID';
$service = getenv('GAE_SERVICE') ?: 'error_reporting_quickstart';
$version = getenv('GAE_VERSION') ?: 'test';
@@ -30,5 +30,5 @@
Bootstrap::init($psrLogger);
print('Throwing a test exception. You can view the message at https://console.cloud.google.com/errors.' . PHP_EOL);
-throw new Exception('quickstart.php test exception');
+throw new Exception('Something went wrong');
# [END error_reporting_quickstart]
diff --git a/error_reporting/test/quickstartTest.php b/error_reporting/test/quickstartTest.php
index d8697c1b44..603e17accd 100644
--- a/error_reporting/test/quickstartTest.php
+++ b/error_reporting/test/quickstartTest.php
@@ -49,6 +49,6 @@ public function testQuickstart()
// Make sure it worked
$this->assertStringContainsString('Throwing a test exception', $output);
- $this->verifyReportedError(self::$projectId, 'quickstart.php test exception');
+ $this->verifyReportedError(self::$projectId, 'Something went wrong');
}
}
From 32c7c9316948a6bf8f5ceb38c842068224e6f355 Mon Sep 17 00:00:00 2001
From: Mend Renovate
Date: Fri, 29 Sep 2023 17:16:43 +0200
Subject: [PATCH 076/285] fix(deps): update dependency google/cloud-language to
^0.31.0 (#1910)
---
language/composer.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/language/composer.json b/language/composer.json
index 7b37a23096..af0ac8122c 100644
--- a/language/composer.json
+++ b/language/composer.json
@@ -1,6 +1,6 @@
{
"require": {
- "google/cloud-language": "^0.30.2",
+ "google/cloud-language": "^0.31.0",
"google/cloud-storage": "^1.20.1"
}
}
From 4aabf82e377554661ebb6e5fdbfdd588e892de59 Mon Sep 17 00:00:00 2001
From: Brent Shaffer
Date: Sun, 1 Oct 2023 13:02:23 -0700
Subject: [PATCH 077/285] chore(tests): stricter static analysis (#1596)
---
.github/workflows/lint.yml | 24 ++--
analyticsdata/src/get_common_metadata.php | 3 +-
.../src/get_metadata_by_property_id.php | 1 +
.../src/run_report_with_aggregations.php | 2 +-
analyticsdata/src/run_report_with_cohorts.php | 2 +-
.../src/run_report_with_date_ranges.php | 2 +-
.../run_report_with_multiple_dimensions.php | 2 +-
.../src/run_report_with_multiple_metrics.php | 2 +-
.../src/run_report_with_named_date_ranges.php | 2 +-
asset/src/batch_get_assets_history.php | 13 ++-
asset/src/list_assets.php | 13 ++-
asset/src/search_all_resources.php | 14 +--
asset/test/assetSearchTest.php | 30 +++--
asset/test/assetTest.php | 52 ++++++---
bigquery/api/src/bigquery_client.php | 1 +
bigquery/api/src/get_table.php | 3 +
bigquery/api/src/stream_row.php | 2 +-
bigtable/src/filter_composing_chain.php | 2 +-
bigtable/src/filter_composing_condition.php | 4 +-
bigtable/src/filter_composing_interleave.php | 4 +-
bigtable/src/filter_limit_block_all.php | 2 +-
bigtable/src/filter_limit_cells_per_col.php | 2 +-
bigtable/src/filter_limit_cells_per_row.php | 2 +-
.../src/filter_limit_cells_per_row_offset.php | 2 +-
.../src/filter_limit_col_family_regex.php | 2 +-
.../src/filter_limit_col_qualifier_regex.php | 2 +-
bigtable/src/filter_limit_col_range.php | 2 +-
bigtable/src/filter_limit_pass_all.php | 2 +-
bigtable/src/filter_limit_row_regex.php | 2 +-
bigtable/src/filter_limit_row_sample.php | 2 +-
bigtable/src/filter_limit_timestamp_range.php | 2 +-
bigtable/src/filter_limit_value_range.php | 2 +-
bigtable/src/filter_limit_value_regex.php | 2 +-
bigtable/src/filter_modify_apply_label.php | 2 +-
bigtable/src/filter_modify_strip_value.php | 2 +-
bigtable/src/get_instance.php | 2 +-
bigtable/src/insert_update_rows.php | 2 +-
bigtable/src/list_tables.php | 1 +
bigtable/src/read_filter.php | 2 +-
bigtable/src/read_prefix.php | 2 +-
bigtable/src/read_row.php | 2 +-
bigtable/src/read_row_partial.php | 2 +-
bigtable/src/read_row_range.php | 2 +-
bigtable/src/read_row_ranges.php | 2 +-
bigtable/src/read_rows.php | 2 +-
bigtable/src/write_batch.php | 4 +-
bigtable/src/write_simple.php | 2 +-
cloud_sql/mysql/pdo/src/Votes.php | 6 +-
cloud_sql/postgres/pdo/src/Votes.php | 6 +-
cloud_sql/sqlserver/pdo/src/Votes.php | 6 +-
.../src/disable_usage_export_bucket.php | 5 +-
.../start_instance_with_encryption_key.php | 5 +-
datastore/api/src/functions/concepts.php | 46 ++++----
datastore/tutorial/src/delete_task.php | 2 +-
datastore/tutorial/src/mark_done.php | 2 +-
dlp/src/deidentify_dates.php | 8 +-
dlp/src/deidentify_deterministic.php | 2 +-
...nspect_send_data_to_hybrid_job_trigger.php | 3 +-
firestore/src/City.php | 21 +++-
.../src/solution_sharded_counter_create.php | 2 +-
.../solution_sharded_counter_increment.php | 4 +-
iap/src/validate_jwt.php | 25 +++--
kms/src/create_key_asymmetric_decrypt.php | 2 +-
kms/src/create_key_asymmetric_sign.php | 2 +-
kms/src/create_key_hsm.php | 2 +-
kms/src/create_key_labels.php | 2 +-
kms/src/create_key_mac.php | 2 +-
kms/src/create_key_ring.php | 2 +-
kms/src/create_key_rotation_schedule.php | 2 +-
.../create_key_symmetric_encrypt_decrypt.php | 2 +-
kms/src/create_key_version.php | 2 +-
kms/src/disable_key_version.php | 2 +-
kms/src/enable_key_version.php | 2 +-
kms/src/encrypt_asymmetric.php | 2 +-
kms/src/iam_remove_member.php | 2 +-
kms/src/update_key_add_rotation.php | 2 +-
kms/src/update_key_remove_labels.php | 2 +-
kms/src/update_key_remove_rotation.php | 2 +-
kms/src/update_key_update_labels.php | 2 +-
kms/src/verify_asymmetric_ec.php | 2 +-
kms/src/verify_asymmetric_rsa.php | 2 +-
logging/src/update_sink.php | 2 +-
logging/src/write_with_monolog_logger.php | 3 +-
logging/src/write_with_psr_logger.php | 2 +
.../create_job_with_concatenated_inputs.php | 8 +-
media/videostitcher/src/create_cdn_key.php | 4 +-
media/videostitcher/src/update_cdn_key.php | 4 +-
monitoring/src/alert_create_channel.php | 2 +-
monitoring/src/alert_delete_channel.php | 3 +-
monitoring/src/alert_replace_channels.php | 4 +-
monitoring/src/alert_restore_policies.php | 12 +-
monitoring/src/list_uptime_check_ips.php | 2 +-
monitoring/src/list_uptime_checks.php | 2 +-
monitoring/src/read_timeseries_align.php | 2 +-
monitoring/src/read_timeseries_fields.php | 2 +-
monitoring/src/read_timeseries_reduce.php | 2 +-
monitoring/src/read_timeseries_simple.php | 2 +-
monitoring/src/update_uptime_check.php | 14 ++-
pubsub/api/src/create_avro_schema.php | 7 +-
.../api/src/create_bigquery_subscription.php | 2 +-
pubsub/api/src/create_proto_schema.php | 5 +-
.../src/create_subscription_with_filter.php | 8 +-
.../src/dead_letter_update_subscription.php | 8 +-
pubsub/api/src/publish_avro_records.php | 3 +-
pubsub/api/src/pubsub_client.php | 2 +
spanner/src/delete_data_with_dml.php | 2 +-
spanner/src/get_commit_stats.php | 2 +-
spanner/src/insert_data_with_dml.php | 2 +-
.../src/list_instance_config_operations.php | 2 +-
spanner/src/list_instance_configs.php | 6 +-
spanner/src/pg_numeric_data_type.php | 2 +-
spanner/src/set_transaction_tag.php | 2 +-
spanner/src/update_data_with_dml.php | 2 +-
spanner/src/update_data_with_dml_structs.php | 2 +-
.../src/update_data_with_dml_timestamp.php | 2 +-
spanner/src/write_data_with_dml.php | 2 +-
.../src/write_data_with_dml_transaction.php | 2 +-
spanner/src/write_read_with_dml.php | 2 +-
storage/src/upload_object.php | 4 +-
storage/src/upload_object_from_memory.php | 4 +-
storage/src/upload_with_kms_key.php | 4 +-
tasks/src/create_http_task.php | 5 +-
testing/composer.json | 1 +
.../compute/cloud-client/instances.neon.dist | 5 +
testing/phpstan/default.neon.dist | 3 +
testing/phpstan/pubsub/api.neon.dist | 8 ++
testing/run_staticanalysis_check.sh | 106 ++++++++++++++++++
testing/sample_helpers.php | 10 +-
vision/src/detect_face.php | 2 +-
vision/src/detect_label.php | 2 +-
vision/src/detect_label_gcs.php | 2 +-
vision/src/detect_pdf_gcs.php | 2 +-
vision/src/detect_web_with_geo_metadata.php | 2 +-
133 files changed, 463 insertions(+), 246 deletions(-)
create mode 100644 testing/phpstan/compute/cloud-client/instances.neon.dist
create mode 100644 testing/phpstan/default.neon.dist
create mode 100644 testing/phpstan/pubsub/api.neon.dist
create mode 100644 testing/run_staticanalysis_check.sh
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index db80ccde4e..c4ddad101f 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -21,19 +21,23 @@ jobs:
staticanalysis:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ github.event.pull_request.head.ref }}
+ fetch-depth: 5
- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.0'
-
+ - uses: jwalton/gh-find-current-pr@v1
+ id: findPr
+ with:
+ state: open
- name: Run Script
run: |
- composer global require phpstan/phpstan
- for dir in $(find * -type d -name src -not -path 'appengine/*' -not -path '*/vendor/*' -exec dirname {} \;);
- do
- echo -e "\n RUNNING for => $dir\n"
- composer install --working-dir=$dir --ignore-platform-reqs
- echo " autoload.php
- ~/.composer/vendor/bin/phpstan analyse $dir/src --autoload-file=autoload.php
- done
+ composer install -d testing/
+ git fetch --no-tags --prune --depth=5 origin main
+ bash testing/run_staticanalysis_check.sh
+ env:
+ PULL_REQUEST_NUMBER: ${{ steps.findPr.outputs.pr }}
+
diff --git a/analyticsdata/src/get_common_metadata.php b/analyticsdata/src/get_common_metadata.php
index 5a8d9a1141..3019f8b5c3 100644
--- a/analyticsdata/src/get_common_metadata.php
+++ b/analyticsdata/src/get_common_metadata.php
@@ -36,7 +36,7 @@
/**
* Retrieves dimensions and metrics available for all Google Analytics 4 properties.
*/
-function get_common_metadata()
+function get_common_metadata(): void
{
// Create an instance of the Google Analytics Data API client library.
$client = new BetaAnalyticsDataClient();
@@ -56,6 +56,7 @@ function get_common_metadata()
$response = $client->getMetadata($request);
} catch (ApiException $ex) {
printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
+ return;
}
print('Dimensions and metrics available for all Google Analytics 4 properties:');
diff --git a/analyticsdata/src/get_metadata_by_property_id.php b/analyticsdata/src/get_metadata_by_property_id.php
index 3d58c0b26a..178a748761 100644
--- a/analyticsdata/src/get_metadata_by_property_id.php
+++ b/analyticsdata/src/get_metadata_by_property_id.php
@@ -52,6 +52,7 @@ function get_metadata_by_property_id(string $propertyId)
$response = $client->getMetadata($request);
} catch (ApiException $ex) {
printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
+ return;
}
printf(
diff --git a/analyticsdata/src/run_report_with_aggregations.php b/analyticsdata/src/run_report_with_aggregations.php
index 206dbc0a1c..a2ef2affcb 100644
--- a/analyticsdata/src/run_report_with_aggregations.php
+++ b/analyticsdata/src/run_report_with_aggregations.php
@@ -38,7 +38,7 @@
use Google\Analytics\Data\V1beta\RunReportResponse;
/**
- * @param string $propertyID Your GA-4 Property ID
+ * @param string $propertyId Your GA-4 Property ID
* Runs a report which includes total, maximum and minimum values
* for each metric.
*/
diff --git a/analyticsdata/src/run_report_with_cohorts.php b/analyticsdata/src/run_report_with_cohorts.php
index 625183e786..29ec2dc7d5 100644
--- a/analyticsdata/src/run_report_with_cohorts.php
+++ b/analyticsdata/src/run_report_with_cohorts.php
@@ -40,7 +40,7 @@
use Google\Analytics\Data\V1beta\RunReportResponse;
/**
- * @param string $propertyID Your GA-4 Property ID
+ * @param string $propertyId Your GA-4 Property ID
* Runs a report on a cohort of users whose first session happened on the
* same week. The number of active users and user retention rate is calculated
* for the cohort using WEEKLY granularity.
diff --git a/analyticsdata/src/run_report_with_date_ranges.php b/analyticsdata/src/run_report_with_date_ranges.php
index a75f6eca82..aceb328d57 100644
--- a/analyticsdata/src/run_report_with_date_ranges.php
+++ b/analyticsdata/src/run_report_with_date_ranges.php
@@ -37,7 +37,7 @@
use Google\Analytics\Data\V1beta\RunReportResponse;
/**
- * @param string $propertyID Your GA-4 Property ID
+ * @param string $propertyId Your GA-4 Property ID
* Runs a report using two date ranges.
*/
function run_report_with_date_ranges(string $propertyId)
diff --git a/analyticsdata/src/run_report_with_multiple_dimensions.php b/analyticsdata/src/run_report_with_multiple_dimensions.php
index c0e540f032..4b7f7ebd32 100644
--- a/analyticsdata/src/run_report_with_multiple_dimensions.php
+++ b/analyticsdata/src/run_report_with_multiple_dimensions.php
@@ -37,7 +37,7 @@
use Google\Analytics\Data\V1beta\RunReportResponse;
/**
- * @param string $propertyID Your GA-4 Property ID
+ * @param string $propertyId Your GA-4 Property ID
* Runs a report of active users grouped by three dimensions.
*/
function run_report_with_multiple_dimensions(string $propertyId)
diff --git a/analyticsdata/src/run_report_with_multiple_metrics.php b/analyticsdata/src/run_report_with_multiple_metrics.php
index d6c8e2c260..e96c9829c8 100644
--- a/analyticsdata/src/run_report_with_multiple_metrics.php
+++ b/analyticsdata/src/run_report_with_multiple_metrics.php
@@ -37,7 +37,7 @@
use Google\Analytics\Data\V1beta\RunReportResponse;
/**
- * @param string $propertyID Your GA-4 Property ID
+ * @param string $propertyId Your GA-4 Property ID
* Runs a report of active users grouped by three metrics.
*/
function run_report_with_multiple_metrics(string $propertyId)
diff --git a/analyticsdata/src/run_report_with_named_date_ranges.php b/analyticsdata/src/run_report_with_named_date_ranges.php
index 9d0357fce8..59b71ff7da 100644
--- a/analyticsdata/src/run_report_with_named_date_ranges.php
+++ b/analyticsdata/src/run_report_with_named_date_ranges.php
@@ -37,7 +37,7 @@
use Google\Analytics\Data\V1beta\RunReportResponse;
/**
- * @param string $propertyID Your GA-4 Property ID
+ * @param string $propertyId Your GA-4 Property ID
* Runs a report using named date ranges.
*/
function run_report_with_named_date_ranges(string $propertyId)
diff --git a/asset/src/batch_get_assets_history.php b/asset/src/batch_get_assets_history.php
index 747f0e2b0e..2ea1e2bf59 100644
--- a/asset/src/batch_get_assets_history.php
+++ b/asset/src/batch_get_assets_history.php
@@ -23,14 +23,23 @@
use Google\Cloud\Asset\V1\TimeWindow;
use Google\Protobuf\Timestamp;
-function batch_get_assets_history(string $projectId, array $assetNames)
+/**
+ * @param string $projectId Tthe project Id for list assets.
+ * @param string[] $assetNames (Optional) Asset types to list for.
+ */
+function batch_get_assets_history(string $projectId, array $assetNames): void
{
$client = new AssetServiceClient();
$formattedParent = $client->projectName($projectId);
$contentType = ContentType::RESOURCE;
$readTimeWindow = new TimeWindow(['start_time' => new Timestamp(['seconds' => time()])]);
- $resp = $client->batchGetAssetsHistory($formattedParent, $contentType, $readTimeWindow, ['assetNames' => $assetNames]);
+ $resp = $client->batchGetAssetsHistory(
+ $formattedParent,
+ $contentType,
+ $readTimeWindow,
+ ['assetNames' => $assetNames]
+ );
# Do things with response.
print($resp->serializeToString());
diff --git a/asset/src/list_assets.php b/asset/src/list_assets.php
index 6d587a6fa3..bed0d3cb08 100644
--- a/asset/src/list_assets.php
+++ b/asset/src/list_assets.php
@@ -21,12 +21,15 @@
use Google\Cloud\Asset\V1\AssetServiceClient;
/**
- * @param string $projectId Tthe project Id for list assets.
- * @param string|array $assetTypes (Optional) Asset types to list for.
- * @param int $pageSize (Optional) Size of one result page.
+ * @param string $projectId Tthe project Id for list assets.
+ * @param string[] $assetTypes (Optional) Asset types to list for.
+ * @param int $pageSize (Optional) Size of one result page.
*/
-function list_assets(string $projectId, array $assetTypes = [], int $pageSize = null)
-{
+function list_assets(
+ string $projectId,
+ array $assetTypes = [],
+ int $pageSize = null
+): void {
// Instantiate a client.
$client = new AssetServiceClient();
diff --git a/asset/src/search_all_resources.php b/asset/src/search_all_resources.php
index 3434851d4b..c7fdbda86b 100644
--- a/asset/src/search_all_resources.php
+++ b/asset/src/search_all_resources.php
@@ -21,12 +21,12 @@
use Google\Cloud\Asset\V1\AssetServiceClient;
/**
- * @param string $scope Scope of the search
- * @param string $query (Optional) Query statement
- * @param string|array $assetTypes (Optional) Asset types to search for
- * @param int $pageSize (Optional) Size of each result page
- * @param string $pageToken (Optional) Token produced by the preceding call
- * @param string $orderBy (Optional) Fields to sort the results
+ * @param string $scope Scope of the search
+ * @param string $query (Optional) Query statement
+ * @param string[] $assetTypes (Optional) Asset types to search for
+ * @param int $pageSize (Optional) Size of each result page
+ * @param string $pageToken (Optional) Token produced by the preceding call
+ * @param string $orderBy (Optional) Fields to sort the results
*/
function search_all_resources(
string $scope,
@@ -35,7 +35,7 @@ function search_all_resources(
int $pageSize = 0,
string $pageToken = '',
string $orderBy = ''
-) {
+): void {
// Instantiate a client.
$asset = new AssetServiceClient();
diff --git a/asset/test/assetSearchTest.php b/asset/test/assetSearchTest.php
index c5db6e0ad0..7d05c01cce 100644
--- a/asset/test/assetSearchTest.php
+++ b/asset/test/assetSearchTest.php
@@ -18,6 +18,7 @@
namespace Google\Cloud\Samples\Asset;
use Google\Cloud\BigQuery\BigQueryClient;
+use Google\Cloud\TestUtils\EventuallyConsistentTestTrait;
use Google\Cloud\TestUtils\TestTrait;
use PHPUnit\Framework\TestCase;
use PHPUnitRetry\RetryTrait;
@@ -30,6 +31,7 @@
*/
class assetSearchTest extends TestCase
{
+ use EventuallyConsistentTestTrait;
use RetryTrait;
use TestTrait;
@@ -55,12 +57,16 @@ public function testSearchAllResources()
$scope = 'projects/' . self::$projectId;
$query = 'name:' . self::$datasetId;
- $output = $this->runFunctionSnippet('search_all_resources', [
- $scope,
- $query
- ]);
+ $this->runEventuallyConsistentTest(
+ function () use ($scope, $query) {
+ $output = $this->runFunctionSnippet('search_all_resources', [
+ $scope,
+ $query
+ ]);
- $this->assertStringContainsString(self::$datasetId, $output);
+ $this->assertStringContainsString(self::$datasetId, $output);
+ }
+ );
}
public function testSearchAllIamPolicies()
@@ -68,10 +74,14 @@ public function testSearchAllIamPolicies()
$scope = 'projects/' . self::$projectId;
$query = 'policy:roles/owner';
- $output = $this->runFunctionSnippet('search_all_iam_policies', [
- $scope,
- $query
- ]);
- $this->assertStringContainsString(self::$projectId, $output);
+ $this->runEventuallyConsistentTest(
+ function () use ($scope, $query) {
+ $output = $this->runFunctionSnippet('search_all_iam_policies', [
+ $scope,
+ $query
+ ]);
+ $this->assertStringContainsString(self::$projectId, $output);
+ }
+ );
}
}
diff --git a/asset/test/assetTest.php b/asset/test/assetTest.php
index ae2b83a45d..3d3d6b1717 100644
--- a/asset/test/assetTest.php
+++ b/asset/test/assetTest.php
@@ -18,6 +18,7 @@
namespace Google\Cloud\Samples\Asset;
use Google\Cloud\Storage\StorageClient;
+use Google\Cloud\TestUtils\EventuallyConsistentTestTrait;
use Google\Cloud\TestUtils\TestTrait;
use PHPUnit\Framework\TestCase;
use PHPUnitRetry\RetryTrait;
@@ -30,6 +31,7 @@
*/
class assetTest extends TestCase
{
+ use EventuallyConsistentTestTrait;
use RetryTrait;
use TestTrait;
@@ -53,36 +55,50 @@ public function testExportAssets()
{
$fileName = 'my-assets.txt';
$dumpFilePath = 'gs://' . self::$bucketName . '/' . $fileName;
- $output = $this->runFunctionSnippet('export_assets', [
- 'projectId' => self::$projectId,
- 'dumpFilePath' => $dumpFilePath,
- ]);
- $assetFile = self::$bucket->object($fileName);
- $this->assertEquals($assetFile->name(), $fileName);
- $assetFile->delete();
+
+ $this->runEventuallyConsistentTest(
+ function () use ($fileName, $dumpFilePath) {
+ $output = $this->runFunctionSnippet('export_assets', [
+ 'projectId' => self::$projectId,
+ 'dumpFilePath' => $dumpFilePath,
+ ]);
+ $assetFile = self::$bucket->object($fileName);
+ $this->assertEquals($assetFile->name(), $fileName);
+ $assetFile->delete();
+ }
+ );
}
public function testListAssets()
{
$assetName = '//storage.googleapis.com/' . self::$bucketName;
- $output = $this->runFunctionSnippet('list_assets', [
- 'projectId' => self::$projectId,
- 'assetTypes' => ['storage.googleapis.com/Bucket'],
- 'pageSize' => 1000,
- ]);
- $this->assertStringContainsString($assetName, $output);
+ $this->runEventuallyConsistentTest(
+ function () use ($assetName) {
+ $output = $this->runFunctionSnippet('list_assets', [
+ 'projectId' => self::$projectId,
+ 'assetTypes' => ['storage.googleapis.com/Bucket'],
+ 'pageSize' => 1000,
+ ]);
+
+ $this->assertStringContainsString($assetName, $output);
+ }
+ );
}
public function testBatchGetAssetsHistory()
{
$assetName = '//storage.googleapis.com/' . self::$bucketName;
- $output = $this->runFunctionSnippet('batch_get_assets_history', [
- 'projectId' => self::$projectId,
- 'assetNames' => [$assetName],
- ]);
+ $this->runEventuallyConsistentTest(
+ function () use ($assetName) {
+ $output = $this->runFunctionSnippet('batch_get_assets_history', [
+ 'projectId' => self::$projectId,
+ 'assetNames' => [$assetName],
+ ]);
- $this->assertStringContainsString($assetName, $output);
+ $this->assertStringContainsString($assetName, $output);
+ }
+ );
}
}
diff --git a/bigquery/api/src/bigquery_client.php b/bigquery/api/src/bigquery_client.php
index e616a1aa49..340567ef3a 100644
--- a/bigquery/api/src/bigquery_client.php
+++ b/bigquery/api/src/bigquery_client.php
@@ -24,6 +24,7 @@
if (isset($argv)) {
return print("This file is for example only and cannot be executed\n");
}
+$projectId = '';
/**
* This file is to be used as an example only!
diff --git a/bigquery/api/src/get_table.php b/bigquery/api/src/get_table.php
index e836d2647c..96a40757cf 100644
--- a/bigquery/api/src/get_table.php
+++ b/bigquery/api/src/get_table.php
@@ -24,6 +24,9 @@
if (isset($argv)) {
return print("This file is for example only and cannot be executed\n");
}
+$projectId = '';
+$datasetId = '';
+$tableId = '';
# [START bigquery_get_table]
use Google\Cloud\BigQuery\BigQueryClient;
diff --git a/bigquery/api/src/stream_row.php b/bigquery/api/src/stream_row.php
index fa320c9135..943da714ff 100644
--- a/bigquery/api/src/stream_row.php
+++ b/bigquery/api/src/stream_row.php
@@ -32,7 +32,7 @@
* @param string $projectId The project Id of your Google Cloud Project.
* @param string $datasetId The BigQuery dataset ID.
* @param string $tableId The BigQuery table ID.
- * @param array $data Json encoded data For eg,
+ * @param string $data Json encoded data For eg,
* $data = json_encode([
* "field1" => "value1",
* "field2" => "value2",
diff --git a/bigtable/src/filter_composing_chain.php b/bigtable/src/filter_composing_chain.php
index e0c37ad859..55f921bc3a 100644
--- a/bigtable/src/filter_composing_chain.php
+++ b/bigtable/src/filter_composing_chain.php
@@ -61,7 +61,7 @@ function filter_composing_chain(
// [END bigtable_filters_composing_chain]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_composing_condition.php b/bigtable/src/filter_composing_condition.php
index a16dd68772..8ab84ce407 100644
--- a/bigtable/src/filter_composing_condition.php
+++ b/bigtable/src/filter_composing_condition.php
@@ -47,7 +47,7 @@ function filter_composing_condition(
$filter = Filter::condition(
Filter::chain()
- ->addFilter(Filter::value()->exactMatch(unpack('C*', 1)))
+ ->addFilter(Filter::value()->exactMatch('1'))
->addFilter(Filter::qualifier()->exactMatch('data_plan_10gb'))
)
->then(Filter::label('passed-filter'))
@@ -65,7 +65,7 @@ function filter_composing_condition(
// [END bigtable_filters_composing_condition]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_composing_interleave.php b/bigtable/src/filter_composing_interleave.php
index 8bbcb807e0..6b86ce822c 100644
--- a/bigtable/src/filter_composing_interleave.php
+++ b/bigtable/src/filter_composing_interleave.php
@@ -46,7 +46,7 @@ function filter_composing_interleave(
$table = $dataClient->table($instanceId, $tableId);
$filter = Filter::interleave()
- ->addFilter(Filter::value()->exactMatch(unpack('C*', 1)))
+ ->addFilter(Filter::value()->exactMatch('1'))
->addFilter(Filter::qualifier()->exactMatch('os_build'));
$rows = $table->readRows([
@@ -61,7 +61,7 @@ function filter_composing_interleave(
// [END bigtable_filters_composing_interleave]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_block_all.php b/bigtable/src/filter_limit_block_all.php
index d6048a8368..543347b489 100644
--- a/bigtable/src/filter_limit_block_all.php
+++ b/bigtable/src/filter_limit_block_all.php
@@ -59,7 +59,7 @@ function filter_limit_block_all(
// [END bigtable_filters_limit_block_all]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_cells_per_col.php b/bigtable/src/filter_limit_cells_per_col.php
index 6319fcace9..47b2fb2ffa 100644
--- a/bigtable/src/filter_limit_cells_per_col.php
+++ b/bigtable/src/filter_limit_cells_per_col.php
@@ -59,7 +59,7 @@ function filter_limit_cells_per_col(
// [END bigtable_filters_limit_cells_per_col]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_cells_per_row.php b/bigtable/src/filter_limit_cells_per_row.php
index 460818204d..f33bab55f1 100644
--- a/bigtable/src/filter_limit_cells_per_row.php
+++ b/bigtable/src/filter_limit_cells_per_row.php
@@ -59,7 +59,7 @@ function filter_limit_cells_per_row(
// [END bigtable_filters_limit_cells_per_row]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_cells_per_row_offset.php b/bigtable/src/filter_limit_cells_per_row_offset.php
index 062bcdda5c..6a2bb451b0 100644
--- a/bigtable/src/filter_limit_cells_per_row_offset.php
+++ b/bigtable/src/filter_limit_cells_per_row_offset.php
@@ -59,7 +59,7 @@ function filter_limit_cells_per_row_offset(
// [END bigtable_filters_limit_cells_per_row_offset]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_col_family_regex.php b/bigtable/src/filter_limit_col_family_regex.php
index dcab0ca27c..fff1c13a15 100644
--- a/bigtable/src/filter_limit_col_family_regex.php
+++ b/bigtable/src/filter_limit_col_family_regex.php
@@ -59,7 +59,7 @@ function filter_limit_col_family_regex(
// [END bigtable_filters_limit_col_family_regex]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_col_qualifier_regex.php b/bigtable/src/filter_limit_col_qualifier_regex.php
index f624c059b6..dc8cef4693 100644
--- a/bigtable/src/filter_limit_col_qualifier_regex.php
+++ b/bigtable/src/filter_limit_col_qualifier_regex.php
@@ -59,7 +59,7 @@ function filter_limit_col_qualifier_regex(
// [END bigtable_filters_limit_col_qualifier_regex]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_col_range.php b/bigtable/src/filter_limit_col_range.php
index f7f8cc612d..f9604bcd53 100644
--- a/bigtable/src/filter_limit_col_range.php
+++ b/bigtable/src/filter_limit_col_range.php
@@ -62,7 +62,7 @@ function filter_limit_col_range(
// [END bigtable_filters_limit_col_range]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_pass_all.php b/bigtable/src/filter_limit_pass_all.php
index fa93437835..06314eebcf 100644
--- a/bigtable/src/filter_limit_pass_all.php
+++ b/bigtable/src/filter_limit_pass_all.php
@@ -59,7 +59,7 @@ function filter_limit_pass_all(
// [END bigtable_filters_limit_pass_all]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_row_regex.php b/bigtable/src/filter_limit_row_regex.php
index 4df7f2ea5f..4a69f1d784 100644
--- a/bigtable/src/filter_limit_row_regex.php
+++ b/bigtable/src/filter_limit_row_regex.php
@@ -59,7 +59,7 @@ function filter_limit_row_regex(
// [END bigtable_filters_limit_row_regex]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_row_sample.php b/bigtable/src/filter_limit_row_sample.php
index b0d25570ea..ae10f34a88 100644
--- a/bigtable/src/filter_limit_row_sample.php
+++ b/bigtable/src/filter_limit_row_sample.php
@@ -59,7 +59,7 @@ function filter_limit_row_sample(
// [END bigtable_filters_limit_row_sample]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_timestamp_range.php b/bigtable/src/filter_limit_timestamp_range.php
index 0d0cf8f4c7..b652886cae 100644
--- a/bigtable/src/filter_limit_timestamp_range.php
+++ b/bigtable/src/filter_limit_timestamp_range.php
@@ -66,7 +66,7 @@ function filter_limit_timestamp_range(
// [END bigtable_filters_limit_timestamp_range]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_value_range.php b/bigtable/src/filter_limit_value_range.php
index abcbfb3be5..e9176f0ea8 100644
--- a/bigtable/src/filter_limit_value_range.php
+++ b/bigtable/src/filter_limit_value_range.php
@@ -62,7 +62,7 @@ function filter_limit_value_range(
// [END bigtable_filters_limit_value_range]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_limit_value_regex.php b/bigtable/src/filter_limit_value_regex.php
index 6ba48cf7d4..0b0602a5ba 100644
--- a/bigtable/src/filter_limit_value_regex.php
+++ b/bigtable/src/filter_limit_value_regex.php
@@ -59,7 +59,7 @@ function filter_limit_value_regex(
// [END bigtable_filters_limit_value_regex]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_modify_apply_label.php b/bigtable/src/filter_modify_apply_label.php
index 02c4f46be8..a8b16f8c1d 100644
--- a/bigtable/src/filter_modify_apply_label.php
+++ b/bigtable/src/filter_modify_apply_label.php
@@ -59,7 +59,7 @@ function filter_modify_apply_label(
// [END bigtable_filters_modify_apply_label]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/filter_modify_strip_value.php b/bigtable/src/filter_modify_strip_value.php
index 5fb521b3ec..d1fa692db7 100644
--- a/bigtable/src/filter_modify_strip_value.php
+++ b/bigtable/src/filter_modify_strip_value.php
@@ -59,7 +59,7 @@ function filter_modify_strip_value(
// [END bigtable_filters_modify_strip_value]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/get_instance.php b/bigtable/src/get_instance.php
index 7d5daa9b4a..d0674d11de 100644
--- a/bigtable/src/get_instance.php
+++ b/bigtable/src/get_instance.php
@@ -67,7 +67,7 @@ function get_instance(
// Labels are an object of the MapField class which implement the IteratorAggregate, Countable
// and ArrayAccess interfaces so you can do the following:
printf("\tNum of Labels: " . $labels->count() . PHP_EOL);
- printf("\tLabel with a key(dev-label): " . ($labels->offsetExists('dev-label') ? $labels['dev-label'] : 'N/A') . PHP_EOL);
+ printf("\tLabel with a key(dev-label): " . ($labels['dev-label'] ?? 'N/A') . PHP_EOL);
// we can even loop over all the labels
foreach ($labels as $key => $val) {
diff --git a/bigtable/src/insert_update_rows.php b/bigtable/src/insert_update_rows.php
index f1d82de874..63acfa90bc 100644
--- a/bigtable/src/insert_update_rows.php
+++ b/bigtable/src/insert_update_rows.php
@@ -102,7 +102,7 @@ function insert_update_rows(
printf('Data inserted successfully!' . PHP_EOL);
}
-function time_in_microseconds()
+function time_in_microseconds(): float
{
$mt = microtime(true);
$mt = sprintf('%.03f', $mt);
diff --git a/bigtable/src/list_tables.php b/bigtable/src/list_tables.php
index 03a8c84369..a79dcbc4d4 100644
--- a/bigtable/src/list_tables.php
+++ b/bigtable/src/list_tables.php
@@ -44,6 +44,7 @@ function list_tables(
printf('Listing Tables:' . PHP_EOL);
$tables = $tableAdminClient->listTables($instanceName)->iterateAllElements();
+ $tables = iterator_to_array($tables);
if (empty($tables)) {
print('No table exists.' . PHP_EOL);
return;
diff --git a/bigtable/src/read_filter.php b/bigtable/src/read_filter.php
index 1e3e59fe1f..1f9c56814a 100644
--- a/bigtable/src/read_filter.php
+++ b/bigtable/src/read_filter.php
@@ -58,7 +58,7 @@ function read_filter(
// [END bigtable_reads_filter]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/read_prefix.php b/bigtable/src/read_prefix.php
index 5434c66d91..bec5f7f8b0 100644
--- a/bigtable/src/read_prefix.php
+++ b/bigtable/src/read_prefix.php
@@ -67,7 +67,7 @@ function read_prefix(
// [END bigtable_reads_prefix]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/read_row.php b/bigtable/src/read_row.php
index 82f4760d3d..2c32a70b8c 100644
--- a/bigtable/src/read_row.php
+++ b/bigtable/src/read_row.php
@@ -53,7 +53,7 @@ function read_row(
// [START bigtable_reads_print]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/read_row_partial.php b/bigtable/src/read_row_partial.php
index a60406ab08..3fef92a813 100644
--- a/bigtable/src/read_row_partial.php
+++ b/bigtable/src/read_row_partial.php
@@ -54,7 +54,7 @@ function read_row_partial(
// [END bigtable_reads_row_partial]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/read_row_range.php b/bigtable/src/read_row_range.php
index da3f42cef7..b6d45f5892 100644
--- a/bigtable/src/read_row_range.php
+++ b/bigtable/src/read_row_range.php
@@ -60,7 +60,7 @@ function read_row_range(
// [END bigtable_reads_row_range]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/read_row_ranges.php b/bigtable/src/read_row_ranges.php
index c82b82e24b..7fa67ef197 100644
--- a/bigtable/src/read_row_ranges.php
+++ b/bigtable/src/read_row_ranges.php
@@ -64,7 +64,7 @@ function read_row_ranges(
// [END bigtable_reads_row_ranges]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/read_rows.php b/bigtable/src/read_rows.php
index 12009624fa..c17b26fea6 100644
--- a/bigtable/src/read_rows.php
+++ b/bigtable/src/read_rows.php
@@ -55,7 +55,7 @@ function read_rows(
// [END bigtable_reads_rows]
// Helper function for printing the row data
-function print_row($key, $row)
+function print_row(string $key, array $row): void
{
printf('Reading data for row %s' . PHP_EOL, $key);
foreach ((array) $row as $family => $cols) {
diff --git a/bigtable/src/write_batch.php b/bigtable/src/write_batch.php
index 9da801723b..1d9f0a8933 100644
--- a/bigtable/src/write_batch.php
+++ b/bigtable/src/write_batch.php
@@ -49,10 +49,10 @@ function write_batch(
$columnFamilyId = 'stats_summary';
$mutations = [
(new Mutations())
- ->upsert($columnFamilyId, 'connected_wifi', 1, $timestampMicros)
+ ->upsert($columnFamilyId, 'connected_wifi', '1', $timestampMicros)
->upsert($columnFamilyId, 'os_build', '12155.0.0-rc1', $timestampMicros),
(new Mutations())
- ->upsert($columnFamilyId, 'connected_wifi', 1, $timestampMicros)
+ ->upsert($columnFamilyId, 'connected_wifi', '1', $timestampMicros)
->upsert($columnFamilyId, 'os_build', '12145.0.0-rc6', $timestampMicros)];
$table->mutateRows([
diff --git a/bigtable/src/write_simple.php b/bigtable/src/write_simple.php
index 1e9b20c1dd..336ecf196b 100644
--- a/bigtable/src/write_simple.php
+++ b/bigtable/src/write_simple.php
@@ -49,7 +49,7 @@ function write_simple(
$timestampMicros = time() * 1000 * 1000;
$columnFamilyId = 'stats_summary';
$mutations = (new Mutations())
- ->upsert($columnFamilyId, 'connected_cell', 1, $timestampMicros)
+ ->upsert($columnFamilyId, 'connected_cell', '1', $timestampMicros)
->upsert($columnFamilyId, 'connected_wifi', DataUtil::intToByteString(1), $timestampMicros)
->upsert($columnFamilyId, 'os_build', 'PQ2A.190405.003', $timestampMicros);
diff --git a/cloud_sql/mysql/pdo/src/Votes.php b/cloud_sql/mysql/pdo/src/Votes.php
index 8ca7a38bba..5148bf513d 100644
--- a/cloud_sql/mysql/pdo/src/Votes.php
+++ b/cloud_sql/mysql/pdo/src/Votes.php
@@ -66,7 +66,7 @@ public function createTableIfNotExists()
/**
* Returns a list of the last five votes
*
- * @return array
+ * @return array
*/
public function listVotes(): array
{
@@ -80,7 +80,7 @@ public function listVotes(): array
* Get the number of votes cast for a given value.
*
* @param string $value
- * @param int
+ * @return int
*/
public function getCountByValue(string $value): int
{
@@ -96,7 +96,7 @@ public function getCountByValue(string $value): int
* Insert a new vote into the database
*
* @param string $value The value to vote for.
- * @return boolean
+ * @return bool
*/
public function insertVote(string $value): bool
{
diff --git a/cloud_sql/postgres/pdo/src/Votes.php b/cloud_sql/postgres/pdo/src/Votes.php
index 83e6eeb5aa..89d6aec3b3 100644
--- a/cloud_sql/postgres/pdo/src/Votes.php
+++ b/cloud_sql/postgres/pdo/src/Votes.php
@@ -66,7 +66,7 @@ public function createTableIfNotExists()
/**
* Returns a list of the last five votes
*
- * @return array
+ * @return array
*/
public function listVotes(): array
{
@@ -80,7 +80,7 @@ public function listVotes(): array
* Get the number of votes cast for a given value.
*
* @param string $value
- * @param int
+ * @return int
*/
public function getCountByValue(string $value): int
{
@@ -96,7 +96,7 @@ public function getCountByValue(string $value): int
* Insert a new vote into the database
*
* @param string $value The value to vote for.
- * @return boolean
+ * @return bool
*/
public function insertVote(string $value): bool
{
diff --git a/cloud_sql/sqlserver/pdo/src/Votes.php b/cloud_sql/sqlserver/pdo/src/Votes.php
index 69d429af16..07b543374a 100644
--- a/cloud_sql/sqlserver/pdo/src/Votes.php
+++ b/cloud_sql/sqlserver/pdo/src/Votes.php
@@ -72,7 +72,7 @@ public function createTableIfNotExists()
/**
* Returns a list of the last five votes
*
- * @return array
+ * @return array
*/
public function listVotes(): array
{
@@ -86,7 +86,7 @@ public function listVotes(): array
* Get the number of votes cast for a given value.
*
* @param string $value
- * @param int
+ * @return int
*/
public function getCountByValue(string $value): int
{
@@ -102,7 +102,7 @@ public function getCountByValue(string $value): int
* Insert a new vote into the database
*
* @param string $value The value to vote for.
- * @return boolean
+ * @return bool
*/
public function insertVote(string $value): bool
{
diff --git a/compute/instances/src/disable_usage_export_bucket.php b/compute/instances/src/disable_usage_export_bucket.php
index f5ba386aca..8ce5aa74c4 100644
--- a/compute/instances/src/disable_usage_export_bucket.php
+++ b/compute/instances/src/disable_usage_export_bucket.php
@@ -26,6 +26,7 @@
# [START compute_usage_report_disable]
use Google\Cloud\Compute\V1\ProjectsClient;
use Google\Cloud\Compute\V1\Operation;
+use Google\Cloud\Compute\V1\UsageExportLocation;
/**
* Disable Compute Engine usage export bucket for the Cloud Project.
@@ -36,9 +37,9 @@
*/
function disable_usage_export_bucket(string $projectId)
{
- // Disable the usage export location by sending null as usageExportLocationResource.
+ // Disable the usage export location by sending empty UsageExportLocation as usageExportLocationResource.
$projectsClient = new ProjectsClient();
- $operation = $projectsClient->setUsageExportBucket($projectId, null);
+ $operation = $projectsClient->setUsageExportBucket($projectId, new UsageExportLocation());
// Wait for the operation to complete.
$operation->pollUntilComplete();
diff --git a/compute/instances/src/start_instance_with_encryption_key.php b/compute/instances/src/start_instance_with_encryption_key.php
index 95a7e4ae03..4bfee422b4 100644
--- a/compute/instances/src/start_instance_with_encryption_key.php
+++ b/compute/instances/src/start_instance_with_encryption_key.php
@@ -59,9 +59,12 @@ function start_instance_with_encryption_key(
$customerEncryptionKey = (new CustomerEncryptionKey())
->setRawKey($key);
+ /** @var \Google\Cloud\Compute\V1\AttachedDisk */
+ $disk = $instanceData->getDisks()[0];
+
// Prepare the information about disk encryption.
$diskData = (new CustomerEncryptionKeyProtectedDisk())
- ->setSource($instanceData->getDisks()[0]->getSource())
+ ->setSource($disk->getSource())
->setDiskEncryptionKey($customerEncryptionKey);
// Set request with one disk.
diff --git a/datastore/api/src/functions/concepts.php b/datastore/api/src/functions/concepts.php
index 0c0f4faf22..a5ba3cf9b3 100644
--- a/datastore/api/src/functions/concepts.php
+++ b/datastore/api/src/functions/concepts.php
@@ -19,7 +19,7 @@
use DateTime;
use Google\Cloud\Datastore\DatastoreClient;
-use Google\Cloud\Datastore\Entity;
+use Google\Cloud\Datastore\EntityInterface;
use Google\Cloud\Datastore\EntityIterator;
use Google\Cloud\Datastore\Key;
use Google\Cloud\Datastore\Query\GqlQuery;
@@ -40,7 +40,7 @@ function initialize_client()
* Create a Datastore entity.
*
* @param DatastoreClient $datastore
- * @return Entity
+ * @return EntityInterface
*/
function basic_entity(DatastoreClient $datastore)
{
@@ -59,7 +59,7 @@ function basic_entity(DatastoreClient $datastore)
* Create a Datastore entity and upsert it.
*
* @param DatastoreClient $datastore
- * @return Entity
+ * @return EntityInterface
*/
function upsert(DatastoreClient $datastore)
{
@@ -82,7 +82,7 @@ function upsert(DatastoreClient $datastore)
* an entity with the same key.
*
* @param DatastoreClient $datastore
- * @return Entity
+ * @return EntityInterface
*/
function insert(DatastoreClient $datastore)
{
@@ -102,7 +102,7 @@ function insert(DatastoreClient $datastore)
* Look up a Datastore entity with the given key.
*
* @param DatastoreClient $datastore
- * @return Entity|null
+ * @return EntityInterface|null
*/
function lookup(DatastoreClient $datastore)
{
@@ -117,7 +117,7 @@ function lookup(DatastoreClient $datastore)
* Update a Datastore entity in a transaction.
*
* @param DatastoreClient $datastore
- * @return Entity|null
+ * @return EntityInterface
*/
function update(DatastoreClient $datastore)
{
@@ -149,7 +149,7 @@ function delete(DatastoreClient $datastore, Key $taskKey)
* Upsert multiple Datastore entities.
*
* @param DatastoreClient $datastore
- * @param array $tasks
+ * @param array $tasks
*/
function batch_upsert(DatastoreClient $datastore, array $tasks)
{
@@ -162,8 +162,8 @@ function batch_upsert(DatastoreClient $datastore, array $tasks)
* Lookup multiple entities.
*
* @param DatastoreClient $datastore
- * @param array $keys
- * @return array
+ * @param array $keys
+ * @return array
*/
function batch_lookup(DatastoreClient $datastore, array $keys)
{
@@ -182,7 +182,7 @@ function batch_lookup(DatastoreClient $datastore, array $keys)
* Delete multiple Datastore entities with the given keys.
*
* @param DatastoreClient $datastore
- * @param array $keys
+ * @param array $keys
*/
function batch_delete(DatastoreClient $datastore, array $keys)
{
@@ -255,7 +255,7 @@ function key_with_multilevel_parent(DatastoreClient $datastore)
*
* @param DatastoreClient $datastore
* @param Key $key
- * @return Entity
+ * @return EntityInterface
*/
function properties(DatastoreClient $datastore, Key $key)
{
@@ -281,7 +281,7 @@ function properties(DatastoreClient $datastore, Key $key)
*
* @param DatastoreClient $datastore
* @param Key $key
- * @return Entity
+ * @return EntityInterface
*/
function array_value(DatastoreClient $datastore, Key $key)
{
@@ -347,7 +347,7 @@ function basic_gql_query(DatastoreClient $datastore)
*
* @param DatastoreClient $datastore
* @param Query|GqlQuery $query
- * @return EntityIterator
+ * @return EntityIterator
*/
function run_query(DatastoreClient $datastore, $query)
{
@@ -617,11 +617,11 @@ function limit(DatastoreClient $datastore)
* Fetch a query cursor.
*
* @param DatastoreClient $datastore
- * @param string $pageSize
+ * @param int $pageSize
* @param string $pageCursor
* @return array
*/
-function cursor_paging(DatastoreClient $datastore, $pageSize, $pageCursor = '')
+function cursor_paging(DatastoreClient $datastore, int $pageSize, string $pageCursor = '')
{
$query = $datastore->query()
->kind('Task')
@@ -769,7 +769,7 @@ function unindexed_property_query(DatastoreClient $datastore)
* Create an entity with two array properties.
*
* @param DatastoreClient $datastore
- * @return Entity
+ * @return EntityInterface
*/
function exploding_properties(DatastoreClient $datastore)
{
@@ -848,9 +848,9 @@ function transactional_retry(
* Insert an entity only if there is no entity with the same key.
*
* @param DatastoreClient $datastore
- * @param Entity $task
+ * @param EntityInterface $task
*/
-function get_or_create(DatastoreClient $datastore, Entity $task)
+function get_or_create(DatastoreClient $datastore, EntityInterface $task)
{
// [START datastore_transactional_get_or_create]
$transaction = $datastore->transaction();
@@ -866,7 +866,7 @@ function get_or_create(DatastoreClient $datastore, Entity $task)
* Run a query with an ancestor inside a transaction.
*
* @param DatastoreClient $datastore
- * @return array
+ * @return array
*/
function get_task_list_entities(DatastoreClient $datastore)
{
@@ -890,7 +890,7 @@ function get_task_list_entities(DatastoreClient $datastore)
* Create and run a query with readConsistency option.
*
* @param DatastoreClient $datastore
- * @return EntityIterator
+ * @return EntityIterator
*/
function eventual_consistent_query(DatastoreClient $datastore)
{
@@ -907,7 +907,7 @@ function eventual_consistent_query(DatastoreClient $datastore)
* Create an entity with a parent key.
*
* @param DatastoreClient $datastore
- * @return Entity
+ * @return EntityInterface
*/
function entity_with_parent(DatastoreClient $datastore)
{
@@ -1004,7 +1004,7 @@ function property_run_query(DatastoreClient $datastore)
* Create and run a property query with a kind.
*
* @param DatastoreClient $datastore
- * @return array string>
+ * @return array
*/
function property_by_kind_run_query(DatastoreClient $datastore)
{
@@ -1014,7 +1014,7 @@ function property_by_kind_run_query(DatastoreClient $datastore)
->kind('__property__')
->hasAncestor($ancestorKey);
$result = $datastore->runQuery($query);
- /* @var array string> $properties */
+ /* @var array $properties */
$properties = [];
/* @var Entity $entity */
foreach ($result as $entity) {
diff --git a/datastore/tutorial/src/delete_task.php b/datastore/tutorial/src/delete_task.php
index c7988e64b8..d7ae4e386f 100644
--- a/datastore/tutorial/src/delete_task.php
+++ b/datastore/tutorial/src/delete_task.php
@@ -24,7 +24,7 @@
* Delete a task with a given id.
*
* @param string $projectId The Google Cloud project ID.
- * @param $taskId
+ * @param string $taskId
*/
function delete_task(string $projectId, string $taskId)
{
diff --git a/datastore/tutorial/src/mark_done.php b/datastore/tutorial/src/mark_done.php
index 4094a056e5..4ebf5bcf03 100644
--- a/datastore/tutorial/src/mark_done.php
+++ b/datastore/tutorial/src/mark_done.php
@@ -24,7 +24,7 @@
* Mark a task with a given id as done.
*
* @param string $projectId The Google Cloud project ID.
- * @param int $taskId
+ * @param string $taskId
*/
function mark_done(string $projectId, string $taskId)
{
diff --git a/dlp/src/deidentify_dates.php b/dlp/src/deidentify_dates.php
index b7c05c2342..5309dfe7a4 100644
--- a/dlp/src/deidentify_dates.php
+++ b/dlp/src/deidentify_dates.php
@@ -51,8 +51,8 @@
* @param string $inputCsvFile The path to the CSV file to deidentify
* @param string $outputCsvFile The path to save the date-shifted CSV file to
* @param string $dateFieldNames The comma-separated list of (date) fields in the CSV file to date shift
- * @param string $lowerBoundDays The maximum number of days to shift a date backward
- * @param string $upperBoundDays The maximum number of days to shift a date forward
+ * @param int $lowerBoundDays The maximum number of days to shift a date backward
+ * @param int $upperBoundDays The maximum number of days to shift a date forward
* @param string $contextFieldName (Optional) The column to determine date shift amount based on
* @param string $keyName (Optional) The encrypted ('wrapped') AES-256 key to use when shifting dates
* @param string $wrappedKey (Optional) The name of the Cloud KMS key used to encrypt (wrap) the AES-256 key
@@ -62,8 +62,8 @@ function deidentify_dates(
string $inputCsvFile,
string $outputCsvFile,
string $dateFieldNames,
- string $lowerBoundDays,
- string $upperBoundDays,
+ int $lowerBoundDays,
+ int $upperBoundDays,
string $contextFieldName = '',
string $keyName = '',
string $wrappedKey = ''
diff --git a/dlp/src/deidentify_deterministic.php b/dlp/src/deidentify_deterministic.php
index 29bf72f33b..ee951eace3 100644
--- a/dlp/src/deidentify_deterministic.php
+++ b/dlp/src/deidentify_deterministic.php
@@ -48,7 +48,7 @@
* @param string $kmsKeyName The name of the Cloud KMS key used to encrypt ('wrap') the AES-256 key.
* Example: key_name = 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/keyRings/YOUR_KEYRING_NAME/cryptoKeys/YOUR_KEY_NAME'.
* @param string $infoTypeName The Info type name to be inspect.
- * @param string $surrogateType The name of the surrogate custom info type to use.
+ * @param string $surrogateTypeName The name of the surrogate custom info type to use.
* Only necessary if you want to reverse the deidentification process. Can be essentially any arbitrary
* string, as long as it doesn't appear in your dataset otherwise.
* @param string $wrappedAesKey The encrypted ('wrapped') AES-256 key to use.
diff --git a/dlp/src/inspect_send_data_to_hybrid_job_trigger.php b/dlp/src/inspect_send_data_to_hybrid_job_trigger.php
index 6cec8978de..49088d30ca 100644
--- a/dlp/src/inspect_send_data_to_hybrid_job_trigger.php
+++ b/dlp/src/inspect_send_data_to_hybrid_job_trigger.php
@@ -25,6 +25,7 @@
# [START dlp_inspect_send_data_to_hybrid_job_trigger]
+use Google\ApiCore\ApiException;
use Google\Cloud\Dlp\V2\Container;
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\ContentItem;
@@ -76,7 +77,7 @@ function inspect_send_data_to_hybrid_job_trigger(
$triggerJob = null;
try {
$triggerJob = $dlp->activateJobTrigger($name);
- } catch (\InvalidArgumentException $e) {
+ } catch (ApiException $e) {
$result = $dlp->listDlpJobs($parent, ['filter' => 'trigger_name=' . $name]);
foreach ($result as $job) {
$triggerJob = $job;
diff --git a/firestore/src/City.php b/firestore/src/City.php
index 48598a0af9..4c940c001c 100644
--- a/firestore/src/City.php
+++ b/firestore/src/City.php
@@ -26,19 +26,22 @@
# [START firestore_data_custom_type_definition]
class City
{
- /* var string */
+ /** @var string */
public $name;
- /* var string */
+ /** @var string */
public $state;
- /* var string */
+ /** @var string */
public $country;
- /* var bool */
+ /** @var bool */
public $capital;
- /* var int */
+ /** @var int */
public $population;
- /* var array */
+ /** @var array */
public $regions;
+ /**
+ * @param array $regions
+ */
public function __construct(
string $name,
string $state,
@@ -55,6 +58,9 @@ public function __construct(
$this->regions = $regions;
}
+ /**
+ * @param array $source
+ */
public static function fromArray(array $source): City
{
// implementation of fromArray is excluded for brevity
@@ -72,6 +78,9 @@ public static function fromArray(array $source): City
# [END_EXCLUDE]
}
+ /**
+ * @return array
+ */
public function toArray(): array
{
// implementation of toArray is excluded for brevity
diff --git a/firestore/src/solution_sharded_counter_create.php b/firestore/src/solution_sharded_counter_create.php
index 6cd896a54c..2e69f6e5e9 100644
--- a/firestore/src/solution_sharded_counter_create.php
+++ b/firestore/src/solution_sharded_counter_create.php
@@ -40,7 +40,7 @@ function solution_sharded_counter_create(string $projectId): void
$numShards = 10;
$ref = $db->collection('samples/php/distributedCounters');
for ($i = 0; $i < $numShards; $i++) {
- $doc = $ref->document($i);
+ $doc = $ref->document((string) $i);
$doc->set(['Cnt' => 0]);
}
# [END firestore_solution_sharded_counter_create]
diff --git a/firestore/src/solution_sharded_counter_increment.php b/firestore/src/solution_sharded_counter_increment.php
index b9981a04c0..2107d0df68 100644
--- a/firestore/src/solution_sharded_counter_increment.php
+++ b/firestore/src/solution_sharded_counter_increment.php
@@ -45,8 +45,8 @@ function solution_sharded_counter_increment(string $projectId): void
foreach ($docCollection as $doc) {
$numShards++;
}
- $shardIdx = random_int(0, $numShards - 1);
- $doc = $ref->document($shardIdx);
+ $shardIdx = random_int(0, max(1, $numShards) - 1);
+ $doc = $ref->document((string) $shardIdx);
$doc->update([
['path' => 'Cnt', 'value' => FieldValue::increment(1)]
]);
diff --git a/iap/src/validate_jwt.php b/iap/src/validate_jwt.php
index 91c53e0fbe..73e1722925 100644
--- a/iap/src/validate_jwt.php
+++ b/iap/src/validate_jwt.php
@@ -33,18 +33,19 @@
* @param string $cloudProjectNumber The project *number* for your Google
* Cloud project. This is returned by 'gcloud projects describe $PROJECT_ID',
* or in the Project Info card in Cloud Console.
- * @param string $cloud_project Your Google Cloud Project ID.
- *
- * @return (user_id, user_email).
+ * @param string $cloudProjectId Your Google Cloud Project ID.
*/
-function validate_jwt_from_app_engine($iapJwt, $cloudProjectNumber, $cloudProjectId)
-{
+function validate_jwt_from_app_engine(
+ string $iapJwt,
+ string $cloudProjectNumber,
+ string $cloudProjectId
+): void {
$expectedAudience = sprintf(
'/projects/%s/apps/%s',
$cloudProjectNumber,
$cloudProjectId
);
- return validate_jwt($iapJwt, $expectedAudience);
+ validate_jwt($iapJwt, $expectedAudience);
}
/**
@@ -58,8 +59,11 @@ function validate_jwt_from_app_engine($iapJwt, $cloudProjectNumber, $cloudProjec
* application. See https://cloud.google.com/iap/docs/signed-headers-howto
* for details on how to get this value.
*/
-function validate_jwt_from_compute_engine($iapJwt, $cloudProjectNumber, $backendServiceId)
-{
+function validate_jwt_from_compute_engine(
+ string $iapJwt,
+ string $cloudProjectNumber,
+ string $backendServiceId
+): void {
$expectedAudience = sprintf(
'/projects/%s/global/backendServices/%s',
$cloudProjectNumber,
@@ -76,7 +80,7 @@ function validate_jwt_from_compute_engine($iapJwt, $cloudProjectNumber, $backend
* App Engine: /projects/{PROJECT_NUMBER}/apps/{PROJECT_ID}
* Compute Engine: /projects/{PROJECT_NUMBER}/global/backendServices/{BACKEND_SERVICE_ID}
*/
-function validate_jwt($iapJwt, $expectedAudience)
+function validate_jwt(string $iapJwt, string $expectedAudience): void
{
// Validate the signature using the IAP cert URL.
$token = new AccessToken();
@@ -85,7 +89,8 @@ function validate_jwt($iapJwt, $expectedAudience)
]);
if (!$jwt) {
- return print('Failed to validate JWT: Invalid JWT');
+ print('Failed to validate JWT: Invalid JWT');
+ return;
}
// Validate token by checking issuer and audience fields.
diff --git a/kms/src/create_key_asymmetric_decrypt.php b/kms/src/create_key_asymmetric_decrypt.php
index e33da5fdc3..4ad5f4df62 100644
--- a/kms/src/create_key_asymmetric_decrypt.php
+++ b/kms/src/create_key_asymmetric_decrypt.php
@@ -32,7 +32,7 @@ function create_key_asymmetric_decrypt(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-asymmetric-decrypt-key'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/create_key_asymmetric_sign.php b/kms/src/create_key_asymmetric_sign.php
index 65c632cafd..c5de6a5b83 100644
--- a/kms/src/create_key_asymmetric_sign.php
+++ b/kms/src/create_key_asymmetric_sign.php
@@ -32,7 +32,7 @@ function create_key_asymmetric_sign(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-asymmetric-signing-key'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/create_key_hsm.php b/kms/src/create_key_hsm.php
index 37f284ff1d..5266615bb0 100644
--- a/kms/src/create_key_hsm.php
+++ b/kms/src/create_key_hsm.php
@@ -33,7 +33,7 @@ function create_key_hsm(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-hsm-key'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/create_key_labels.php b/kms/src/create_key_labels.php
index 6d77bc9e5b..461adc19e0 100644
--- a/kms/src/create_key_labels.php
+++ b/kms/src/create_key_labels.php
@@ -31,7 +31,7 @@ function create_key_labels(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-key-with-labels'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/create_key_mac.php b/kms/src/create_key_mac.php
index e0ada08bda..1e5f16eddf 100644
--- a/kms/src/create_key_mac.php
+++ b/kms/src/create_key_mac.php
@@ -32,7 +32,7 @@ function create_key_mac(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-mac-key'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/create_key_ring.php b/kms/src/create_key_ring.php
index efd1526edf..d73964ec49 100644
--- a/kms/src/create_key_ring.php
+++ b/kms/src/create_key_ring.php
@@ -27,7 +27,7 @@ function create_key_ring(
string $projectId = 'my-project',
string $locationId = 'us-east1',
string $id = 'my-key-ring'
-) {
+): KeyRing {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/create_key_rotation_schedule.php b/kms/src/create_key_rotation_schedule.php
index 2e7c077671..81d662be1b 100644
--- a/kms/src/create_key_rotation_schedule.php
+++ b/kms/src/create_key_rotation_schedule.php
@@ -33,7 +33,7 @@ function create_key_rotation_schedule(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-key-with-rotation-schedule'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/create_key_symmetric_encrypt_decrypt.php b/kms/src/create_key_symmetric_encrypt_decrypt.php
index a460cf12d2..78288fa1ae 100644
--- a/kms/src/create_key_symmetric_encrypt_decrypt.php
+++ b/kms/src/create_key_symmetric_encrypt_decrypt.php
@@ -31,7 +31,7 @@ function create_key_symmetric_encrypt_decrypt(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-symmetric-key'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/create_key_version.php b/kms/src/create_key_version.php
index 13bd25a63d..81101a4924 100644
--- a/kms/src/create_key_version.php
+++ b/kms/src/create_key_version.php
@@ -28,7 +28,7 @@ function create_key_version(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $keyId = 'my-key'
-) {
+): CryptoKeyVersion {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/disable_key_version.php b/kms/src/disable_key_version.php
index 68272b2294..c7131c4e1f 100644
--- a/kms/src/disable_key_version.php
+++ b/kms/src/disable_key_version.php
@@ -31,7 +31,7 @@ function disable_key_version(
string $keyRingId = 'my-key-ring',
string $keyId = 'my-key',
string $versionId = '123'
-) {
+): CryptoKeyVersion {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/enable_key_version.php b/kms/src/enable_key_version.php
index c934c2f0aa..dc8ac54faa 100644
--- a/kms/src/enable_key_version.php
+++ b/kms/src/enable_key_version.php
@@ -31,7 +31,7 @@ function enable_key_version(
string $keyRingId = 'my-key-ring',
string $keyId = 'my-key',
string $versionId = '123'
-) {
+): CryptoKeyVersion {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/encrypt_asymmetric.php b/kms/src/encrypt_asymmetric.php
index 1f2ea37e7c..39a99d14a5 100644
--- a/kms/src/encrypt_asymmetric.php
+++ b/kms/src/encrypt_asymmetric.php
@@ -27,7 +27,7 @@ function encrypt_asymmetric(
string $keyId = 'my-key',
string $versionId = '123',
string $plaintext = '...'
-) {
+): void {
// PHP has limited support for asymmetric encryption operations.
// Specifically, openssl_public_encrypt() does not allow customizing
// algorithms or padding. Thus, it is not currently possible to use PHP
diff --git a/kms/src/iam_remove_member.php b/kms/src/iam_remove_member.php
index 6cb56ebaab..27d24f6d4a 100644
--- a/kms/src/iam_remove_member.php
+++ b/kms/src/iam_remove_member.php
@@ -30,7 +30,7 @@ function iam_remove_member(
string $keyRingId = 'my-key-ring',
string $keyId = 'my-key',
string $member = 'user:foo@example.com'
-) {
+): Policy {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/update_key_add_rotation.php b/kms/src/update_key_add_rotation.php
index 92a82c39cd..3ea8e1c269 100644
--- a/kms/src/update_key_add_rotation.php
+++ b/kms/src/update_key_add_rotation.php
@@ -31,7 +31,7 @@ function update_key_add_rotation(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $keyId = 'my-key'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/update_key_remove_labels.php b/kms/src/update_key_remove_labels.php
index 6f17cea24a..8a20c9c64b 100644
--- a/kms/src/update_key_remove_labels.php
+++ b/kms/src/update_key_remove_labels.php
@@ -29,7 +29,7 @@ function update_key_remove_labels(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $keyId = 'my-key'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/update_key_remove_rotation.php b/kms/src/update_key_remove_rotation.php
index 0c8c048de4..9e89d5a9b9 100644
--- a/kms/src/update_key_remove_rotation.php
+++ b/kms/src/update_key_remove_rotation.php
@@ -29,7 +29,7 @@ function update_key_remove_rotation(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $keyId = 'my-key'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/update_key_update_labels.php b/kms/src/update_key_update_labels.php
index a5fe76f35e..41fc02e916 100644
--- a/kms/src/update_key_update_labels.php
+++ b/kms/src/update_key_update_labels.php
@@ -29,7 +29,7 @@ function update_key_update_labels(
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $keyId = 'my-key'
-) {
+): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/verify_asymmetric_ec.php b/kms/src/verify_asymmetric_ec.php
index e065b3edd6..1d1871836d 100644
--- a/kms/src/verify_asymmetric_ec.php
+++ b/kms/src/verify_asymmetric_ec.php
@@ -30,7 +30,7 @@ function verify_asymmetric_ec(
string $versionId = '123',
string $message = '...',
string $signature = '...'
-) {
+): bool {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
diff --git a/kms/src/verify_asymmetric_rsa.php b/kms/src/verify_asymmetric_rsa.php
index 1aa675964f..0ca5067a02 100644
--- a/kms/src/verify_asymmetric_rsa.php
+++ b/kms/src/verify_asymmetric_rsa.php
@@ -28,7 +28,7 @@ function verify_asymmetric_rsa(
string $versionId = '123',
string $message = '...',
string $signature = '...'
-) {
+): void {
// PHP has limited support for asymmetric encryption operations.
// Specifically, openssl_public_encrypt() does not allow customizing
// algorithms or padding. Thus, it is not currently possible to use PHP
diff --git a/logging/src/update_sink.php b/logging/src/update_sink.php
index 7bbe7f6c37..2726ed2303 100644
--- a/logging/src/update_sink.php
+++ b/logging/src/update_sink.php
@@ -24,7 +24,7 @@
* Update a log sink.
*
* @param string $projectId
- * @param string sinkName
+ * @param string $sinkName
* @param string $filterString
*/
function update_sink($projectId, $sinkName, $filterString)
diff --git a/logging/src/write_with_monolog_logger.php b/logging/src/write_with_monolog_logger.php
index caa5c84a99..92438a9e37 100644
--- a/logging/src/write_with_monolog_logger.php
+++ b/logging/src/write_with_monolog_logger.php
@@ -29,7 +29,8 @@
* @param string $projectId The Google project ID.
* @param string $loggerName The name of the logger.
* @param string $message The log message.
- * @param int $level
+ * @param string $level
+ * @phpstan-param LogLevel::* $level
*/
function write_with_monolog_logger(
string $projectId,
diff --git a/logging/src/write_with_psr_logger.php b/logging/src/write_with_psr_logger.php
index 29ebf7552c..037702e873 100644
--- a/logging/src/write_with_psr_logger.php
+++ b/logging/src/write_with_psr_logger.php
@@ -27,6 +27,8 @@
* @param string $projectId The Google project ID.
* @param string $loggerName The name of the logger.
* @param string $message The log message.
+ * @param string $level The log level.
+ * @phpstan-param LogLevel::* $level
*/
function write_with_psr_logger(
string $projectId,
diff --git a/media/transcoder/src/create_job_with_concatenated_inputs.php b/media/transcoder/src/create_job_with_concatenated_inputs.php
index 9365344730..1434d7008a 100644
--- a/media/transcoder/src/create_job_with_concatenated_inputs.php
+++ b/media/transcoder/src/create_job_with_concatenated_inputs.php
@@ -53,14 +53,14 @@
function create_job_with_concatenated_inputs($projectId, $location, $input1Uri, $startTimeInput1, $endTimeInput1, $input2Uri, $startTimeInput2, $endTimeInput2, $outputUri)
{
$startTimeInput1Sec = (int) floor(abs($startTimeInput1));
- $startTimeInput1Nanos = (int) (1000000000 * bcsub(abs($startTimeInput1), floor(abs($startTimeInput1)), 4));
+ $startTimeInput1Nanos = (int) (1000000000 * bcsub((string) abs($startTimeInput1), (string) floor(abs($startTimeInput1)), 4));
$endTimeInput1Sec = (int) floor(abs($endTimeInput1));
- $endTimeInput1Nanos = (int) (1000000000 * bcsub(abs($endTimeInput1), floor(abs($endTimeInput1)), 4));
+ $endTimeInput1Nanos = (int) (1000000000 * bcsub((string) abs($endTimeInput1), (string) floor(abs($endTimeInput1)), 4));
$startTimeInput2Sec = (int) floor(abs($startTimeInput2));
- $startTimeInput2Nanos = (int) (1000000000 * bcsub(abs($startTimeInput2), floor(abs($startTimeInput2)), 4));
+ $startTimeInput2Nanos = (int) (1000000000 * bcsub((string) abs($startTimeInput2), (string) floor(abs($startTimeInput2)), 4));
$endTimeInput2Sec = (int) floor(abs($endTimeInput2));
- $endTimeInput2Nanos = (int) (1000000000 * bcsub(abs($endTimeInput2), floor(abs($endTimeInput2)), 4));
+ $endTimeInput2Nanos = (int) (1000000000 * bcsub((string) abs($endTimeInput2), (string) floor(abs($endTimeInput2)), 4));
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/videostitcher/src/create_cdn_key.php b/media/videostitcher/src/create_cdn_key.php
index 4dba07114c..35a733d4c5 100644
--- a/media/videostitcher/src/create_cdn_key.php
+++ b/media/videostitcher/src/create_cdn_key.php
@@ -46,7 +46,7 @@
* https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
* for more information. For a Cloud CDN key,
* this is a base64-encoded string secret.
- * @param boolean $isMediaCdn If true, create a Media CDN key. If false,
+ * @param bool $isMediaCdn If true, create a Media CDN key. If false,
* create a Cloud CDN key.
*/
function create_cdn_key(
@@ -56,7 +56,7 @@ function create_cdn_key(
string $hostname,
string $keyName,
string $privateKey,
- string $isMediaCdn
+ bool $isMediaCdn
): void {
// Instantiate a client.
$stitcherClient = new VideoStitcherServiceClient();
diff --git a/media/videostitcher/src/update_cdn_key.php b/media/videostitcher/src/update_cdn_key.php
index ba86c2ecd9..a5fabc9ae8 100644
--- a/media/videostitcher/src/update_cdn_key.php
+++ b/media/videostitcher/src/update_cdn_key.php
@@ -47,7 +47,7 @@
* https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
* for more information. For a Cloud CDN key,
* this is a base64-encoded string secret.
- * @param boolean $isMediaCdn If true, update a Media CDN key. If false,
+ * @param bool $isMediaCdn If true, update a Media CDN key. If false,
* update a Cloud CDN key.
*/
function update_cdn_key(
@@ -57,7 +57,7 @@ function update_cdn_key(
string $hostname,
string $keyName,
string $privateKey,
- string $isMediaCdn
+ bool $isMediaCdn
): void {
// Instantiate a client.
$stitcherClient = new VideoStitcherServiceClient();
diff --git a/monitoring/src/alert_create_channel.php b/monitoring/src/alert_create_channel.php
index 62d449b0cc..c5b4af5856 100644
--- a/monitoring/src/alert_create_channel.php
+++ b/monitoring/src/alert_create_channel.php
@@ -30,7 +30,7 @@
/**
* @param string $projectId Your project ID
*/
-function alert_create_channel($projectId)
+function alert_create_channel(string $projectId): void
{
$channelClient = new NotificationChannelServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/alert_delete_channel.php b/monitoring/src/alert_delete_channel.php
index 962284262b..0f41860f06 100644
--- a/monitoring/src/alert_delete_channel.php
+++ b/monitoring/src/alert_delete_channel.php
@@ -28,8 +28,9 @@
/**
* @param string $projectId Your project ID
+ * @param string $channelId
*/
-function alert_delete_channel($projectId, $channelId)
+function alert_delete_channel(string $projectId, string $channelId): void
{
$channelClient = new NotificationChannelServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/alert_replace_channels.php b/monitoring/src/alert_replace_channels.php
index 666937cbdf..1c19a35d86 100644
--- a/monitoring/src/alert_replace_channels.php
+++ b/monitoring/src/alert_replace_channels.php
@@ -32,9 +32,9 @@
/**
* @param string $projectId Your project ID
* @param string $alertPolicyId Your alert policy id ID
- * @param array $channelIds array of channel IDs
+ * @param string[] $channelIds array of channel IDs
*/
-function alert_replace_channels($projectId, $alertPolicyId, array $channelIds)
+function alert_replace_channels(string $projectId, string $alertPolicyId, array $channelIds): void
{
$alertClient = new AlertPolicyServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/alert_restore_policies.php b/monitoring/src/alert_restore_policies.php
index 5c7857ab36..b7da148fb3 100644
--- a/monitoring/src/alert_restore_policies.php
+++ b/monitoring/src/alert_restore_policies.php
@@ -36,7 +36,7 @@
/**
* @param string $projectId Your project ID
*/
-function alert_restore_policies($projectId)
+function alert_restore_policies(string $projectId): void
{
$alertClient = new AlertPolicyServiceClient([
'projectId' => $projectId,
@@ -48,14 +48,14 @@ function alert_restore_policies($projectId)
print('Loading alert policies and notification channels from backup.json.' . PHP_EOL);
$projectName = $alertClient->projectName($projectId);
- $record = json_decode(file_get_contents('backup.json'), true);
+ $record = json_decode((string) file_get_contents('backup.json'), true);
$isSameProject = $projectName == $record['project_name'];
# Convert dicts to AlertPolicies.
$policies = [];
foreach ($record['policies'] as $policyArray) {
$policy = new AlertPolicy();
- $policy->mergeFromJsonString(json_encode($policyArray));
+ $policy->mergeFromJsonString((string) json_encode($policyArray));
$policies[] = $policy;
}
@@ -63,7 +63,7 @@ function alert_restore_policies($projectId)
$channels = [];
foreach (array_filter($record['channels']) as $channelArray) {
$channel = new NotificationChannel();
- $channel->mergeFromJsonString(json_encode($channelArray));
+ $channel->mergeFromJsonString((string) json_encode($channelArray));
$channels[] = $channel;
}
@@ -108,8 +108,8 @@ function alert_restore_policies($projectId)
foreach ($policies as $policy) {
printf('Updating policy %s' . PHP_EOL, $policy->getDisplayName());
# These two fields cannot be set directly, so clear them.
- $policy->setCreationRecord(null);
- $policy->setMutationRecord(null);
+ $policy->clearCreationRecord();
+ $policy->clearMutationRecord();
$notificationChannels = $policy->getNotificationChannels();
diff --git a/monitoring/src/list_uptime_check_ips.php b/monitoring/src/list_uptime_check_ips.php
index 4bc08e38cf..b8e90e807b 100644
--- a/monitoring/src/list_uptime_check_ips.php
+++ b/monitoring/src/list_uptime_check_ips.php
@@ -32,7 +32,7 @@
* list_uptime_check_ips($projectId);
* ```
*/
-function list_uptime_check_ips($projectId)
+function list_uptime_check_ips(string $projectId): void
{
$uptimeCheckClient = new UptimeCheckServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/list_uptime_checks.php b/monitoring/src/list_uptime_checks.php
index 4fe94bac99..d3128f03af 100644
--- a/monitoring/src/list_uptime_checks.php
+++ b/monitoring/src/list_uptime_checks.php
@@ -32,7 +32,7 @@
* list_uptime_checks($projectId);
* ```
*/
-function list_uptime_checks($projectId)
+function list_uptime_checks(string $projectId): void
{
$uptimeCheckClient = new UptimeCheckServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/read_timeseries_align.php b/monitoring/src/read_timeseries_align.php
index cbf16470e1..516309b749 100644
--- a/monitoring/src/read_timeseries_align.php
+++ b/monitoring/src/read_timeseries_align.php
@@ -40,7 +40,7 @@
*
* @param string $projectId Your project ID
*/
-function read_timeseries_align($projectId, $minutesAgo = 20)
+function read_timeseries_align(string $projectId, int $minutesAgo = 20): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/read_timeseries_fields.php b/monitoring/src/read_timeseries_fields.php
index 096c67e01c..92db07e61a 100644
--- a/monitoring/src/read_timeseries_fields.php
+++ b/monitoring/src/read_timeseries_fields.php
@@ -37,7 +37,7 @@
*
* @param string $projectId Your project ID
*/
-function read_timeseries_fields($projectId, $minutesAgo = 20)
+function read_timeseries_fields(string $projectId, int $minutesAgo = 20): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/read_timeseries_reduce.php b/monitoring/src/read_timeseries_reduce.php
index 1bad97657a..aa125dca09 100644
--- a/monitoring/src/read_timeseries_reduce.php
+++ b/monitoring/src/read_timeseries_reduce.php
@@ -39,7 +39,7 @@
*
* @param string $projectId Your project ID
*/
-function read_timeseries_reduce($projectId, $minutesAgo = 20)
+function read_timeseries_reduce(string $projectId, int $minutesAgo = 20): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/read_timeseries_simple.php b/monitoring/src/read_timeseries_simple.php
index 500e6e6e64..934012d974 100644
--- a/monitoring/src/read_timeseries_simple.php
+++ b/monitoring/src/read_timeseries_simple.php
@@ -37,7 +37,7 @@
*
* @param string $projectId Your project ID
*/
-function read_timeseries_simple($projectId, $minutesAgo = 20)
+function read_timeseries_simple(string $projectId, int $minutesAgo = 20): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/update_uptime_check.php b/monitoring/src/update_uptime_check.php
index 5538350ff2..6aa2feaeeb 100644
--- a/monitoring/src/update_uptime_check.php
+++ b/monitoring/src/update_uptime_check.php
@@ -33,8 +33,12 @@
* update_uptime_checks($projectId);
* ```
*/
-function update_uptime_checks($projectId, $configName, $newDisplayName = null, $newHttpCheckPath = null)
-{
+function update_uptime_checks(
+ string $projectId,
+ string $configName,
+ string $newDisplayName = null,
+ string $newHttpCheckPath = null
+): void {
$uptimeCheckClient = new UptimeCheckServiceClient([
'projectId' => $projectId,
]);
@@ -46,11 +50,13 @@ function update_uptime_checks($projectId, $configName, $newDisplayName = null, $
$uptimeCheck->setDisplayName($newDisplayName);
}
if ($newHttpCheckPath) {
- $fieldMask->getPaths()[] = 'http_check.path';
+ $paths = $fieldMask->getPaths()[] = 'http_check.path';
$uptimeCheck->getHttpCheck()->setPath($newHttpCheckPath);
}
- $uptimeCheckClient->updateUptimeCheckConfig($uptimeCheck, $fieldMask);
+ $uptimeCheckClient->updateUptimeCheckConfig($uptimeCheck, [
+ 'updateMask' => $fieldMask
+ ]);
print($uptimeCheck->serializeToString() . PHP_EOL);
}
diff --git a/pubsub/api/src/create_avro_schema.php b/pubsub/api/src/create_avro_schema.php
index 54ed913505..2fd09268f6 100644
--- a/pubsub/api/src/create_avro_schema.php
+++ b/pubsub/api/src/create_avro_schema.php
@@ -24,7 +24,6 @@
# [START pubsub_create_avro_schema]
use Google\Cloud\PubSub\PubSubClient;
-use Google\Cloud\PubSub\V1\Schema\Type;
/**
* Create a Schema with an AVRO definition.
@@ -33,14 +32,14 @@
* @param string $schemaId
* @param string $avscFile
*/
-function create_avro_schema($projectId, $schemaId, $avscFile)
+function create_avro_schema(string $projectId, string $schemaId, string $avscFile): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
- $definition = file_get_contents($avscFile);
- $schema = $pubsub->createSchema($schemaId, Type::AVRO, $definition);
+ $definition = (string) file_get_contents($avscFile);
+ $schema = $pubsub->createSchema($schemaId, 'AVRO', $definition);
printf('Schema %s created.', $schema->name());
}
diff --git a/pubsub/api/src/create_bigquery_subscription.php b/pubsub/api/src/create_bigquery_subscription.php
index 6c3e54b8c8..3e168e351b 100644
--- a/pubsub/api/src/create_bigquery_subscription.php
+++ b/pubsub/api/src/create_bigquery_subscription.php
@@ -33,7 +33,7 @@
* @param string $projectId The Google project ID.
* @param string $topicName The Pub/Sub topic name.
* @param string $subscriptionName The Pub/Sub subscription name.
- * @param string $tableName The BigQuery table to which to write.
+ * @param string $table The BigQuery table to which to write.
*/
function create_bigquery_subscription($projectId, $topicName, $subscriptionName, $table)
{
diff --git a/pubsub/api/src/create_proto_schema.php b/pubsub/api/src/create_proto_schema.php
index b6e5b3b93e..22b4f5b5ab 100644
--- a/pubsub/api/src/create_proto_schema.php
+++ b/pubsub/api/src/create_proto_schema.php
@@ -24,7 +24,6 @@
# [START pubsub_create_proto_schema]
use Google\Cloud\PubSub\PubSubClient;
-use Google\Cloud\PubSub\V1\Schema\Type;
/**
* Create a Schema with an Protocol Buffer definition.
@@ -39,8 +38,8 @@ function create_proto_schema($projectId, $schemaId, $protoFile)
'projectId' => $projectId,
]);
- $definition = file_get_contents($protoFile);
- $schema = $pubsub->createSchema($schemaId, Type::PROTOCOL_BUFFER, $definition);
+ $definition = (string) file_get_contents($protoFile);
+ $schema = $pubsub->createSchema($schemaId, 'PROTOCOL_BUFFER', $definition);
printf('Schema %s created.', $schema->name());
}
diff --git a/pubsub/api/src/create_subscription_with_filter.php b/pubsub/api/src/create_subscription_with_filter.php
index fcd6436ce5..8753530bca 100644
--- a/pubsub/api/src/create_subscription_with_filter.php
+++ b/pubsub/api/src/create_subscription_with_filter.php
@@ -34,8 +34,12 @@
* @param string $subscriptionName The Pub/Sub subscription name.
* @param string $filter The Pub/Sub subscription filter.
*/
-function create_subscription_with_filter($projectId, $topicName, $subscriptionName, $filter)
-{
+function create_subscription_with_filter(
+ string $projectId,
+ string $topicName,
+ string $subscriptionName,
+ string $filter
+): void {
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
diff --git a/pubsub/api/src/dead_letter_update_subscription.php b/pubsub/api/src/dead_letter_update_subscription.php
index 655b4c07d8..da96ec4aba 100644
--- a/pubsub/api/src/dead_letter_update_subscription.php
+++ b/pubsub/api/src/dead_letter_update_subscription.php
@@ -33,8 +33,12 @@
* @param string $topicName The Pub/Sub topic name.
* @param string $deadLetterTopicName The Pub/Sub topic to use for dead letter policy.
*/
-function dead_letter_update_subscription($projectId, $topicName, $subscriptionName, $deadLetterTopicName)
-{
+function dead_letter_update_subscription(
+ string $projectId,
+ string $topicName,
+ string $subscriptionName,
+ string $deadLetterTopicName
+): void {
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
diff --git a/pubsub/api/src/publish_avro_records.php b/pubsub/api/src/publish_avro_records.php
index bd68219c9e..e8f1f3a559 100644
--- a/pubsub/api/src/publish_avro_records.php
+++ b/pubsub/api/src/publish_avro_records.php
@@ -39,7 +39,6 @@
* @param string $projectId
* @param string $topicId
* @param string $definitionFile
- * @return void
*/
function publish_avro_records($projectId, $topicId, $definitionFile)
{
@@ -47,7 +46,7 @@ function publish_avro_records($projectId, $topicId, $definitionFile)
'projectId' => $projectId,
]);
- $definition = file_get_contents($definitionFile);
+ $definition = (string) file_get_contents($definitionFile);
$messageData = [
'name' => 'Alaska',
diff --git a/pubsub/api/src/pubsub_client.php b/pubsub/api/src/pubsub_client.php
index 8f35a5eeb8..f0444e0519 100644
--- a/pubsub/api/src/pubsub_client.php
+++ b/pubsub/api/src/pubsub_client.php
@@ -23,6 +23,8 @@
namespace Google\Cloud\Samples\PubSub;
+$projectId = '';
+
/**
* This file is to be used as an example only!
*
diff --git a/spanner/src/delete_data_with_dml.php b/spanner/src/delete_data_with_dml.php
index 7ba0cef5c9..e2435a4329 100644
--- a/spanner/src/delete_data_with_dml.php
+++ b/spanner/src/delete_data_with_dml.php
@@ -39,7 +39,7 @@ function delete_data_with_dml(string $instanceId, string $databaseId): void
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $database->runTransaction(function (Transaction $t) {
$rowCount = $t->executeUpdate(
"DELETE FROM Singers WHERE FirstName = 'Alice'");
$t->commit();
diff --git a/spanner/src/get_commit_stats.php b/spanner/src/get_commit_stats.php
index 9c0eceefac..5c36ceb71b 100644
--- a/spanner/src/get_commit_stats.php
+++ b/spanner/src/get_commit_stats.php
@@ -43,7 +43,7 @@ function get_commit_stats(string $instanceId, string $databaseId): void
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $commitStats = $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $commitStats = $database->runTransaction(function (Transaction $t) {
$t->updateBatch('Albums', [
[
'SingerId' => 1,
diff --git a/spanner/src/insert_data_with_dml.php b/spanner/src/insert_data_with_dml.php
index 95e5faf5d2..a272042671 100644
--- a/spanner/src/insert_data_with_dml.php
+++ b/spanner/src/insert_data_with_dml.php
@@ -46,7 +46,7 @@ function insert_data_with_dml(string $instanceId, string $databaseId): void
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $database->runTransaction(function (Transaction $t) {
$rowCount = $t->executeUpdate(
'INSERT Singers (SingerId, FirstName, LastName) '
. " VALUES (10, 'Virginia', 'Watson')");
diff --git a/spanner/src/list_instance_config_operations.php b/spanner/src/list_instance_config_operations.php
index 732566f3ee..731516c63d 100644
--- a/spanner/src/list_instance_config_operations.php
+++ b/spanner/src/list_instance_config_operations.php
@@ -33,7 +33,7 @@
* list_instance_config_operations();
* ```
*/
-function list_instance_config_operations()
+function list_instance_config_operations(): void
{
$spanner = new SpannerClient();
diff --git a/spanner/src/list_instance_configs.php b/spanner/src/list_instance_configs.php
index f12c1c81e7..e902daeec5 100644
--- a/spanner/src/list_instance_configs.php
+++ b/spanner/src/list_instance_configs.php
@@ -37,8 +37,10 @@ function list_instance_configs(): void
{
$spanner = new SpannerClient();
foreach ($spanner->instanceConfigurations() as $config) {
- printf('Available leader options for instance config %s: %s' . PHP_EOL,
- $config->info()['displayName'], $config->info()['leaderOptions']
+ printf(
+ 'Available leader options for instance config %s: %s' . PHP_EOL,
+ $config->info()['displayName'],
+ $config->info()['leaderOptions']
);
}
}
diff --git a/spanner/src/pg_numeric_data_type.php b/spanner/src/pg_numeric_data_type.php
index 76124eaa94..483dcb162b 100644
--- a/spanner/src/pg_numeric_data_type.php
+++ b/spanner/src/pg_numeric_data_type.php
@@ -71,7 +71,7 @@ function pg_numeric_data_type(string $instanceId, string $databaseId, string $ta
printf('Inserted %d venue(s).' . PHP_EOL, $count);
});
- $database->runTransaction(function (Transaction $t) use ($spanner, $sql) {
+ $database->runTransaction(function (Transaction $t) use ($sql) {
$count = $t->executeUpdate($sql, [
'parameters' => [
'p1' => 2,
diff --git a/spanner/src/set_transaction_tag.php b/spanner/src/set_transaction_tag.php
index 5499aa0c28..c0c891a9ee 100644
--- a/spanner/src/set_transaction_tag.php
+++ b/spanner/src/set_transaction_tag.php
@@ -43,7 +43,7 @@ function set_transaction_tag(string $instanceId, string $databaseId): void
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $database->runTransaction(function (Transaction $t) {
$t->executeUpdate(
'UPDATE Venues SET Capacity = CAST(Capacity/4 AS INT64) WHERE OutdoorVenue = false',
[
diff --git a/spanner/src/update_data_with_dml.php b/spanner/src/update_data_with_dml.php
index fd5d77358c..7658f74172 100644
--- a/spanner/src/update_data_with_dml.php
+++ b/spanner/src/update_data_with_dml.php
@@ -50,7 +50,7 @@ function update_data_with_dml(string $instanceId, string $databaseId): void
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $database->runTransaction(function (Transaction $t) {
$rowCount = $t->executeUpdate(
'UPDATE Albums '
. 'SET MarketingBudget = MarketingBudget * 2 '
diff --git a/spanner/src/update_data_with_dml_structs.php b/spanner/src/update_data_with_dml_structs.php
index 3431d4de67..139933c2ea 100644
--- a/spanner/src/update_data_with_dml_structs.php
+++ b/spanner/src/update_data_with_dml_structs.php
@@ -49,7 +49,7 @@ function update_data_with_dml_structs(string $instanceId, string $databaseId): v
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $database->runTransaction(function (Transaction $t) {
$nameValue = (new StructValue)
->add('FirstName', 'Timothy')
->add('LastName', 'Campbell');
diff --git a/spanner/src/update_data_with_dml_timestamp.php b/spanner/src/update_data_with_dml_timestamp.php
index 9297cace6f..12a5532b5a 100644
--- a/spanner/src/update_data_with_dml_timestamp.php
+++ b/spanner/src/update_data_with_dml_timestamp.php
@@ -46,7 +46,7 @@ function update_data_with_dml_timestamp(string $instanceId, string $databaseId):
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $database->runTransaction(function (Transaction $t) {
$rowCount = $t->executeUpdate(
'UPDATE Albums '
. 'SET LastUpdateTime = PENDING_COMMIT_TIMESTAMP() WHERE SingerId = 1');
diff --git a/spanner/src/write_data_with_dml.php b/spanner/src/write_data_with_dml.php
index cfe5f24b59..88ede3ed04 100644
--- a/spanner/src/write_data_with_dml.php
+++ b/spanner/src/write_data_with_dml.php
@@ -46,7 +46,7 @@ function write_data_with_dml(string $instanceId, string $databaseId): void
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $database->runTransaction(function (Transaction $t) {
$rowCount = $t->executeUpdate(
'INSERT Singers (SingerId, FirstName, LastName) VALUES '
. "(12, 'Melissa', 'Garcia'), "
diff --git a/spanner/src/write_data_with_dml_transaction.php b/spanner/src/write_data_with_dml_transaction.php
index 500f6b4ddb..7519fc4b69 100644
--- a/spanner/src/write_data_with_dml_transaction.php
+++ b/spanner/src/write_data_with_dml_transaction.php
@@ -51,7 +51,7 @@ function write_data_with_dml_transaction(string $instanceId, string $databaseId)
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $database->runTransaction(function (Transaction $t) {
// Transfer marketing budget from one album to another. We do it in a transaction to
// ensure that the transfer is atomic.
$transferAmount = 200000;
diff --git a/spanner/src/write_read_with_dml.php b/spanner/src/write_read_with_dml.php
index e2b62f693e..28ad05e34e 100644
--- a/spanner/src/write_read_with_dml.php
+++ b/spanner/src/write_read_with_dml.php
@@ -46,7 +46,7 @@ function write_read_with_dml(string $instanceId, string $databaseId): void
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
- $database->runTransaction(function (Transaction $t) use ($spanner) {
+ $database->runTransaction(function (Transaction $t) {
$rowCount = $t->executeUpdate(
'INSERT Singers (SingerId, FirstName, LastName) '
. " VALUES (11, 'Timothy', 'Campbell')");
diff --git a/storage/src/upload_object.php b/storage/src/upload_object.php
index ce1b4d46fb..fb7dd331d0 100644
--- a/storage/src/upload_object.php
+++ b/storage/src/upload_object.php
@@ -39,7 +39,9 @@
function upload_object(string $bucketName, string $objectName, string $source): void
{
$storage = new StorageClient();
- $file = fopen($source, 'r');
+ if (!$file = fopen($source, 'r')) {
+ throw new \InvalidArgumentException('Unable to open file for reading');
+ }
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload($file, [
'name' => $objectName
diff --git a/storage/src/upload_object_from_memory.php b/storage/src/upload_object_from_memory.php
index ecd885dda5..9f11d8b692 100644
--- a/storage/src/upload_object_from_memory.php
+++ b/storage/src/upload_object_from_memory.php
@@ -42,7 +42,9 @@ function upload_object_from_memory(
string $contents
): void {
$storage = new StorageClient();
- $stream = fopen('data://text/plain,' . $contents, 'r');
+ if (!$stream = fopen('data://text/plain,' . $contents, 'r')) {
+ throw new \InvalidArgumentException('Unable to open file for reading');
+ }
$bucket = $storage->bucket($bucketName);
$bucket->upload($stream, [
'name' => $objectName,
diff --git a/storage/src/upload_with_kms_key.php b/storage/src/upload_with_kms_key.php
index 11b43746b9..20f69c7a3c 100644
--- a/storage/src/upload_with_kms_key.php
+++ b/storage/src/upload_with_kms_key.php
@@ -42,7 +42,9 @@
function upload_with_kms_key(string $bucketName, string $objectName, string $source, string $kmsKeyName): void
{
$storage = new StorageClient();
- $file = fopen($source, 'r');
+ if (!$file = fopen($source, 'r')) {
+ throw new \InvalidArgumentException('Unable to open file for reading');
+ }
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload($file, [
'name' => $objectName,
diff --git a/tasks/src/create_http_task.php b/tasks/src/create_http_task.php
index f5cd7d9454..9433f1f2c6 100644
--- a/tasks/src/create_http_task.php
+++ b/tasks/src/create_http_task.php
@@ -27,7 +27,8 @@
if ($argc < 5 || $argc > 6) {
return printf("Usage: php %s PROJECT_ID LOCATION_ID QUEUE_ID URL [PAYLOAD]\n", __FILE__);
}
-list($_, $projectId, $locationId, $queueId, $url, $payload) = $argv;
+list($_, $projectId, $locationId, $queueId, $url) = $argv;
+$payload = $argv[5] ?? '';
# [START cloud_tasks_create_http_task]
use Google\Cloud\Tasks\V2\CloudTasksClient;
@@ -53,7 +54,7 @@
// POST is the default HTTP method, but any HTTP method can be used.
$httpRequest->setHttpMethod(HttpMethod::POST);
// Setting a body value is only compatible with HTTP POST and PUT requests.
-if (isset($payload)) {
+if (!empty($payload)) {
$httpRequest->setBody($payload);
}
diff --git a/testing/composer.json b/testing/composer.json
index 88e64eb382..a39308fd69 100755
--- a/testing/composer.json
+++ b/testing/composer.json
@@ -10,6 +10,7 @@
"phpunit/phpunit": "^9.0",
"friendsofphp/php-cs-fixer": "^3,<3.9",
"composer/semver": "^3.2",
+ "phpstan/phpstan": "^1.10",
"phpspec/prophecy-phpunit": "^2.0"
}
}
diff --git a/testing/phpstan/compute/cloud-client/instances.neon.dist b/testing/phpstan/compute/cloud-client/instances.neon.dist
new file mode 100644
index 0000000000..2a8480e8e8
--- /dev/null
+++ b/testing/phpstan/compute/cloud-client/instances.neon.dist
@@ -0,0 +1,5 @@
+parameters:
+ level: 5
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#Google\\Cloud\\Compute\\V1\\Gapic\\ProjectsGapicClient::setUsageExportBucket\(\) expects Google\\Cloud\\Compute\\V1\\UsageExportLocation#'
diff --git a/testing/phpstan/default.neon.dist b/testing/phpstan/default.neon.dist
new file mode 100644
index 0000000000..bf3085e4ad
--- /dev/null
+++ b/testing/phpstan/default.neon.dist
@@ -0,0 +1,3 @@
+parameters:
+ level: 5
+ treatPhpDocTypesAsCertain: false
diff --git a/testing/phpstan/pubsub/api.neon.dist b/testing/phpstan/pubsub/api.neon.dist
new file mode 100644
index 0000000000..2b73a2b7e2
--- /dev/null
+++ b/testing/phpstan/pubsub/api.neon.dist
@@ -0,0 +1,8 @@
+parameters:
+ level: 5
+ treatPhpDocTypesAsCertain: false
+ excludePaths:
+ - ../../../pubsub/api/src/data
+ ignoreErrors:
+ - '#Utilities\\StateProto#'
+
diff --git a/testing/run_staticanalysis_check.sh b/testing/run_staticanalysis_check.sh
new file mode 100644
index 0000000000..3db1638a1e
--- /dev/null
+++ b/testing/run_staticanalysis_check.sh
@@ -0,0 +1,106 @@
+#!/bin/bash
+# Copyright 2023 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+if [ "${BASH_DEBUG}" = "true" ]; then
+ set -x
+fi
+
+if [ "${TEST_DIRECTORIES}" = "" ]; then
+ TEST_DIRECTORIES="*"
+fi
+
+SKIP_DIRS=(
+ dialogflow
+ iot
+)
+
+TMP_REPORT_DIR=$(mktemp -d)
+SUCCEEDED_FILE=${TMP_REPORT_DIR}/succeeded
+FAILED_FILE=${TMP_REPORT_DIR}/failed
+SKIPPED_FILE=${TMP_REPORT_DIR}/skipped
+
+# Determine all files changed on this branch
+# (will be empty if running from "main").
+FILES_CHANGED=$(git diff --name-only HEAD origin/main)
+
+# If the label `kokoro:run-all` is added, or if we were not triggered from a Pull
+# Request, run the whole test suite.
+if [ -z "$PULL_REQUEST_NUMBER" ]; then
+ RUN_ALL_TESTS=1
+else
+ labels=$(curl "https://api.github.com/repos/GoogleCloudPlatform/php-docs-samples/issues/$PULL_REQUEST_NUMBER/labels")
+
+ # Check to see if the repo includes the "kokoro:run-all" label
+ if grep -q "kokoro:run-all" <<< $labels; then
+ RUN_ALL_TESTS=1
+ else
+ RUN_ALL_TESTS=0
+ fi
+fi
+
+for dir in $(find $TEST_DIRECTORIES -type d -name src -not -path '/*' -not -path 'appengine/*' -not -path '*/vendor/*' -exec dirname {} \;);
+do
+ # Only run tests for samples that have changed.
+ if [ "$RUN_ALL_TESTS" -ne "1" ]; then
+ if ! grep -q ^$dir <<< "$FILES_CHANGED" ; then
+ echo "Skipping tests in $dir (unchanged)"
+ echo "$dir: skipped" >> "${SKIPPED_FILE}"
+ continue
+ fi
+ fi
+ if [[ " ${SKIP_DIRS[@]} " =~ " ${dir} " ]]; then
+ printf "Skipping $dir (explicitly flagged to be skipped)\n\n"
+ echo "$dir: skipped" >> "${SKIPPED_FILE}"
+ continue
+ fi
+ composer update --working-dir=$dir --ignore-platform-reqs -q
+ echo " autoload.php
+ neon="testing/phpstan/default.neon.dist"
+ if [ -f "testing/phpstan/$dir.neon.dist" ]; then
+ neon="testing/phpstan/$dir.neon.dist"
+ fi
+ echo "Running phpstan in \"$dir\" with config \"$neon\""
+ testing/vendor/bin/phpstan analyse $dir/src \
+ --autoload-file=autoload.php \
+ --configuration=$neon
+ if [ $? == 0 ]; then
+ echo "$dir: ok" >> "${SUCCEEDED_FILE}"
+ else
+ echo "$dir: failed" >> "${FAILED_FILE}"
+ fi
+done
+
+set +x
+
+if [ -f "${SUCCEEDED_FILE}" ]; then
+ echo "--------- Succeeded -----------"
+ cat "${SUCCEEDED_FILE}"
+ echo "-------------------------------"
+fi
+
+if [ -f "${SKIPPED_FILE}" ]; then
+ echo "--------- SKIPPED --------------"
+ cat "${SKIPPED_FILE}"
+ echo "--------------------------------"
+ # Report any skips
+fi
+
+if [ -f "${FAILED_FILE}" ]; then
+ echo "--------- Failed --------------"
+ cat "${FAILED_FILE}"
+ echo "-------------------------------"
+ # Report any failure
+ exit 1
+fi
diff --git a/testing/sample_helpers.php b/testing/sample_helpers.php
index 960e35d9bf..da7a4e0bcb 100644
--- a/testing/sample_helpers.php
+++ b/testing/sample_helpers.php
@@ -8,13 +8,13 @@ function execute_sample(string $file, string $namespace, ?array $argv)
{
// Return if sample file is not being executed via CLI
if (is_null($argv)) {
- return;
+ return null;
}
// Return if sample file is being included via PHPUnit
$argvFile = array_shift($argv);
if ('.php' != substr($argvFile, -4)) {
- return;
+ return null;
}
// Determine the name of the function to execute
@@ -27,7 +27,7 @@ function execute_sample(string $file, string $namespace, ?array $argv)
|| count($argv) > $functionReflection->getNumberOfParameters()
) {
print(get_usage(basename($file), $functionReflection));
- return;
+ return null;
}
// Require composer autoload for the user
@@ -37,7 +37,7 @@ function execute_sample(string $file, string $namespace, ?array $argv)
'You must run "composer install" in the sample root (%s/)' . PHP_EOL,
$autoloadDir
);
- return;
+ return null;
}
require_once $autoloadFile;
@@ -59,7 +59,7 @@ function execute_sample(string $file, string $namespace, ?array $argv)
return call_user_func_array($functionName, $argv);
}
-function get_usage(string $file, ReflectionFunction $functionReflection)
+function get_usage(string $file, ReflectionFunction $functionReflection): string
{
// Print basic usage
$paramNames = [];
diff --git a/vision/src/detect_face.php b/vision/src/detect_face.php
index cec248b4e4..a423f484d5 100644
--- a/vision/src/detect_face.php
+++ b/vision/src/detect_face.php
@@ -68,7 +68,7 @@ function detect_face(string $path, string $outFile = null)
# [START vision_face_detection_tutorial_process_response]
# draw box around faces
- if ($faces && $outFile) {
+ if ($faces->count() && $outFile) {
$imageCreateFunc = [
'png' => 'imagecreatefrompng',
'gd' => 'imagecreatefromgd',
diff --git a/vision/src/detect_label.php b/vision/src/detect_label.php
index 678145e2b1..f88c2f8ae1 100644
--- a/vision/src/detect_label.php
+++ b/vision/src/detect_label.php
@@ -32,7 +32,7 @@ function detect_label(string $path)
$response = $imageAnnotator->labelDetection($image);
$labels = $response->getLabelAnnotations();
- if ($labels) {
+ if ($labels->count()) {
print('Labels:' . PHP_EOL);
foreach ($labels as $label) {
print($label->getDescription() . PHP_EOL);
diff --git a/vision/src/detect_label_gcs.php b/vision/src/detect_label_gcs.php
index ca8d5744bb..ad56abe81b 100644
--- a/vision/src/detect_label_gcs.php
+++ b/vision/src/detect_label_gcs.php
@@ -31,7 +31,7 @@ function detect_label_gcs(string $path)
$response = $imageAnnotator->labelDetection($path);
$labels = $response->getLabelAnnotations();
- if ($labels) {
+ if ($labels->count()) {
print('Labels:' . PHP_EOL);
foreach ($labels as $label) {
print($label->getDescription() . PHP_EOL);
diff --git a/vision/src/detect_pdf_gcs.php b/vision/src/detect_pdf_gcs.php
index 2082ac356b..a0d73f1118 100644
--- a/vision/src/detect_pdf_gcs.php
+++ b/vision/src/detect_pdf_gcs.php
@@ -31,7 +31,7 @@
/**
* @param string $path GCS path to the document, e.g. "gs://path/to/your/document.pdf"
- * @param string $outFile GCS path to store the results, e.g. "gs://path/to/store/results/"
+ * @param string $output GCS path to store the results, e.g. "gs://path/to/store/results/"
*/
function detect_pdf_gcs(string $path, string $output)
{
diff --git a/vision/src/detect_web_with_geo_metadata.php b/vision/src/detect_web_with_geo_metadata.php
index 55d4751db5..019887942b 100644
--- a/vision/src/detect_web_with_geo_metadata.php
+++ b/vision/src/detect_web_with_geo_metadata.php
@@ -43,7 +43,7 @@ function detect_web_with_geo_metadata(string $path)
$response = $imageAnnotator->webDetection($image, ['imageContext' => $imageContext]);
$web = $response->getWebDetection();
- if ($web && $web->getWebEntities()) {
+ if ($web && $web->getWebEntities()->count()) {
printf('%d web entities found:' . PHP_EOL,
count($web->getWebEntities()));
foreach ($web->getWebEntities() as $entity) {
From cb97568657292bb1c146970faca31a72318d8af4 Mon Sep 17 00:00:00 2001
From: Brent Shaffer
Date: Wed, 4 Oct 2023 10:45:08 -0700
Subject: [PATCH 078/285] chore: fix lint github action (#1925)
* use files changed github action
* fix yaml syntax
* use files instead of dirs
* testing modifying a file
* debug info
* format files changed correctly
* Revert "testing modifying a file"
This reverts commit 22da5ea160c129b7f1dad79c6c2d255d88256641.
* get rid of skipped dir (redundant)
---
.github/workflows/lint.yml | 10 +++++-----
testing/run_staticanalysis_check.sh | 25 ++++++++-----------------
2 files changed, 13 insertions(+), 22 deletions(-)
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index c4ddad101f..901becf7ff 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -22,13 +22,13 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- with:
- ref: ${{ github.event.pull_request.head.ref }}
- fetch-depth: 5
- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.0'
+ - name: Get changed files
+ id: changedFiles
+ uses: tj-actions/changed-files@v39
- uses: jwalton/gh-find-current-pr@v1
id: findPr
with:
@@ -39,5 +39,5 @@ jobs:
git fetch --no-tags --prune --depth=5 origin main
bash testing/run_staticanalysis_check.sh
env:
- PULL_REQUEST_NUMBER: ${{ steps.findPr.outputs.pr }}
-
+ FILES_CHANGED: ${{ steps.changedFiles.outputs.all_changed_files }}
+ PULL_REQUEST_NUMBER: ${{ steps.findPr.outputs.pr }}
\ No newline at end of file
diff --git a/testing/run_staticanalysis_check.sh b/testing/run_staticanalysis_check.sh
index 3db1638a1e..0dd02ceaff 100644
--- a/testing/run_staticanalysis_check.sh
+++ b/testing/run_staticanalysis_check.sh
@@ -17,10 +17,6 @@ if [ "${BASH_DEBUG}" = "true" ]; then
set -x
fi
-if [ "${TEST_DIRECTORIES}" = "" ]; then
- TEST_DIRECTORIES="*"
-fi
-
SKIP_DIRS=(
dialogflow
iot
@@ -29,11 +25,15 @@ SKIP_DIRS=(
TMP_REPORT_DIR=$(mktemp -d)
SUCCEEDED_FILE=${TMP_REPORT_DIR}/succeeded
FAILED_FILE=${TMP_REPORT_DIR}/failed
-SKIPPED_FILE=${TMP_REPORT_DIR}/skipped
-# Determine all files changed on this branch
-# (will be empty if running from "main").
-FILES_CHANGED=$(git diff --name-only HEAD origin/main)
+if [ "${TEST_DIRECTORIES}" = "" ]; then
+ TEST_DIRECTORIES="*"
+fi
+
+if [ "${FILES_CHANGED}" = "" ]; then
+ FILES_CHANGED=""
+fi
+FILES_CHANGED=$(echo $FILES_CHANGED | tr " " "\n")
# If the label `kokoro:run-all` is added, or if we were not triggered from a Pull
# Request, run the whole test suite.
@@ -56,13 +56,11 @@ do
if [ "$RUN_ALL_TESTS" -ne "1" ]; then
if ! grep -q ^$dir <<< "$FILES_CHANGED" ; then
echo "Skipping tests in $dir (unchanged)"
- echo "$dir: skipped" >> "${SKIPPED_FILE}"
continue
fi
fi
if [[ " ${SKIP_DIRS[@]} " =~ " ${dir} " ]]; then
printf "Skipping $dir (explicitly flagged to be skipped)\n\n"
- echo "$dir: skipped" >> "${SKIPPED_FILE}"
continue
fi
composer update --working-dir=$dir --ignore-platform-reqs -q
@@ -90,13 +88,6 @@ if [ -f "${SUCCEEDED_FILE}" ]; then
echo "-------------------------------"
fi
-if [ -f "${SKIPPED_FILE}" ]; then
- echo "--------- SKIPPED --------------"
- cat "${SKIPPED_FILE}"
- echo "--------------------------------"
- # Report any skips
-fi
-
if [ -f "${FAILED_FILE}" ]; then
echo "--------- Failed --------------"
cat "${FAILED_FILE}"
From d98b3ef8a94100f69f97715137a72113af741e94 Mon Sep 17 00:00:00 2001
From: sameer-crest <129392897+sameer-crest@users.noreply.github.com>
Date: Wed, 4 Oct 2023 23:39:41 +0530
Subject: [PATCH 079/285] fix(dlp): corrected the region tags (#1924)
---
dlp/src/inspect_text_file.php | 4 ++--
dlp/src/k_anonymity.php | 4 ++--
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/dlp/src/inspect_text_file.php b/dlp/src/inspect_text_file.php
index 5acf13de7c..197401b748 100644
--- a/dlp/src/inspect_text_file.php
+++ b/dlp/src/inspect_text_file.php
@@ -23,7 +23,7 @@
namespace Google\Cloud\Samples\Dlp;
-// [START dlp_inspect_text_file]
+// [START dlp_inspect_file]
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\ContentItem;
use Google\Cloud\Dlp\V2\InfoType;
@@ -81,7 +81,7 @@ function inspect_text_file(string $projectId, string $filepath): void
}
}
}
-// [END dlp_inspect_text_file]
+// [END dlp_inspect_file]
// The following 2 lines are only needed to run the samples
require_once __DIR__ . '/../../testing/sample_helpers.php';
diff --git a/dlp/src/k_anonymity.php b/dlp/src/k_anonymity.php
index 449ad3a7e7..3ab5dce271 100644
--- a/dlp/src/k_anonymity.php
+++ b/dlp/src/k_anonymity.php
@@ -23,7 +23,7 @@
namespace Google\Cloud\Samples\Dlp;
-# [START dlp_k_anomymity]
+# [START dlp_k_anonymity]
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\RiskAnalysisJobConfig;
use Google\Cloud\Dlp\V2\BigQueryTable;
@@ -169,7 +169,7 @@ function ($id) {
print('Unexpected job state. Most likely, the job is either running or has not yet started.');
}
}
-# [END dlp_k_anomymity]
+# [END dlp_k_anonymity]
// The following 2 lines are only needed to run the samples
require_once __DIR__ . '/../../testing/sample_helpers.php';
From 7829067093b0c6c78beb0380080c0db0db47db7c Mon Sep 17 00:00:00 2001
From: Ajumal
Date: Sun, 15 Oct 2023 16:04:02 +0530
Subject: [PATCH 080/285] feat(PubSub): Add CPS to GCS sample (#1874)
---
.kokoro/secrets.sh.enc | Bin 9119 -> 9188 bytes
pubsub/api/composer.json | 2 +-
.../src/create_cloud_storage_subscription.php | 53 ++++++++++++++++++
pubsub/api/test/pubsubTest.php | 25 +++++++++
4 files changed, 79 insertions(+), 1 deletion(-)
create mode 100644 pubsub/api/src/create_cloud_storage_subscription.php
diff --git a/.kokoro/secrets.sh.enc b/.kokoro/secrets.sh.enc
index eaf26147ae4914ad7acfdc3c9370e43d9592336a..8bb4b60e692bb5dd8b3ca2125304d46924885c8e 100644
GIT binary patch
literal 9188
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
^IoC=I(;x<`xku3J1&D8xSpn59=UO^
zqh4DFGyRZ9Kl3Ik*&&s1ARcdqZoS`?vtLV=O~DB;+~U_Rv7a?w&zzrc*ak3
zxMu_%)D+1l2f4o#obs-isWIYvtZWggi@ch`yyM`i`a~HH*H{#HjV~j`Td|JO)Bp?K
zn)@U?nFHQ3?`K^SRqR+28a8YH6I$y&fe0Sv{~q0K&z{X&o0||I)^&ZYTTC3JFbu|!_sLon1)5!Q
z_PR`Pg*8612pzZvV67kHwAvL`$L^0d&9&AYt_tKTZ*{ijq_@JI_hluBN;!5D+zqE?!xkaO8hP(Cw+<3X1C08!t?E~$rQ
z8oUpdMC6;h&Z+TRD;%Qw!XqJJ!-()c;aSn2uWnyxp_QXUNGOd6X}{^_MNjp;cCrl>
zvf6WDO=4u}NXOYkI(h@9X`bmV!^|fMF)!VcT66~29#xydo04t0_{V}hg;@x;rvf5?
zOL=jO<6KV_`c_zA^W4Uq-_qLb>T=F}Ms1;=E0y3HfcS%CO8U~e@v)y45fB~bQDZT{
z%lXtajGl->+lGPk(|cl#XKFpBNa!3$iX-cF(RQ#J;wsO)v{pm;0(D`zAFzIJ8E_8e
zSHXh}rTRX!vr2u3vI+zqUM@&jAPgF!XeUIR=|XL|&)&^Ky@*n*U2
z$2BPGZW53SZ68M07^sJum=BL4V8?lmL=QYFm#5E46&4@g2*MT$JIi$vG&jhk0oucuDdDxq5iwVc`W2TCvun1P9P>A=!jM9
z{{;d718cq|v_)>DISw}|H)7n3bY=l;Bfh1tItGJ)s4u7EMF>
z4PyXR`ETOC><<6V2kS|Oe7Yox1`*blmSuWp3heO(>oJI!dF&B%&zCQ@niW>ZBoD
z_EQ71$MtKkH0V3ag_#LcJM)A^oHpI^1LU7eU|9F-{k=gt`D8vwMF}>IL*((*M&p~|
zbi!TB;^Tw#d}CLr5&QVUTc9wYEynf<@j-+OZYl;a+P2>2$SJ%@lSLX~YH#?YKEF{1
zQ2u6MiviSRK&pcLS5}awLOTTs2W-9fKO+D2jEvcKX*)@7&Tn!seIKu25~GzhU-c0R
zD<5+vZ_7{oo+B7AHL$eKky{Bn%iu1Pa)Z!oX7%lP1o62i->~7`7Ix>r-aSv_c+amw
zxJ5F{elyDmtixQGx6I?hz`q{MmoKG2Rv&$UocTUNT@_0n>sLSF<&g4kb0#t^g319QtmP?Xv-gAiZ^02Fc~Ubz=e$y9L8FLVeHQMU9U}8#@Z=@uI$Yuw(-)7-pvc{F_t;s^62n
zw88>lE+&&uS!-mPc??93Zi74JmBg#-vDzTsMmP=>
literal 9119
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