diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 7e9b516115..2d4e12f10e 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -17,10 +17,5 @@ jobs:
- 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
- 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/
+ bash testing/run_staticanalysis_check.sh
diff --git a/appengine/flexible/datastore/app.php b/appengine/flexible/datastore/app.php
index 4eb850a2f9..ad9e4e0acd 100644
--- a/appengine/flexible/datastore/app.php
+++ b/appengine/flexible/datastore/app.php
@@ -80,7 +80,7 @@
->withHeader('Content-Type', 'text/plain');
});
-function get_user_ip(Request $request)
+function get_user_ip(Request $request): void
{
$ip = $request->getAttribute('ip_address');
// Keep only the first two octets of the IP address.
diff --git a/appengine/flexible/metadata/app.php b/appengine/flexible/metadata/app.php
index bc355f73c1..8938db407d 100644
--- a/appengine/flexible/metadata/app.php
+++ b/appengine/flexible/metadata/app.php
@@ -19,7 +19,7 @@
use Slim\Factory\AppFactory;
# [START gae_flex_metadata]
-function get_external_ip_using_google_cloud()
+function get_external_ip_using_google_cloud(): void
{
$metadata = new Google\Cloud\Core\Compute\Metadata();
$externalIp = $metadata->get(
@@ -28,7 +28,7 @@ function get_external_ip_using_google_cloud()
return $externalIp;
}
-function get_external_ip_using_curl()
+function get_external_ip_using_curl(): void
{
$url = 'http://metadata.google.internal/computeMetadata/v1/' .
'instance/network-interfaces/0/access-configs/0/external-ip';
diff --git a/appengine/flexible/tasks/src/create_task.php b/appengine/flexible/tasks/src/create_task.php
index f06bc6d33f..840eb872b0 100644
--- a/appengine/flexible/tasks/src/create_task.php
+++ b/appengine/flexible/tasks/src/create_task.php
@@ -42,7 +42,7 @@
* @param integer $inSeconds The number of seconds from now to schedule task attempt.
*
*/
-function create_task($projectId, $queueId, $location, $payload = 'helloworld', $inSeconds = null)
+function create_task($projectId, $queueId, $location, $payload = 'helloworld', $inSeconds = null): void
{
// Instantiate the client, authenticate, and add scopes.
$client = new Google_Client();
diff --git a/appengine/standard/auth/src/auth_api.php b/appengine/standard/auth/src/auth_api.php
index 09578f2c74..8be907a014 100644
--- a/appengine/standard/auth/src/auth_api.php
+++ b/appengine/standard/auth/src/auth_api.php
@@ -27,7 +27,7 @@
use Google_Client;
use Google_Service_Storage;
-function auth_api($projectId)
+function auth_api($projectId): void
{
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
diff --git a/appengine/standard/auth/src/auth_cloud.php b/appengine/standard/auth/src/auth_cloud.php
index 1ca0f8eb03..5446ca901f 100644
--- a/appengine/standard/auth/src/auth_cloud.php
+++ b/appengine/standard/auth/src/auth_cloud.php
@@ -26,7 +26,7 @@
// Imports the Cloud Storage client library.
use Google\Cloud\Storage\StorageClient;
-function auth_cloud($projectId)
+function auth_cloud($projectId): void
{
# If you don't specify credentials when constructing the client, the
# client library will look for credentials in the environment.
diff --git a/appengine/standard/metadata/index.php b/appengine/standard/metadata/index.php
index 77734f8a79..6ef92d1656 100644
--- a/appengine/standard/metadata/index.php
+++ b/appengine/standard/metadata/index.php
@@ -34,7 +34,7 @@
*
* @param $metadataKey the key for the metadata server
*/
-function request_metadata_using_google_cloud($metadataKey)
+function request_metadata_using_google_cloud($metadataKey): void
{
$metadata = new Google\Cloud\Core\Compute\Metadata();
$metadataValue = $metadata->get($metadataKey);
@@ -47,7 +47,7 @@ function request_metadata_using_google_cloud($metadataKey)
*
* @param $metadataKey the key for the metadata server
*/
-function request_metadata_using_curl(http://github.com/$metadataKey)
+function request_metadata_using_curl(http://github.com/$metadataKey): void
{
$url = 'http://metadata/computeMetadata/v1/' . $metadataKey;
@@ -60,7 +60,7 @@ function request_metadata_using_curl(http://github.com/$metadataKey)
}
# [END gae_metadata]
-function print_metadata_paths($root = '')
+function print_metadata_paths($root = ''): void
{
$keys = request_metadata_using_google_cloud($root);
$html = '
';
diff --git a/appengine/standard/tasks/apps/handler/index.php b/appengine/standard/tasks/apps/handler/index.php
index 318c26011a..02d8d28301 100644
--- a/appengine/standard/tasks/apps/handler/index.php
+++ b/appengine/standard/tasks/apps/handler/index.php
@@ -59,7 +59,7 @@
* @param string $taskName provides the identifier of the task.
* @param string $body The task details from the HTTP request.
*/
-function handle_task($queueName, $taskName, $body = '')
+function handle_task($queueName, $taskName, $body = ''): void
{
global $logger;
diff --git a/appengine/standard/trace/index.php b/appengine/standard/trace/index.php
index 8033f2498b..da6505a528 100644
--- a/appengine/standard/trace/index.php
+++ b/appengine/standard/trace/index.php
@@ -28,7 +28,7 @@
Tracer::start($exporter);
-function trace_callable()
+function trace_callable(): void
{
# [START span_with_closure]
Tracer::inSpan(
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/export_assets.php b/asset/src/export_assets.php
index 86c91d6408..f2ee346923 100644
--- a/asset/src/export_assets.php
+++ b/asset/src/export_assets.php
@@ -29,7 +29,7 @@
* @param string $dumpFilePath the file path where the assets will be dumped to.
* e.g.: gs://[bucket-name]/[asset-file-name].
*/
-function export_assets(string $projectId, string $dumpFilePath)
+function export_assets(string $projectId, string $dumpFilePath): void
{
$client = new AssetServiceClient();
diff --git a/asset/src/list_assets.php b/asset/src/list_assets.php
index ab6d863482..e853a1214e 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_iam_policies.php b/asset/src/search_all_iam_policies.php
index 8bc0ff7395..31208b4e1a 100644
--- a/asset/src/search_all_iam_policies.php
+++ b/asset/src/search_all_iam_policies.php
@@ -31,7 +31,7 @@ function search_all_iam_policies(
string $query = '',
int $pageSize = 0,
string $pageToken = ''
-) {
+): void {
// Instantiate a client.
$asset = 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/auth/src/auth_api_explicit.php b/auth/src/auth_api_explicit.php
index 0475079120..90e33a3122 100644
--- a/auth/src/auth_api_explicit.php
+++ b/auth/src/auth_api_explicit.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $serviceAccountPath Path to service account credentials JSON.
*/
-function auth_api_explicit($projectId, $serviceAccountPath)
+function auth_api_explicit($projectId, $serviceAccountPath): void
{
$client = new Google_Client();
$client->setAuthConfig($serviceAccountPath);
diff --git a/auth/src/auth_api_explicit_compute.php b/auth/src/auth_api_explicit_compute.php
index 299770b014..093d5cb61b 100644
--- a/auth/src/auth_api_explicit_compute.php
+++ b/auth/src/auth_api_explicit_compute.php
@@ -36,7 +36,7 @@
*
* @param string $projectId The Google project ID.
*/
-function auth_api_explicit_compute($projectId)
+function auth_api_explicit_compute($projectId): void
{
$gceCredentials = new GCECredentials();
$middleware = new AuthTokenMiddleware($gceCredentials);
diff --git a/auth/src/auth_api_implicit.php b/auth/src/auth_api_implicit.php
index 901e82a838..9cf86f9a8a 100644
--- a/auth/src/auth_api_implicit.php
+++ b/auth/src/auth_api_implicit.php
@@ -31,7 +31,7 @@
*
* @param string $projectId The Google project ID.
*/
-function auth_api_implicit($projectId)
+function auth_api_implicit($projectId): void
{
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
diff --git a/auth/src/auth_cloud_explicit.php b/auth/src/auth_cloud_explicit.php
index 58289501cf..de9592da2e 100644
--- a/auth/src/auth_cloud_explicit.php
+++ b/auth/src/auth_cloud_explicit.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $serviceAccountPath Path to service account credentials JSON.
*/
-function auth_cloud_explicit($projectId, $serviceAccountPath)
+function auth_cloud_explicit($projectId, $serviceAccountPath): void
{
# Explicitly use service account credentials by specifying the private key
# file.
diff --git a/auth/src/auth_cloud_explicit_compute.php b/auth/src/auth_cloud_explicit_compute.php
index 4b5454f19c..11ae12691d 100644
--- a/auth/src/auth_cloud_explicit_compute.php
+++ b/auth/src/auth_cloud_explicit_compute.php
@@ -32,7 +32,7 @@
*
* @param string $projectId The Google project ID.
*/
-function auth_cloud_explicit_compute($projectId)
+function auth_cloud_explicit_compute($projectId): void
{
$gceCredentials = new GCECredentials();
$config = [
diff --git a/auth/src/auth_cloud_implicit.php b/auth/src/auth_cloud_implicit.php
index af9331e249..df860c4cc4 100644
--- a/auth/src/auth_cloud_implicit.php
+++ b/auth/src/auth_cloud_implicit.php
@@ -31,7 +31,7 @@
*
* @param string $projectId The Google project ID.
*/
-function auth_cloud_implicit($projectId)
+function auth_cloud_implicit($projectId): void
{
$config = [
'projectId' => $projectId,
diff --git a/auth/src/auth_http_explicit.php b/auth/src/auth_http_explicit.php
index 962891c7f9..54b3d52e5e 100644
--- a/auth/src/auth_http_explicit.php
+++ b/auth/src/auth_http_explicit.php
@@ -35,7 +35,7 @@
* @param string $projectId The Google project ID.
* @param string $serviceAccountPath Path to service account credentials JSON.
*/
-function auth_http_explicit($projectId, $serviceAccountPath)
+function auth_http_explicit($projectId, $serviceAccountPath): void
{
# Construct service account credentials using the service account key file
# and Google Auth library's ServiceAccountCredentials class.
diff --git a/auth/src/auth_http_implicit.php b/auth/src/auth_http_implicit.php
index 8b16f4aa54..38b70dd570 100644
--- a/auth/src/auth_http_implicit.php
+++ b/auth/src/auth_http_implicit.php
@@ -33,7 +33,7 @@
*
* @param string $projectId The Google project ID.
*/
-function auth_http_implicit($projectId)
+function auth_http_implicit($projectId): void
{
# Get the credentials and project ID from the environment using Google Auth
# library's ApplicationDefaultCredentials class.
diff --git a/bigquery/api/src/bigquery_client.php b/bigquery/api/src/bigquery_client.php
index 9d63dec148..3ebf94b184 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 e648ad0f4f..b5a0e94ab8 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/import_from_local_csv.php b/bigquery/api/src/import_from_local_csv.php
index d12e117652..e6fdb6d81a 100644
--- a/bigquery/api/src/import_from_local_csv.php
+++ b/bigquery/api/src/import_from_local_csv.php
@@ -47,7 +47,10 @@
$dataset = $bigQuery->dataset($datasetId);
$table = $dataset->table($tableId);
// create the import job
-$loadConfig = $table->load(fopen($source, 'r'))->sourceFormat('CSV');
+if (!$file = fopen($source, 'r')) {
+ throw new InvalidArgumentException('Unable to open source file');
+}
+$loadConfig = $table->load($file)->sourceFormat('CSV');
$job = $table->runJob($loadConfig);
// poll the job until it is complete
diff --git a/bigquery/api/src/insert_sql.php b/bigquery/api/src/insert_sql.php
index b9501a8e42..10ccde18dd 100644
--- a/bigquery/api/src/insert_sql.php
+++ b/bigquery/api/src/insert_sql.php
@@ -43,7 +43,9 @@
]);
$dataset = $bigQuery->dataset($datasetId);
// run a sync query for each line of the import
-$file = fopen($source, 'r');
+if (!$file = fopen($source, 'r')) {
+ throw new InvalidArgumentException('Unable to open source file');
+}
while ($line = fgets($file)) {
if (0 !== strpos(trim($line), 'INSERT')) {
continue;
diff --git a/bigtable/src/filter_composing_chain.php b/bigtable/src/filter_composing_chain.php
index 17587dc587..2487cfea95 100644
--- a/bigtable/src/filter_composing_chain.php
+++ b/bigtable/src/filter_composing_chain.php
@@ -61,7 +61,10 @@ function filter_composing_chain(
// [END bigtable_filters_composing_chain]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 e61aa78101..b124e8a92b 100644
--- a/bigtable/src/filter_composing_condition.php
+++ b/bigtable/src/filter_composing_condition.php
@@ -65,7 +65,10 @@ function filter_composing_condition(
// [END bigtable_filters_composing_condition]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 48047371ba..7e681721f1 100644
--- a/bigtable/src/filter_composing_interleave.php
+++ b/bigtable/src/filter_composing_interleave.php
@@ -61,7 +61,10 @@ function filter_composing_interleave(
// [END bigtable_filters_composing_interleave]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 5a7812a774..fc81c40c31 100644
--- a/bigtable/src/filter_limit_block_all.php
+++ b/bigtable/src/filter_limit_block_all.php
@@ -59,7 +59,10 @@ function filter_limit_block_all(
// [END bigtable_filters_limit_block_all]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 4816477e10..e7a7c9795b 100644
--- a/bigtable/src/filter_limit_cells_per_col.php
+++ b/bigtable/src/filter_limit_cells_per_col.php
@@ -59,7 +59,10 @@ 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)
+/**
+ * @param array $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 e3d5269f1c..ca772fd93b 100644
--- a/bigtable/src/filter_limit_cells_per_row.php
+++ b/bigtable/src/filter_limit_cells_per_row.php
@@ -59,7 +59,10 @@ 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)
+/**
+ * @param array $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 873bee4e5c..6a20d7c3d4 100644
--- a/bigtable/src/filter_limit_cells_per_row_offset.php
+++ b/bigtable/src/filter_limit_cells_per_row_offset.php
@@ -59,7 +59,10 @@ 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)
+/**
+ * @param array $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 087196276e..0c3e9ef34b 100644
--- a/bigtable/src/filter_limit_col_family_regex.php
+++ b/bigtable/src/filter_limit_col_family_regex.php
@@ -59,7 +59,10 @@ 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)
+/**
+ * @param array $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 b75faa4f08..2b4f1699d9 100644
--- a/bigtable/src/filter_limit_col_qualifier_regex.php
+++ b/bigtable/src/filter_limit_col_qualifier_regex.php
@@ -59,7 +59,10 @@ 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)
+/**
+ * @param array $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 89156ade53..c497e4f3da 100644
--- a/bigtable/src/filter_limit_col_range.php
+++ b/bigtable/src/filter_limit_col_range.php
@@ -62,7 +62,10 @@ function filter_limit_col_range(
// [END bigtable_filters_limit_col_range]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 f54b923f09..ced9262b6b 100644
--- a/bigtable/src/filter_limit_pass_all.php
+++ b/bigtable/src/filter_limit_pass_all.php
@@ -59,7 +59,10 @@ function filter_limit_pass_all(
// [END bigtable_filters_limit_pass_all]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 edc7f0c0fd..ed0cf26a1f 100644
--- a/bigtable/src/filter_limit_row_regex.php
+++ b/bigtable/src/filter_limit_row_regex.php
@@ -59,7 +59,10 @@ function filter_limit_row_regex(
// [END bigtable_filters_limit_row_regex]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 53ab0b8e73..c2542fdf62 100644
--- a/bigtable/src/filter_limit_row_sample.php
+++ b/bigtable/src/filter_limit_row_sample.php
@@ -59,7 +59,10 @@ function filter_limit_row_sample(
// [END bigtable_filters_limit_row_sample]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 bf287e46a2..05b48fb095 100644
--- a/bigtable/src/filter_limit_timestamp_range.php
+++ b/bigtable/src/filter_limit_timestamp_range.php
@@ -66,7 +66,10 @@ function filter_limit_timestamp_range(
// [END bigtable_filters_limit_timestamp_range]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 73b5134090..151ad14cc2 100644
--- a/bigtable/src/filter_limit_value_range.php
+++ b/bigtable/src/filter_limit_value_range.php
@@ -62,7 +62,10 @@ function filter_limit_value_range(
// [END bigtable_filters_limit_value_range]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 4459926d7b..8539429ea9 100644
--- a/bigtable/src/filter_limit_value_regex.php
+++ b/bigtable/src/filter_limit_value_regex.php
@@ -59,7 +59,10 @@ function filter_limit_value_regex(
// [END bigtable_filters_limit_value_regex]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 3996db6088..3f5cdad20d 100644
--- a/bigtable/src/filter_modify_apply_label.php
+++ b/bigtable/src/filter_modify_apply_label.php
@@ -59,7 +59,10 @@ function filter_modify_apply_label(
// [END bigtable_filters_modify_apply_label]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 9f6c0057e7..9e0599b5aa 100644
--- a/bigtable/src/filter_modify_strip_value.php
+++ b/bigtable/src/filter_modify_strip_value.php
@@ -59,7 +59,10 @@ function filter_modify_strip_value(
// [END bigtable_filters_modify_strip_value]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 ba1bcdcdc8..6b52b9a167 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 550259625f..69b7f9614f 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 e4d648a113..083831c282 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 03b8204913..04f091a580 100644
--- a/bigtable/src/read_filter.php
+++ b/bigtable/src/read_filter.php
@@ -58,7 +58,10 @@ function read_filter(
// [END bigtable_reads_filter]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 e279139a17..ad7f88863f 100644
--- a/bigtable/src/read_prefix.php
+++ b/bigtable/src/read_prefix.php
@@ -67,7 +67,10 @@ function read_prefix(
// [END bigtable_reads_prefix]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 6ffb8f6f85..e451dccd67 100644
--- a/bigtable/src/read_row.php
+++ b/bigtable/src/read_row.php
@@ -53,7 +53,10 @@ function read_row(
// [START bigtable_reads_print]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 3a7d9e1604..c1ec16c761 100644
--- a/bigtable/src/read_row_partial.php
+++ b/bigtable/src/read_row_partial.php
@@ -54,7 +54,10 @@ function read_row_partial(
// [END bigtable_reads_row_partial]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 b1837fabc0..3c484d8b24 100644
--- a/bigtable/src/read_row_range.php
+++ b/bigtable/src/read_row_range.php
@@ -60,7 +60,10 @@ function read_row_range(
// [END bigtable_reads_row_range]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 c838874cb2..8225d75598 100644
--- a/bigtable/src/read_row_ranges.php
+++ b/bigtable/src/read_row_ranges.php
@@ -64,7 +64,10 @@ function read_row_ranges(
// [END bigtable_reads_row_ranges]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 6b7e5984ce..b2780d4f6f 100644
--- a/bigtable/src/read_rows.php
+++ b/bigtable/src/read_rows.php
@@ -55,7 +55,10 @@ function read_rows(
// [END bigtable_reads_rows]
// Helper function for printing the row data
-function print_row($key, $row)
+/**
+ * @param array $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 a1aa854158..84df343e92 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 1eb23a94cd..445d0986ae 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/cdn/signUrl.php b/cdn/signUrl.php
index 323cb7ddb6..092d91cbc6 100644
--- a/cdn/signUrl.php
+++ b/cdn/signUrl.php
@@ -23,7 +23,7 @@
*
* @return string
*/
-function base64url_decode($input)
+function base64url_decode($input): void
{
$input .= str_repeat('=', (4 - strlen($input) % 4) % 4);
return base64_decode(strtr($input, '-_', '+/'), true);
@@ -38,7 +38,7 @@ function base64url_decode($input)
*
* @return string
*/
-function base64url_encode($input, $padding = true)
+function base64url_encode($input, $padding = true): void
{
$output = strtr(base64_encode($input), '+/', '-_');
return ($padding) ? $output : str_replace('=', '', $output);
@@ -63,7 +63,7 @@ function base64url_encode($input, $padding = true)
*
* @return string
*/
-function sign_url(http://github.com/$url,%20$keyName,%20$base64UrlKey,%20$expirationTime)
+function sign_url(http://github.com/$url,%20$keyName,%20$base64UrlKey,%20$expirationTime): void
{
// Decode the key
$decodedKey = base64url_decode($base64UrlKey);
diff --git a/cloud_sql/mysql/pdo/src/DBInitializer.php b/cloud_sql/mysql/pdo/src/DBInitializer.php
index 926ec72d86..60c652e61f 100644
--- a/cloud_sql/mysql/pdo/src/DBInitializer.php
+++ b/cloud_sql/mysql/pdo/src/DBInitializer.php
@@ -28,11 +28,11 @@ class DBInitializer
{
/**
- * @param $username string username of the database user
- * @param $password string password of the database user
- * @param $dbName string name of the target database
- * @param $dbHost string IP address or domain of the target database
- * @param $connConfig array driver-specific options for PDO
+ * @param string $username username of the database user
+ * @param string $password password of the database user
+ * @param string $dbName name of the target database
+ * @param string $dbHost IP address or domain of the target database
+ * @param array $connConfig driver-specific options for PDO
*/
public static function initTcpDatabaseConnection(
string $username,
@@ -85,12 +85,12 @@ public static function initTcpDatabaseConnection(
}
/**
- * @param $username string username of the database user
- * @param $password string password of the database user
- * @param $dbName string name of the target database
- * @param $connectionName string Cloud SQL instance name
- * @param $socketDir string Full path to unix socket
- * @param $conn_config array driver-specific options for PDO
+ * @param string $username username of the database user
+ * @param string $password password of the database user
+ * @param string $dbName name of the target database
+ * @param string $connectionName Cloud SQL instance name
+ * @param string $socketDir Full path to unix socket
+ * @param array $connConfig driver-specific options for PDO
*/
public static function initUnixDatabaseConnection(
string $username,
@@ -98,7 +98,7 @@ public static function initUnixDatabaseConnection(
string $dbName,
string $connectionName,
string $socketDir,
- array $conn_config
+ array $connConfig
): PDO {
try {
# [START cloud_sql_mysql_pdo_create_socket]
@@ -117,7 +117,7 @@ public static function initUnixDatabaseConnection(
);
// Connect to the database.
- $conn = new PDO($dsn, $username, $password, $conn_config);
+ $conn = new PDO($dsn, $username, $password, $connConfig);
# [END cloud_sql_mysql_pdo_create_socket]
} catch (TypeError $e) {
throw new RuntimeException(
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/mysql/pdo/src/app.php b/cloud_sql/mysql/pdo/src/app.php
index f0b1b67645..8e0e081f20 100644
--- a/cloud_sql/mysql/pdo/src/app.php
+++ b/cloud_sql/mysql/pdo/src/app.php
@@ -68,7 +68,7 @@
$connConfig
);
} else {
- $connectionName = getenv('CLOUDSQL_CONNECTION_NAME');
+ $connectionName = getenv('CLOUDSQL_CONNECTION_NAME') ?: '';
$socketDir = getenv('DB_SOCKET_DIR') ?: '/cloudsql';
return DBInitializer::initUnixDatabaseConnection(
$username,
diff --git a/cloud_sql/postgres/pdo/src/DBInitializer.php b/cloud_sql/postgres/pdo/src/DBInitializer.php
index ff468e4494..c80cb57bf6 100644
--- a/cloud_sql/postgres/pdo/src/DBInitializer.php
+++ b/cloud_sql/postgres/pdo/src/DBInitializer.php
@@ -28,11 +28,11 @@ class DBInitializer
{
/**
- * @param $username string username of the database user
- * @param $password string password of the database user
- * @param $dbName string name of the target database
- * @param $dbHost string IP address or domain of the target database
- * @param $connConfig array driver-specific options for PDO
+ * @param string $username username of the database user
+ * @param string $password password of the database user
+ * @param string $dbName name of the target database
+ * @param string $dbHost IP address or domain of the target database
+ * @param array $connConfig driver-specific options for PDO
*/
public static function initTcpDatabaseConnection(
string $username,
@@ -85,12 +85,12 @@ public static function initTcpDatabaseConnection(
}
/**
- * @param $username string username of the database user
- * @param $password string password of the database user
- * @param $dbName string name of the target database
- * @param $connectionName string Cloud SQL instance name
- * @param $socketDir string Full path to unix socket
- * @param $connConfig array driver-specific options for PDO
+ * @param string $username username of the database user
+ * @param string $password password of the database user
+ * @param string $dbName name of the target database
+ * @param string $connectionName Cloud SQL instance name
+ * @param string $socketDir Full path to unix socket
+ * @param array $connConfig driver-specific options for PDO
*/
public static function initUnixDatabaseConnection(
string $username,
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/postgres/pdo/src/app.php b/cloud_sql/postgres/pdo/src/app.php
index 7f3c308d02..30448dba21 100644
--- a/cloud_sql/postgres/pdo/src/app.php
+++ b/cloud_sql/postgres/pdo/src/app.php
@@ -68,7 +68,7 @@
$connConfig
);
} else {
- $connectionName = getenv('CLOUDSQL_CONNECTION_NAME');
+ $connectionName = getenv('CLOUDSQL_CONNECTION_NAME') ?: '';
$socketDir = getenv('DB_SOCKET_DIR') ?: '/tmp/cloudsql';
return DBInitializer::initUnixDatabaseConnection(
$username,
diff --git a/cloud_sql/sqlserver/pdo/src/DBInitializer.php b/cloud_sql/sqlserver/pdo/src/DBInitializer.php
index 668db496aa..f7406abdf5 100644
--- a/cloud_sql/sqlserver/pdo/src/DBInitializer.php
+++ b/cloud_sql/sqlserver/pdo/src/DBInitializer.php
@@ -27,11 +27,11 @@
class DBInitializer
{
/**
- * @param $username string username of the database user
- * @param $password string password of the database user
- * @param $dbName string name of the target database
- * @param $dbHost string IP address or domain of the target database
- * @param $connConfig array driver-specific options for PDO
+ * @param string $username username of the database user
+ * @param string $password password of the database user
+ * @param string $dbName name of the target database
+ * @param string $dbHost IP address or domain of the target database
+ * @param array $connConfig driver-specific options for PDO
*/
public static function initTcpDatabaseConnection(
string $username,
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/api-client/helloworld/app.php b/compute/api-client/helloworld/app.php
index aa7666e1a1..03bffaf07a 100755
--- a/compute/api-client/helloworld/app.php
+++ b/compute/api-client/helloworld/app.php
@@ -67,7 +67,7 @@
* @param string $apiResponse The API response to process.
* @return string Markup for the specific Google Compute Engine API request.
*/
-function generateMarkup($apiRequestName, $apiResponse)
+function generateMarkup($apiRequestName, $apiResponse): void
{
$apiRequestMarkup = '';
$apiRequestMarkup .= '';
diff --git a/compute/cloud-client/firewall/src/create_firewall_rule.php b/compute/cloud-client/firewall/src/create_firewall_rule.php
index e01d2f2012..8c28dd2a53 100644
--- a/compute/cloud-client/firewall/src/create_firewall_rule.php
+++ b/compute/cloud-client/firewall/src/create_firewall_rule.php
@@ -48,7 +48,7 @@
* @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
*/
-function create_firewall_rule(string $projectId, string $firewallRuleName, string $network = 'global/networks/default')
+function create_firewall_rule(string $projectId, string $firewallRuleName, string $network = 'global/networks/default'): void
{
$firewallsClient = new FirewallsClient();
$allowedPorts = (new Allowed())
diff --git a/compute/cloud-client/firewall/src/delete_firewall_rule.php b/compute/cloud-client/firewall/src/delete_firewall_rule.php
index 1e37961bd2..6a6436ad66 100644
--- a/compute/cloud-client/firewall/src/delete_firewall_rule.php
+++ b/compute/cloud-client/firewall/src/delete_firewall_rule.php
@@ -35,7 +35,7 @@
* @throws \Google\ApiCore\ApiException if the remote call fails.
* @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
*/
-function delete_firewall_rule(string $projectId, string $firewallRuleName)
+function delete_firewall_rule(string $projectId, string $firewallRuleName): void
{
$firewallsClient = new FirewallsClient();
diff --git a/compute/cloud-client/firewall/src/list_firewall_rules.php b/compute/cloud-client/firewall/src/list_firewall_rules.php
index a69b01ddc0..e5f30fc181 100644
--- a/compute/cloud-client/firewall/src/list_firewall_rules.php
+++ b/compute/cloud-client/firewall/src/list_firewall_rules.php
@@ -34,7 +34,7 @@
*
* @throws \Google\ApiCore\ApiException if the remote call fails.
*/
-function list_firewall_rules(string $projectId)
+function list_firewall_rules(string $projectId): void
{
// List all firewall rules defined for the project using Firewalls Client.
$firewallClient = new FirewallsClient();
diff --git a/compute/cloud-client/firewall/src/patch_firewall_priority.php b/compute/cloud-client/firewall/src/patch_firewall_priority.php
index 9bced91320..59cb828c40 100644
--- a/compute/cloud-client/firewall/src/patch_firewall_priority.php
+++ b/compute/cloud-client/firewall/src/patch_firewall_priority.php
@@ -37,7 +37,7 @@
* @throws \Google\ApiCore\ApiException if the remote call fails.
* @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
*/
-function patch_firewall_priority(string $projectId, string $firewallRuleName, int $priority)
+function patch_firewall_priority(string $projectId, string $firewallRuleName, int $priority): void
{
$firewallsClient = new FirewallsClient();
$firewallResource = (new Firewall())->setPriority($priority);
diff --git a/compute/cloud-client/firewall/src/print_firewall_rule.php b/compute/cloud-client/firewall/src/print_firewall_rule.php
index 7057be93df..0a482208aa 100644
--- a/compute/cloud-client/firewall/src/print_firewall_rule.php
+++ b/compute/cloud-client/firewall/src/print_firewall_rule.php
@@ -33,7 +33,7 @@
*
* @throws \Google\ApiCore\ApiException if the remote call fails.
*/
-function print_firewall_rule(string $projectId, string $firewallRuleName)
+function print_firewall_rule(string $projectId, string $firewallRuleName): void
{
// Get details of a firewall rule defined for the project using Firewalls Client.
$firewallClient = new FirewallsClient();
diff --git a/compute/cloud-client/helloworld/app.php b/compute/cloud-client/helloworld/app.php
index 522368b5d8..acbbf32617 100755
--- a/compute/cloud-client/helloworld/app.php
+++ b/compute/cloud-client/helloworld/app.php
@@ -46,7 +46,7 @@
/**
* Helper function to pretty-print a Protobuf message.
*/
-function print_message(Message $message)
+function print_message(Message $message): void
{
return json_encode(
json_decode($message->serializeToJsonString(), true),
diff --git a/compute/cloud-client/instances/src/create_instance.php b/compute/cloud-client/instances/src/create_instance.php
index 7ba344f058..58601141e2 100644
--- a/compute/cloud-client/instances/src/create_instance.php
+++ b/compute/cloud-client/instances/src/create_instance.php
@@ -56,7 +56,7 @@ function create_instance(
string $machineType = 'n1-standard-1',
string $sourceImage = 'projects/debian-cloud/global/images/family/debian-10',
string $networkName = 'global/networks/default'
-) {
+): void {
// Set the machine type using the specified zone.
$machineTypeFullName = sprintf('zones/%s/machineTypes/%s', $zone, $machineType);
diff --git a/compute/cloud-client/instances/src/create_instance_with_encryption_key.php b/compute/cloud-client/instances/src/create_instance_with_encryption_key.php
index 415b4ffc55..33c6b94bb3 100644
--- a/compute/cloud-client/instances/src/create_instance_with_encryption_key.php
+++ b/compute/cloud-client/instances/src/create_instance_with_encryption_key.php
@@ -61,7 +61,7 @@ function create_instance_with_encryption_key(
string $machineType = 'n1-standard-1',
string $sourceImage = 'projects/debian-cloud/global/images/family/debian-10',
string $networkName = 'global/networks/default'
-) {
+): void {
// Set the machine type using the specified zone.
$machineTypeFullName = sprintf('zones/%s/machineTypes/%s', $zone, $machineType);
diff --git a/compute/cloud-client/instances/src/delete_instance.php b/compute/cloud-client/instances/src/delete_instance.php
index aa1d2f224b..2b87a2395a 100644
--- a/compute/cloud-client/instances/src/delete_instance.php
+++ b/compute/cloud-client/instances/src/delete_instance.php
@@ -40,7 +40,7 @@ function delete_instance(
string $projectId,
string $zone,
string $instanceName
-) {
+): void {
// Delete the Compute Engine instance using InstancesClient.
$instancesClient = new InstancesClient();
$operation = $instancesClient->delete($instanceName, $projectId, $zone);
diff --git a/compute/cloud-client/instances/src/disable_usage_export_bucket.php b/compute/cloud-client/instances/src/disable_usage_export_bucket.php
index 5366778938..6f2c858822 100644
--- a/compute/cloud-client/instances/src/disable_usage_export_bucket.php
+++ b/compute/cloud-client/instances/src/disable_usage_export_bucket.php
@@ -34,7 +34,7 @@
*
* @throws \Google\ApiCore\ApiException if the remote call fails.
*/
-function disable_usage_export_bucket(string $projectId)
+function disable_usage_export_bucket(string $projectId): void
{
// Disable the usage export location by sending null as usageExportLocationResource.
$projectsClient = new ProjectsClient();
diff --git a/compute/cloud-client/instances/src/get_usage_export_bucket.php b/compute/cloud-client/instances/src/get_usage_export_bucket.php
index 7057291790..d92a4fac97 100644
--- a/compute/cloud-client/instances/src/get_usage_export_bucket.php
+++ b/compute/cloud-client/instances/src/get_usage_export_bucket.php
@@ -35,7 +35,7 @@
*
* @throws \Google\ApiCore\ApiException if the remote call fails.
*/
-function get_usage_export_bucket(string $projectId)
+function get_usage_export_bucket(string $projectId): void
{
// Get the usage export location for the project from the server.
$projectsClient = new ProjectsClient();
diff --git a/compute/cloud-client/instances/src/list_all_images.php b/compute/cloud-client/instances/src/list_all_images.php
index 6df5e0536a..935ac3c7ef 100644
--- a/compute/cloud-client/instances/src/list_all_images.php
+++ b/compute/cloud-client/instances/src/list_all_images.php
@@ -33,7 +33,7 @@
*
* @throws \Google\ApiCore\ApiException if the remote call fails.
*/
-function list_all_images(string $projectId)
+function list_all_images(string $projectId): void
{
$imagesClient = new ImagesClient();
// Listing only non-deprecated images to reduce the size of the reply.
diff --git a/compute/cloud-client/instances/src/list_all_instances.php b/compute/cloud-client/instances/src/list_all_instances.php
index 253a9481f9..0686dfa959 100644
--- a/compute/cloud-client/instances/src/list_all_instances.php
+++ b/compute/cloud-client/instances/src/list_all_instances.php
@@ -33,7 +33,7 @@
*
* @throws \Google\ApiCore\ApiException if the remote call fails.
*/
-function list_all_instances(string $projectId)
+function list_all_instances(string $projectId): void
{
// List Compute Engine instances using InstancesClient.
$instancesClient = new InstancesClient();
diff --git a/compute/cloud-client/instances/src/list_images_by_page.php b/compute/cloud-client/instances/src/list_images_by_page.php
index b4ca554b98..6eb1faefc8 100644
--- a/compute/cloud-client/instances/src/list_images_by_page.php
+++ b/compute/cloud-client/instances/src/list_images_by_page.php
@@ -35,7 +35,7 @@
*
* @throws \Google\ApiCore\ApiException if the remote call fails.
*/
-function list_images_by_page(string $projectId, int $pageSize = 10)
+function list_images_by_page(string $projectId, int $pageSize = 10): void
{
$imagesClient = new ImagesClient();
$pageNum = 1;
diff --git a/compute/cloud-client/instances/src/list_instances.php b/compute/cloud-client/instances/src/list_instances.php
index 212b7f2074..d627fa86aa 100644
--- a/compute/cloud-client/instances/src/list_instances.php
+++ b/compute/cloud-client/instances/src/list_instances.php
@@ -34,7 +34,7 @@
*
* @throws \Google\ApiCore\ApiException if the remote call fails.
*/
-function list_instances(string $projectId, string $zone)
+function list_instances(string $projectId, string $zone): void
{
// List Compute Engine instances using InstancesClient.
$instancesClient = new InstancesClient();
diff --git a/compute/cloud-client/instances/src/reset_instance.php b/compute/cloud-client/instances/src/reset_instance.php
index 515e3b7320..9256371709 100644
--- a/compute/cloud-client/instances/src/reset_instance.php
+++ b/compute/cloud-client/instances/src/reset_instance.php
@@ -40,7 +40,7 @@ function reset_instance(
string $projectId,
string $zone,
string $instanceName
-) {
+): void {
// Stop the Compute Engine instance using InstancesClient.
$instancesClient = new InstancesClient();
$operation = $instancesClient->reset($instanceName, $projectId, $zone);
diff --git a/compute/cloud-client/instances/src/set_usage_export_bucket.php b/compute/cloud-client/instances/src/set_usage_export_bucket.php
index f5b9658e51..fd4a406ee3 100644
--- a/compute/cloud-client/instances/src/set_usage_export_bucket.php
+++ b/compute/cloud-client/instances/src/set_usage_export_bucket.php
@@ -45,7 +45,7 @@ function set_usage_export_bucket(
string $projectId,
string $bucketName,
string $reportNamePrefix = ''
-) {
+): void {
// Initialize UsageExportLocation object with provided bucket name and no report name prefix.
$usageExportLocation = new UsageExportLocation(array(
'bucket_name' => $bucketName,
diff --git a/compute/cloud-client/instances/src/start_instance.php b/compute/cloud-client/instances/src/start_instance.php
index 2807de131d..9b47dbb9d9 100644
--- a/compute/cloud-client/instances/src/start_instance.php
+++ b/compute/cloud-client/instances/src/start_instance.php
@@ -40,7 +40,7 @@ function start_instance(
string $projectId,
string $zone,
string $instanceName
-) {
+): void {
// Start the Compute Engine instance using InstancesClient.
$instancesClient = new InstancesClient();
$operation = $instancesClient->start($instanceName, $projectId, $zone);
diff --git a/compute/cloud-client/instances/src/start_instance_with_encryption_key.php b/compute/cloud-client/instances/src/start_instance_with_encryption_key.php
index 312a1b1ef1..6af4092288 100644
--- a/compute/cloud-client/instances/src/start_instance_with_encryption_key.php
+++ b/compute/cloud-client/instances/src/start_instance_with_encryption_key.php
@@ -47,7 +47,7 @@ function start_instance_with_encryption_key(
string $zone,
string $instanceName,
string $key
-) {
+): void {
// Initiate the InstancesClient.
$instancesClient = new InstancesClient();
@@ -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/compute/cloud-client/instances/src/stop_instance.php b/compute/cloud-client/instances/src/stop_instance.php
index 21c6a0d82f..a0a3b8c87f 100644
--- a/compute/cloud-client/instances/src/stop_instance.php
+++ b/compute/cloud-client/instances/src/stop_instance.php
@@ -40,7 +40,7 @@ function stop_instance(
string $projectId,
string $zone,
string $instanceName
-) {
+): void {
// Stop the Compute Engine instance using InstancesClient.
$instancesClient = new InstancesClient();
$operation = $instancesClient->stop($instanceName, $projectId, $zone);
diff --git a/compute/logging/index.php b/compute/logging/index.php
index f389f2c92e..6c058f1a98 100644
--- a/compute/logging/index.php
+++ b/compute/logging/index.php
@@ -22,7 +22,7 @@
$GLOBALS['logger'] = new FluentLogger('localhost', '24224');
-function fluentd_exception_handler(Exception $e)
+function fluentd_exception_handler(Exception $e): void
{
global $logger;
diff --git a/datastore/api/src/functions/concepts.php b/datastore/api/src/functions/concepts.php
index 25fedbf6f2..39e97cc707 100644
--- a/datastore/api/src/functions/concepts.php
+++ b/datastore/api/src/functions/concepts.php
@@ -21,6 +21,7 @@
use Google\Cloud\Datastore\DatastoreClient;
use Google\Cloud\Datastore\Entity;
use Google\Cloud\Datastore\EntityIterator;
+use Google\Cloud\Datastore\EntityInterface;
use Google\Cloud\Datastore\Key;
use Google\Cloud\Datastore\Query\Query;
@@ -29,7 +30,7 @@
*
* @return DatastoreClient
*/
-function initialize_client()
+function initialize_client(): DatastoreClient
{
$datastore = new DatastoreClient();
return $datastore;
@@ -41,9 +42,10 @@ function initialize_client()
* @param DatastoreClient $datastore
* @return Entity
*/
-function basic_entity(DatastoreClient $datastore)
+function basic_entity(DatastoreClient $datastore): Entity
{
// [START datastore_basic_entity]
+ /** @var Entity */
$task = $datastore->entity('Task', [
'category' => 'Personal',
'done' => false,
@@ -60,10 +62,11 @@ function basic_entity(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Entity
*/
-function upsert(DatastoreClient $datastore)
+function upsert(DatastoreClient $datastore): Entity
{
// [START datastore_upsert]
$key = $datastore->key('Task', 'sampleTask');
+ /** @var Entity */
$task = $datastore->entity($key, [
'category' => 'Personal',
'done' => false,
@@ -83,9 +86,10 @@ function upsert(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Entity
*/
-function insert(DatastoreClient $datastore)
+function insert(DatastoreClient $datastore): Entity
{
// [START datastore_insert]
+ /** @var Entity */
$task = $datastore->entity('Task', [
'category' => 'Personal',
'done' => false,
@@ -101,12 +105,13 @@ function insert(DatastoreClient $datastore)
* Look up a Datastore entity with the given key.
*
* @param DatastoreClient $datastore
- * @return Entity|null
+ * @return Entity
*/
-function lookup(DatastoreClient $datastore)
+function lookup(DatastoreClient $datastore): Entity
{
// [START datastore_lookup]
$key = $datastore->key('Task', 'sampleTask');
+ /** @var Entity */
$task = $datastore->lookup($key);
// [END datastore_lookup]
return $task;
@@ -116,13 +121,14 @@ function lookup(DatastoreClient $datastore)
* Update a Datastore entity in a transaction.
*
* @param DatastoreClient $datastore
- * @return Entity|null
+ * @return Entity
*/
-function update(DatastoreClient $datastore)
+function update(DatastoreClient $datastore): Entity
{
// [START datastore_update]
$transaction = $datastore->transaction();
$key = $datastore->key('Task', 'sampleTask');
+ /** @var Entity */
$task = $transaction->lookup($key);
$task['priority'] = 5;
$transaction->update($task);
@@ -137,7 +143,7 @@ function update(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @param Key $taskKey
*/
-function delete(DatastoreClient $datastore, Key $taskKey)
+function delete(DatastoreClient $datastore, Key $taskKey): void
{
// [START datastore_delete]
$datastore->delete($taskKey);
@@ -148,9 +154,9 @@ 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)
+function batch_upsert(DatastoreClient $datastore, array $tasks): void
{
// [START datastore_batch_upsert]
$datastore->upsertBatch($tasks);
@@ -161,10 +167,10 @@ 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)
+function batch_lookup(DatastoreClient $datastore, array $keys): array
{
// [START datastore_batch_lookup]
$result = $datastore->lookupBatch($keys);
@@ -183,7 +189,7 @@ function batch_lookup(DatastoreClient $datastore, array $keys)
* @param DatastoreClient $datastore
* @param array $keys
*/
-function batch_delete(DatastoreClient $datastore, array $keys)
+function batch_delete(DatastoreClient $datastore, array $keys): void
{
// [START datastore_batch_delete]
$datastore->deleteBatch($keys);
@@ -196,7 +202,7 @@ function batch_delete(DatastoreClient $datastore, array $keys)
* @param DatastoreClient $datastore
* @return Key
*/
-function named_key(DatastoreClient $datastore)
+function named_key(DatastoreClient $datastore): Key
{
// [START datastore_named_key]
$taskKey = $datastore->key('Task', 'sampleTask');
@@ -210,7 +216,7 @@ function named_key(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Key
*/
-function incomplete_key(DatastoreClient $datastore)
+function incomplete_key(DatastoreClient $datastore): Key
{
// [START datastore_incomplete_key]
$taskKey = $datastore->key('Task');
@@ -224,7 +230,7 @@ function incomplete_key(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Key
*/
-function key_with_parent(DatastoreClient $datastore)
+function key_with_parent(DatastoreClient $datastore): Key
{
// [START datastore_key_with_parent]
$taskKey = $datastore->key('TaskList', 'default')
@@ -239,7 +245,7 @@ function key_with_parent(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Key
*/
-function key_with_multilevel_parent(DatastoreClient $datastore)
+function key_with_multilevel_parent(DatastoreClient $datastore): Key
{
// [START datastore_key_with_multilevel_parent]
$taskKey = $datastore->key('User', 'alice')
@@ -256,9 +262,10 @@ function key_with_multilevel_parent(DatastoreClient $datastore)
* @param Key $key
* @return Entity
*/
-function properties(DatastoreClient $datastore, Key $key)
+function properties(DatastoreClient $datastore, Key $key): Entity
{
// [START datastore_properties]
+ /** @var Entity */
$task = $datastore->entity(
$key,
[
@@ -282,9 +289,10 @@ function properties(DatastoreClient $datastore, Key $key)
* @param Key $key
* @return Entity
*/
-function array_value(DatastoreClient $datastore, Key $key)
+function array_value(DatastoreClient $datastore, Key $key): Entity
{
// [START datastore_array_value]
+ /** @var Entity */
$task = $datastore->entity(
$key,
[
@@ -302,7 +310,7 @@ function array_value(DatastoreClient $datastore, Key $key)
* @param DatastoreClient $datastore
* @return Query
*/
-function basic_query(DatastoreClient $datastore)
+function basic_query(DatastoreClient $datastore): Query
{
// [START datastore_basic_query]
$query = $datastore->query()
@@ -318,9 +326,9 @@ function basic_query(DatastoreClient $datastore)
* Run a given query.
*
* @param DatastoreClient $datastore
- * @return EntityIterator
+ * @return EntityIterator
*/
-function run_query(DatastoreClient $datastore, Query $query)
+function run_query(DatastoreClient $datastore, Query $query): EntityIterator
{
// [START datastore_run_query]
$result = $datastore->runQuery($query);
@@ -334,7 +342,7 @@ function run_query(DatastoreClient $datastore, Query $query)
* @param DatastoreClient $datastore
* @return Query
*/
-function property_filter(DatastoreClient $datastore)
+function property_filter(DatastoreClient $datastore): Query
{
// [START datastore_property_filter]
$query = $datastore->query()
@@ -350,7 +358,7 @@ function property_filter(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function composite_filter(DatastoreClient $datastore)
+function composite_filter(DatastoreClient $datastore): Query
{
// [START datastore_composite_filter]
$query = $datastore->query()
@@ -367,7 +375,7 @@ function composite_filter(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function key_filter(DatastoreClient $datastore)
+function key_filter(DatastoreClient $datastore): Query
{
// [START datastore_key_filter]
$query = $datastore->query()
@@ -383,7 +391,7 @@ function key_filter(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function ascending_sort(DatastoreClient $datastore)
+function ascending_sort(DatastoreClient $datastore): Query
{
// [START datastore_ascending_sort]
$query = $datastore->query()
@@ -399,7 +407,7 @@ function ascending_sort(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function descending_sort(DatastoreClient $datastore)
+function descending_sort(DatastoreClient $datastore): Query
{
// [START datastore_descending_sort]
$query = $datastore->query()
@@ -415,7 +423,7 @@ function descending_sort(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function multi_sort(DatastoreClient $datastore)
+function multi_sort(DatastoreClient $datastore): Query
{
// [START datastore_multi_sort]
$query = $datastore->query()
@@ -432,7 +440,7 @@ function multi_sort(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function ancestor_query(DatastoreClient $datastore)
+function ancestor_query(DatastoreClient $datastore): Query
{
// [START datastore_ancestor_query]
$ancestorKey = $datastore->key('TaskList', 'default');
@@ -450,7 +458,7 @@ function ancestor_query(DatastoreClient $datastore)
* @param Key $lastSeenKey
* @return Query
*/
-function kindless_query(DatastoreClient $datastore, Key $lastSeenKey)
+function kindless_query(DatastoreClient $datastore, Key $lastSeenKey): Query
{
// [START datastore_kindless_query]
$query = $datastore->query()
@@ -465,7 +473,7 @@ function kindless_query(DatastoreClient $datastore, Key $lastSeenKey)
* @param DatastoreClient $datastore
* @return Query
*/
-function keys_only_query(DatastoreClient $datastore)
+function keys_only_query(DatastoreClient $datastore): Query
{
// [START datastore_keys_only_query]
$query = $datastore->query()
@@ -480,7 +488,7 @@ function keys_only_query(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function projection_query(DatastoreClient $datastore)
+function projection_query(DatastoreClient $datastore): Query
{
// [START datastore_projection_query]
$query = $datastore->query()
@@ -495,15 +503,15 @@ function projection_query(DatastoreClient $datastore)
*
* @param DatastoreClient $datastore
* @param Query $query
- * @return array
+ * @return array
*/
-function run_projection_query(DatastoreClient $datastore, Query $query)
+function run_projection_query(DatastoreClient $datastore, Query $query): array
{
// [START datastore_run_query_projection]
$priorities = array();
$percentCompletes = array();
+ /** @var Entity[] */
$result = $datastore->runQuery($query);
- /* @var Entity $task */
foreach ($result as $task) {
$priorities[] = $task['priority'];
$percentCompletes[] = $task['percent_complete'];
@@ -518,7 +526,7 @@ function run_projection_query(DatastoreClient $datastore, Query $query)
* @param DatastoreClient $datastore
* @return Query
*/
-function distinct_on(DatastoreClient $datastore)
+function distinct_on(DatastoreClient $datastore): Query
{
// [START datastore_distinct_on_query]
$query = $datastore->query()
@@ -537,7 +545,7 @@ function distinct_on(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function array_value_inequality_range(DatastoreClient $datastore)
+function array_value_inequality_range(DatastoreClient $datastore): Query
{
// [START datastore_array_value_inequality_range]
$query = $datastore->query()
@@ -554,7 +562,7 @@ function array_value_inequality_range(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function array_value_equality(DatastoreClient $datastore)
+function array_value_equality(DatastoreClient $datastore): Query
{
// [START datastore_array_value_equality]
$query = $datastore->query()
@@ -571,7 +579,7 @@ function array_value_equality(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function limit(DatastoreClient $datastore)
+function limit(DatastoreClient $datastore): Query
{
// [START datastore_limit]
$query = $datastore->query()
@@ -586,20 +594,20 @@ function limit(DatastoreClient $datastore)
* Fetch a query cursor.
*
* @param DatastoreClient $datastore
- * @param string $pageSize
+ * @param int $pageSize
* @param string $pageCursor
- * @return array
+ * @return array{nextPageCursor:string|null,entities:Entity[]}
*/
-function cursor_paging(DatastoreClient $datastore, $pageSize, $pageCursor = '')
+function cursor_paging(DatastoreClient $datastore, int $pageSize, $pageCursor = ''): array
{
$query = $datastore->query()
->kind('Task')
->limit($pageSize)
->start($pageCursor);
+ /** @var Entity[] */
$result = $datastore->runQuery($query);
$nextPageCursor = '';
$entities = [];
- /* @var Entity $entity */
foreach ($result as $entity) {
$nextPageCursor = $entity->cursor();
$entities[] = $entity;
@@ -617,7 +625,7 @@ function cursor_paging(DatastoreClient $datastore, $pageSize, $pageCursor = '')
* @param DatastoreClient $datastore
* @return Query
*/
-function inequality_range(DatastoreClient $datastore)
+function inequality_range(DatastoreClient $datastore): Query
{
// [START datastore_inequality_range]
$query = $datastore->query()
@@ -634,7 +642,7 @@ function inequality_range(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function inequality_invalid(DatastoreClient $datastore)
+function inequality_invalid(DatastoreClient $datastore): Query
{
// [START datastore_inequality_invalid]
$query = $datastore->query()
@@ -652,7 +660,7 @@ function inequality_invalid(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function equal_and_inequality_range(DatastoreClient $datastore)
+function equal_and_inequality_range(DatastoreClient $datastore): Query
{
// [START datastore_equal_and_inequality_range]
$query = $datastore->query()
@@ -671,7 +679,7 @@ function equal_and_inequality_range(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function inequality_sort(DatastoreClient $datastore)
+function inequality_sort(DatastoreClient $datastore): Query
{
// [START datastore_inequality_sort]
$query = $datastore->query()
@@ -689,7 +697,7 @@ function inequality_sort(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function inequality_sort_invalid_not_same(DatastoreClient $datastore)
+function inequality_sort_invalid_not_same(DatastoreClient $datastore): Query
{
// [START datastore_inequality_sort_invalid_not_same]
$query = $datastore->query()
@@ -706,7 +714,7 @@ function inequality_sort_invalid_not_same(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function inequality_sort_invalid_not_first(DatastoreClient $datastore)
+function inequality_sort_invalid_not_first(DatastoreClient $datastore): Query
{
// [START datastore_inequality_sort_invalid_not_first]
$query = $datastore->query()
@@ -724,7 +732,7 @@ function inequality_sort_invalid_not_first(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Query
*/
-function unindexed_property_query(DatastoreClient $datastore)
+function unindexed_property_query(DatastoreClient $datastore): Query
{
// [START datastore_unindexed_property_query]
$query = $datastore->query()
@@ -740,9 +748,10 @@ function unindexed_property_query(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Entity
*/
-function exploding_properties(DatastoreClient $datastore)
+function exploding_properties(DatastoreClient $datastore): Entity
{
// [START datastore_exploding_properties]
+ /** @var Entity */
$task = $datastore->entity(
$datastore->key('Task'),
[
@@ -762,14 +771,14 @@ function exploding_properties(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @param Key $fromKey
* @param Key $toKey
- * @param $amount
+ * @param int $amount
*/
function transfer_funds(
DatastoreClient $datastore,
Key $fromKey,
Key $toKey,
- $amount
-) {
+ int $amount
+): void {
$transaction = $datastore->transaction();
// The option 'sort' is important here, otherwise the order of the result
// might be different from the order of the keys.
@@ -797,7 +806,7 @@ function transactional_retry(
DatastoreClient $datastore,
Key $fromKey,
Key $toKey
-) {
+): void {
// [START datastore_transactional_retry]
$retries = 5;
for ($i = 0; $i < $retries; $i++) {
@@ -819,7 +828,7 @@ function transactional_retry(
* @param DatastoreClient $datastore
* @param Entity $task
*/
-function get_or_create(DatastoreClient $datastore, Entity $task)
+function get_or_create(DatastoreClient $datastore, Entity $task): void
{
// [START datastore_transactional_get_or_create]
$transaction = $datastore->transaction();
@@ -837,7 +846,7 @@ function get_or_create(DatastoreClient $datastore, Entity $task)
* @param DatastoreClient $datastore
* @return array
*/
-function get_task_list_entities(DatastoreClient $datastore)
+function get_task_list_entities(DatastoreClient $datastore): array
{
// [START datastore_transactional_single_entity_group_read_only]
$transaction = $datastore->readOnlyTransaction();
@@ -845,9 +854,9 @@ function get_task_list_entities(DatastoreClient $datastore)
$query = $datastore->query()
->kind('Task')
->hasAncestor($taskListKey);
+ /** @var Entity[] */
$result = $transaction->runQuery($query);
$taskListEntities = [];
- /* @var Entity $task */
foreach ($result as $task) {
$taskListEntities[] = $task;
}
@@ -859,9 +868,9 @@ 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)
+function eventual_consistent_query(DatastoreClient $datastore): EntityIterator
{
// [START datastore_eventual_consistent_query]
$query = $datastore->query()
@@ -878,11 +887,12 @@ function eventual_consistent_query(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return Entity
*/
-function entity_with_parent(DatastoreClient $datastore)
+function entity_with_parent(DatastoreClient $datastore): Entity
{
// [START datastore_entity_with_parent]
$parentKey = $datastore->key('TaskList', 'default');
$key = $datastore->key('Task')->ancestorKey($parentKey);
+ /** @var Entity */
$task = $datastore->entity(
$key,
[
@@ -904,7 +914,7 @@ function entity_with_parent(DatastoreClient $datastore)
* @param string $end an ending namespace (exclusive)
* @return array namespaces returned from the query.
*/
-function namespace_run_query(DatastoreClient $datastore, $start, $end)
+function namespace_run_query(DatastoreClient $datastore, $start, $end): array
{
// [START datastore_namespace_run_query]
$query = $datastore->query()
@@ -928,7 +938,7 @@ function namespace_run_query(DatastoreClient $datastore, $start, $end)
* @param DatastoreClient $datastore
* @return array kinds returned from the query
*/
-function kind_run_query(DatastoreClient $datastore)
+function kind_run_query(DatastoreClient $datastore): array
{
// [START datastore_kind_run_query]
$query = $datastore->query()
@@ -950,7 +960,7 @@ function kind_run_query(DatastoreClient $datastore)
* @param DatastoreClient $datastore
* @return array
*/
-function property_run_query(DatastoreClient $datastore)
+function property_run_query(DatastoreClient $datastore): array
{
// [START datastore_property_run_query]
$query = $datastore->query()
@@ -973,23 +983,22 @@ 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)
+function property_by_kind_run_query(DatastoreClient $datastore): array
{
// [START datastore_property_by_kind_run_query]
$ancestorKey = $datastore->key('__kind__', 'Task');
$query = $datastore->query()
->kind('__property__')
->hasAncestor($ancestorKey);
+ /** @var Entity[] */
$result = $datastore->runQuery($query);
- /* @var array string> $properties */
$properties = [];
- /* @var Entity $entity */
foreach ($result as $entity) {
- $propertyName = $entity->key()->path()[1]['name'];
+ $propertyName = (string) $entity->key()->path()[1]['name'];
$propertyType = $entity['property_representation'];
- $properties[$propertyName] = $propertyType;
+ $properties[$propertyName] = (string) $propertyType;
}
// Example values of $properties: ['description' => ['STRING']]
// [END datastore_property_by_kind_run_query]
@@ -1000,9 +1009,9 @@ function property_by_kind_run_query(DatastoreClient $datastore)
* Create and run a property query with property filtering.
*
* @param DatastoreClient $datastore
- * @return array
+ * @return array
*/
-function property_filtering_run_query(DatastoreClient $datastore)
+function property_filtering_run_query(DatastoreClient $datastore): array
{
// [START datastore_property_filtering_run_query]
$ancestorKey = $datastore->key('__kind__', 'Task');
@@ -1011,10 +1020,10 @@ function property_filtering_run_query(DatastoreClient $datastore)
$query = $datastore->query()
->kind('__property__')
->filter('__key__', '>=', $startKey);
+ /** @var Entity[] */
$result = $datastore->runQuery($query);
- /* @var array $properties */
+ /** @var array */
$properties = [];
- /* @var Entity $entity */
foreach ($result as $entity) {
$kind = $entity->key()->path()[0]['name'];
$propertyName = $entity->key()->path()[1]['name'];
diff --git a/datastore/api/test/ConceptsTest.php b/datastore/api/test/ConceptsTest.php
index bc32dac6a6..a399043fa7 100644
--- a/datastore/api/test/ConceptsTest.php
+++ b/datastore/api/test/ConceptsTest.php
@@ -28,7 +28,7 @@
* @param int $length
* @return string
*/
-function generateRandomString($length = 10)
+function generateRandomString($length = 10): void
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$ret = '';
diff --git a/datastore/tutorial/src/CreateTaskCommand.php b/datastore/tutorial/src/CreateTaskCommand.php
index 8ccfbacb02..8dec72d348 100644
--- a/datastore/tutorial/src/CreateTaskCommand.php
+++ b/datastore/tutorial/src/CreateTaskCommand.php
@@ -31,7 +31,7 @@
*/
class CreateTaskCommand extends Command
{
- protected function configure()
+ protected function configure(): void
{
$this->setName('new')
->setDescription('Adds a task with a description')
diff --git a/datastore/tutorial/src/DeleteTaskCommand.php b/datastore/tutorial/src/DeleteTaskCommand.php
index ce5a824ae2..f5978c8f12 100644
--- a/datastore/tutorial/src/DeleteTaskCommand.php
+++ b/datastore/tutorial/src/DeleteTaskCommand.php
@@ -31,7 +31,7 @@
*/
class DeleteTaskCommand extends Command
{
- protected function configure()
+ protected function configure(): void
{
$this->setName('delete')
->setDescription('Delete a task')
diff --git a/datastore/tutorial/src/ListTasksCommand.php b/datastore/tutorial/src/ListTasksCommand.php
index ad5f6d7e00..5f74571004 100644
--- a/datastore/tutorial/src/ListTasksCommand.php
+++ b/datastore/tutorial/src/ListTasksCommand.php
@@ -32,7 +32,7 @@
*/
class ListTasksCommand extends Command
{
- protected function configure()
+ protected function configure(): void
{
$this->setName('list-tasks')
->setDescription(
@@ -53,10 +53,10 @@ protected function execute(InputInterface $input, OutputInterface $output)
} else {
$datastore = build_datastore_service_with_namespace();
}
+ /** @var Entity[] $result */
$result = list_tasks($datastore);
$table = new Table($output);
$table->setHeaders(array('ID', 'Description', 'Status', 'Created'));
- /* @var Entity $task */
foreach ($result as $index => $task) {
$done = $task['done'] ? 'done' : 'created';
$table->setRow(
diff --git a/datastore/tutorial/src/MarkTaskDoneCommand.php b/datastore/tutorial/src/MarkTaskDoneCommand.php
index 418f37b261..1bac67ac41 100644
--- a/datastore/tutorial/src/MarkTaskDoneCommand.php
+++ b/datastore/tutorial/src/MarkTaskDoneCommand.php
@@ -31,7 +31,7 @@
*/
class MarkTaskDoneCommand extends Command
{
- protected function configure()
+ protected function configure(): void
{
$this->setName('done')
->setDescription('Mark a task as done')
diff --git a/datastore/tutorial/src/functions.php b/datastore/tutorial/src/functions.php
index ce0ccfac1a..89f2b97bf9 100644
--- a/datastore/tutorial/src/functions.php
+++ b/datastore/tutorial/src/functions.php
@@ -19,6 +19,7 @@
use DateTime;
use Google\Cloud\Datastore\EntityIterator;
+use Google\Cloud\Datastore\EntityInterface;
// [START datastore_build_service]
use Google\Cloud\Datastore\DatastoreClient;
@@ -28,7 +29,7 @@
* @param string $projectId
* @return DatastoreClient
*/
-function build_datastore_service($projectId)
+function build_datastore_service($projectId): DatastoreClient
{
$datastore = new DatastoreClient(['projectId' => $projectId]);
return $datastore;
@@ -40,7 +41,7 @@ function build_datastore_service($projectId)
*
* @return DatastoreClient
*/
-function build_datastore_service_with_namespace()
+function build_datastore_service_with_namespace(): DatastoreClient
{
$namespaceId = getenv('CLOUD_DATASTORE_NAMESPACE');
if ($namespaceId === false) {
@@ -54,10 +55,10 @@ function build_datastore_service_with_namespace()
* Create a new task with a given description.
*
* @param DatastoreClient $datastore
- * @param $description
- * @return Google\Cloud\Datastore\Entity
+ * @param string $description
+ * @return \Google\Cloud\Datastore\EntityInterface
*/
-function add_task(DatastoreClient $datastore, $description)
+function add_task(DatastoreClient $datastore, string $description): EntityInterface
{
$taskKey = $datastore->key('Task');
$task = $datastore->entity(
@@ -81,10 +82,11 @@ function add_task(DatastoreClient $datastore, $description)
* @param DatastoreClient $datastore
* @param int $taskId
*/
-function mark_done(DatastoreClient $datastore, $taskId)
+function mark_done(DatastoreClient $datastore, int $taskId): void
{
$taskKey = $datastore->key('Task', $taskId);
$transaction = $datastore->transaction();
+ /** @var \Google\Cloud\Datastore\Entity */
$task = $transaction->lookup($taskKey);
$task['done'] = true;
$transaction->upsert($task);
@@ -97,9 +99,9 @@ function mark_done(DatastoreClient $datastore, $taskId)
* Delete a task with a given id.
*
* @param DatastoreClient $datastore
- * @param $taskId
+ * @param int $taskId
*/
-function delete_task(DatastoreClient $datastore, $taskId)
+function delete_task(DatastoreClient $datastore, int $taskId): void
{
$taskKey = $datastore->key('Task', $taskId);
$datastore->delete($taskKey);
@@ -111,9 +113,9 @@ function delete_task(DatastoreClient $datastore, $taskId)
* Return an iterator for all the tasks in ascending order of creation time.
*
* @param DatastoreClient $datastore
- * @return EntityIterator
+ * @return EntityIterator<\Google\Cloud\Datastore\EntityInterface>
*/
-function list_tasks(DatastoreClient $datastore)
+function list_tasks(DatastoreClient $datastore): EntityIterator
{
$query = $datastore->query()
->kind('Task')
diff --git a/dialogflow/src/context_create.php b/dialogflow/src/context_create.php
index 4e25283a9b..43fa5511f1 100644
--- a/dialogflow/src/context_create.php
+++ b/dialogflow/src/context_create.php
@@ -21,7 +21,7 @@
use Google\Cloud\Dialogflow\V2\ContextsClient;
use Google\Cloud\Dialogflow\V2\Context;
-function context_create($projectId, $contextId, $sessionId, $lifespan = 1)
+function context_create($projectId, $contextId, $sessionId, $lifespan = 1): void
{
$contextsClient = new ContextsClient();
diff --git a/dialogflow/src/context_delete.php b/dialogflow/src/context_delete.php
index 5e49d1e3a7..587edcaf9b 100644
--- a/dialogflow/src/context_delete.php
+++ b/dialogflow/src/context_delete.php
@@ -20,7 +20,7 @@
use Google\Cloud\Dialogflow\V2\ContextsClient;
-function context_delete($projectId, $contextId, $sessionId)
+function context_delete($projectId, $contextId, $sessionId): void
{
$contextsClient = new ContextsClient();
diff --git a/dialogflow/src/context_list.php b/dialogflow/src/context_list.php
index 8fb2d29219..59b6f42e1d 100644
--- a/dialogflow/src/context_list.php
+++ b/dialogflow/src/context_list.php
@@ -20,7 +20,7 @@
use Google\Cloud\Dialogflow\V2\ContextsClient;
-function context_list($projectId, $sessionId)
+function context_list($projectId, $sessionId): void
{
// get contexts
$contextsClient = new ContextsClient();
diff --git a/dialogflow/src/detect_intent_audio.php b/dialogflow/src/detect_intent_audio.php
index caffa0cd14..73aff1a168 100644
--- a/dialogflow/src/detect_intent_audio.php
+++ b/dialogflow/src/detect_intent_audio.php
@@ -28,7 +28,7 @@
* Using the same `session_id` between requests allows continuation
* of the conversation.
*/
-function detect_intent_audio($projectId, $path, $sessionId, $languageCode = 'en-US')
+function detect_intent_audio($projectId, $path, $sessionId, $languageCode = 'en-US'): void
{
// new session
$sessionsClient = new SessionsClient();
diff --git a/dialogflow/src/detect_intent_stream.php b/dialogflow/src/detect_intent_stream.php
index 13ab259b54..d234a7f7ee 100644
--- a/dialogflow/src/detect_intent_stream.php
+++ b/dialogflow/src/detect_intent_stream.php
@@ -29,7 +29,7 @@
* Using the same `session_id` between requests allows continuation
* of the conversation.
*/
-function detect_intent_stream($projectId, $path, $sessionId, $languageCode = 'en-US')
+function detect_intent_stream($projectId, $path, $sessionId, $languageCode = 'en-US'): void
{
// need to use gRPC
if (!defined('Grpc\STATUS_OK')) {
diff --git a/dialogflow/src/detect_intent_texts.php b/dialogflow/src/detect_intent_texts.php
index 91b165f197..2e96ff3dfe 100644
--- a/dialogflow/src/detect_intent_texts.php
+++ b/dialogflow/src/detect_intent_texts.php
@@ -27,7 +27,7 @@
* Using the same `session_id` between requests allows continuation
* of the conversation.
*/
-function detect_intent_texts($projectId, $texts, $sessionId, $languageCode = 'en-US')
+function detect_intent_texts($projectId, $texts, $sessionId, $languageCode = 'en-US'): void
{
// new session
$sessionsClient = new SessionsClient();
diff --git a/dialogflow/src/entity_create.php b/dialogflow/src/entity_create.php
index 57e70dad88..5803ab1c10 100644
--- a/dialogflow/src/entity_create.php
+++ b/dialogflow/src/entity_create.php
@@ -24,7 +24,7 @@
/**
* Create an entity of the given entity type.
*/
-function entity_create($projectId, $entityTypeId, $entityValue, $synonyms = [])
+function entity_create($projectId, $entityTypeId, $entityValue, $synonyms = []): void
{
// synonyms must be exactly [$entityValue] if the entityTypes'
// kind is KIND_LIST
diff --git a/dialogflow/src/entity_delete.php b/dialogflow/src/entity_delete.php
index e113bd69d0..7faeca7210 100644
--- a/dialogflow/src/entity_delete.php
+++ b/dialogflow/src/entity_delete.php
@@ -23,7 +23,7 @@
/**
* Delete entity with the given entity type and entity value.
*/
-function entity_delete($projectId, $entityTypeId, $entityValue)
+function entity_delete($projectId, $entityTypeId, $entityValue): void
{
$entityTypesClient = new EntityTypesClient();
diff --git a/dialogflow/src/entity_list.php b/dialogflow/src/entity_list.php
index 6a9b13caff..0ca1974793 100644
--- a/dialogflow/src/entity_list.php
+++ b/dialogflow/src/entity_list.php
@@ -20,7 +20,7 @@
use Google\Cloud\Dialogflow\V2\EntityTypesClient;
-function entity_list($projectId, $entityTypeId)
+function entity_list($projectId, $entityTypeId): void
{
$entityTypesClient = new EntityTypesClient();
diff --git a/dialogflow/src/entity_type_create.php b/dialogflow/src/entity_type_create.php
index ee3841d1c7..43f0da3001 100644
--- a/dialogflow/src/entity_type_create.php
+++ b/dialogflow/src/entity_type_create.php
@@ -25,7 +25,7 @@
/**
* Create an entity type with the given display name.
*/
-function entity_type_create($projectId, $displayName, $kind = Kind::KIND_MAP)
+function entity_type_create($projectId, $displayName, $kind = Kind::KIND_MAP): void
{
$entityTypesClient = new EntityTypesClient();
diff --git a/dialogflow/src/entity_type_delete.php b/dialogflow/src/entity_type_delete.php
index 996f467b80..32e30b9e18 100644
--- a/dialogflow/src/entity_type_delete.php
+++ b/dialogflow/src/entity_type_delete.php
@@ -23,7 +23,7 @@
/**
* Delete entity type with the given entity type name.
*/
-function entity_type_delete($projectId, $entityTypeId)
+function entity_type_delete($projectId, $entityTypeId): void
{
$entityTypesClient = new EntityTypesClient();
diff --git a/dialogflow/src/entity_type_list.php b/dialogflow/src/entity_type_list.php
index 3363bba43c..7eec9d76bf 100644
--- a/dialogflow/src/entity_type_list.php
+++ b/dialogflow/src/entity_type_list.php
@@ -20,7 +20,7 @@
use Google\Cloud\Dialogflow\V2\EntityTypesClient;
-function entity_type_list($projectId)
+function entity_type_list($projectId): void
{
// get entity types
$entityTypesClient = new EntityTypesClient();
diff --git a/dialogflow/src/intent_delete.php b/dialogflow/src/intent_delete.php
index 300bc25437..8a0cf8f693 100644
--- a/dialogflow/src/intent_delete.php
+++ b/dialogflow/src/intent_delete.php
@@ -23,7 +23,7 @@
/**
* Delete intent with the given intent type and intent value.
*/
-function intent_delete($projectId, $intentId)
+function intent_delete($projectId, $intentId): void
{
$intentsClient = new IntentsClient();
$intentName = $intentsClient->intentName($projectId, $intentId);
diff --git a/dialogflow/src/intent_list.php b/dialogflow/src/intent_list.php
index 876a44455e..30862808b9 100644
--- a/dialogflow/src/intent_list.php
+++ b/dialogflow/src/intent_list.php
@@ -20,7 +20,7 @@
use Google\Cloud\Dialogflow\V2\IntentsClient;
-function intent_list($projectId)
+function intent_list($projectId): void
{
// get intents
$intentsClient = new IntentsClient();
diff --git a/dialogflow/src/session_entity_type_delete.php b/dialogflow/src/session_entity_type_delete.php
index 73063d1f3e..b3609d25fe 100644
--- a/dialogflow/src/session_entity_type_delete.php
+++ b/dialogflow/src/session_entity_type_delete.php
@@ -23,7 +23,7 @@
/**
* Delete a session entity type with the given display name.
*/
-function session_entity_type_delete($projectId, $displayName, $sessionId)
+function session_entity_type_delete($projectId, $displayName, $sessionId): void
{
$sessionEntityTypesClient = new SessionEntityTypesClient();
diff --git a/dialogflow/src/session_entity_type_list.php b/dialogflow/src/session_entity_type_list.php
index 48802be6c5..c56bbeb229 100644
--- a/dialogflow/src/session_entity_type_list.php
+++ b/dialogflow/src/session_entity_type_list.php
@@ -20,7 +20,7 @@
use Google\Cloud\Dialogflow\V2\SessionEntityTypesClient;
-function session_entity_type_list($projectId, $sessionId)
+function session_entity_type_list($projectId, $sessionId): void
{
$sessionEntityTypesClient = new SessionEntityTypesClient();
$parent = $sessionEntityTypesClient->sessionName($projectId, $sessionId);
diff --git a/dlp/src/categorical_stats.php b/dlp/src/categorical_stats.php
index e8ffe6a7ba..5dc62d5f6c 100644
--- a/dlp/src/categorical_stats.php
+++ b/dlp/src/categorical_stats.php
@@ -22,18 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 8) {
- return print("Usage: php categorical_stats.php CALLING_PROJECT DATA_PROJECT TOPIC SUBSCRIPTION DATASET TABLE COLUMN\n");
-}
-list($_, $callingProjectId, $dataProjectId, $topicId, $subscriptionId, $datasetId, $tableId, $columnName) = $argv;
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_categorical_stats]
-/**
- * Computes risk metrics of a column of data in a Google BigQuery table.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\RiskAnalysisJobConfig;
use Google\Cloud\Dlp\V2\BigQueryTable;
@@ -45,118 +36,134 @@
use Google\Cloud\Dlp\V2\FieldId;
use Google\Cloud\PubSub\PubSubClient;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $dataProjectId = 'The project ID containing the target Datastore';
-// $topicId = 'The name of the Pub/Sub topic to notify once the job completes';
-// $subscriptionId = 'The name of the Pub/Sub subscription to use when listening for job';
-// $datasetId = 'The ID of the dataset to inspect';
-// $tableId = 'The ID of the table to inspect';
-// $columnName = 'The name of the column to compute risk metrics for, e.g. "age"';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient([
- 'projectId' => $callingProjectId,
-]);
-$pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
-]);
-$topic = $pubsub->topic($topicId);
-
-// Construct risk analysis config
-$columnField = (new FieldId())
- ->setName($columnName);
-
-$statsConfig = (new CategoricalStatsConfig())
- ->setField($columnField);
-
-$privacyMetric = (new PrivacyMetric())
- ->setCategoricalStatsConfig($statsConfig);
-
-// Construct items to be analyzed
-$bigqueryTable = (new BigQueryTable())
- ->setProjectId($dataProjectId)
- ->setDatasetId($datasetId)
- ->setTableId($tableId);
-
-// Construct the action to run when job completes
-$pubSubAction = (new PublishToPubSub())
- ->setTopic($topic->name());
-
-$action = (new Action())
- ->setPubSub($pubSubAction);
-
-// 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
-]);
-
-// Listen for job notifications via an existing topic/subscription.
-$subscription = $topic->subscription($subscriptionId);
-
-// 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:
- $histBuckets = $job->getRiskDetails()->getCategoricalStatsResult()->getValueFrequencyHistogramBuckets();
-
- foreach ($histBuckets as $bucketIndex => $histBucket) {
- // Print bucket stats
- printf('Bucket %s:' . PHP_EOL, $bucketIndex);
- printf(' Most common value occurs %s time(s)' . PHP_EOL, $histBucket->getValueFrequencyUpperBound());
- printf(' Least common value occurs %s time(s)' . PHP_EOL, $histBucket->getValueFrequencyLowerBound());
- printf(' %s unique value(s) total.', $histBucket->getBucketSize());
-
- // Print bucket values
- foreach ($histBucket->getBucketValues() as $percent => $quantile) {
- printf(
- ' Value %s occurs %s time(s).' . PHP_EOL,
- $quantile->getValue()->serializeToJsonString(),
- $quantile->getCount()
- );
+/**
+ * Computes risk metrics of a column of data in a Google BigQuery table.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $dataProjectId The project ID containing the target Datastore
+ * @param string $topicId The name of the Pub/Sub topic to notify once the job completes
+ * @param string $subscriptionId The name of the Pub/Sub subscription to use when listening for job
+ * @param string $datasetId The ID of the dataset to inspect
+ * @param string $tableId The ID of the table to inspect
+ * @param string $columnName The name of the column to compute risk metrics for, e.g. "age"
+ */
+function categorical_stats(
+ string $callingProjectId,
+ string $dataProjectId,
+ string $topicId,
+ string $subscriptionId,
+ string $datasetId,
+ string $tableId,
+ string $columnName
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $pubsub = new PubSubClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $topic = $pubsub->topic($topicId);
+
+ // Construct risk analysis config
+ $columnField = (new FieldId())
+ ->setName($columnName);
+
+ $statsConfig = (new CategoricalStatsConfig())
+ ->setField($columnField);
+
+ $privacyMetric = (new PrivacyMetric())
+ ->setCategoricalStatsConfig($statsConfig);
+
+ // Construct items to be analyzed
+ $bigqueryTable = (new BigQueryTable())
+ ->setProjectId($dataProjectId)
+ ->setDatasetId($datasetId)
+ ->setTableId($tableId);
+
+ // Construct the action to run when job completes
+ $pubSubAction = (new PublishToPubSub())
+ ->setTopic($topic->name());
+
+ $action = (new Action())
+ ->setPubSub($pubSubAction);
+
+ // 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
+ ]);
+
+ // Listen for job notifications via an existing topic/subscription.
+ $subscription = $topic->subscription($subscriptionId);
+
+ // 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:
+ $histBuckets = $job->getRiskDetails()->getCategoricalStatsResult()->getValueFrequencyHistogramBuckets();
+
+ foreach ($histBuckets as $bucketIndex => $histBucket) {
+ // Print bucket stats
+ printf('Bucket %s:' . PHP_EOL, $bucketIndex);
+ printf(' Most common value occurs %s time(s)' . PHP_EOL, $histBucket->getValueFrequencyUpperBound());
+ printf(' Least common value occurs %s time(s)' . PHP_EOL, $histBucket->getValueFrequencyLowerBound());
+ printf(' %s unique value(s) total.', $histBucket->getBucketSize());
+
+ // Print bucket values
+ foreach ($histBucket->getBucketValues() as $percent => $quantile) {
+ printf(
+ ' Value %s occurs %s time(s).' . PHP_EOL,
+ $quantile->getValue()->serializeToJsonString(),
+ $quantile->getCount()
+ );
+ }
+ }
- break;
- case JobState::FAILED:
- $errors = $job->getErrors();
- printf('Job %s had errors:' . PHP_EOL, $job->getName());
- 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.');
+ break;
+ case JobState::FAILED:
+ $errors = $job->getErrors();
+ printf('Job %s had errors:' . PHP_EOL, $job->getName());
+ 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.');
+ }
}
# [END dlp_categorical_stats]
+
+// 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_inspect_template.php b/dlp/src/create_inspect_template.php
index 033e3e27e8..839be01ed1 100644
--- a/dlp/src/create_inspect_template.php
+++ b/dlp/src/create_inspect_template.php
@@ -22,21 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 3 || count($argv) > 6) {
- return print("Usage: php create_inspect_template.php CALLING_PROJECT TEMPLATE [DISPLAY_NAME] [DESCRIPTION] [MAX_FINDINGS]\n");
-}
-list($_, $callingProjectId, $templateId, $displayName, $description) = $argv;
-$displayName = isset($argv[3]) ? $argv[3] : '';
-$description = isset($argv[4]) ? $argv[4] : '';
-$maxFindings = isset($argv[5]) ? (int) $argv[5] : 0;
+namespace Google\Cloud\Samples\Dlp;
// [START dlp_create_inspect_template]
-/**
- * Create a new DLP inspection configuration template.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
@@ -44,53 +32,67 @@
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $templateId = 'The name of the template to be created';
-// $displayName = ''; // (Optional) The human-readable name to give the template
-// $description = ''; // (Optional) A description for the trigger to be created
-// $maxFindings = 0; // (Optional) The maximum number of findings to report per request (0 = server maximum)
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
+/**
+ * Create a new DLP inspection configuration template.
+ *
+ * @param string $callingProjectId project ID to run the API call under
+ * @param string $templateId name of the template to be created
+ * @param string $displayName (Optional) The human-readable name to give the template
+ * @param string $description (Optional) A description for the trigger to be created
+ * @param int $maxFindings (Optional) The maximum number of findings to report per request (0 = server maximum)
+ */
+function create_inspect_template(
+ string $callingProjectId,
+ string $templateId,
+ string $displayName = '',
+ string $description = '',
+ int $maxFindings = 0
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
-// ----- Construct inspection config -----
-// The infoTypes of information to match
-$personNameInfoType = (new InfoType())
- ->setName('PERSON_NAME');
-$phoneNumberInfoType = (new InfoType())
- ->setName('PHONE_NUMBER');
-$infoTypes = [$personNameInfoType, $phoneNumberInfoType];
+ // ----- Construct inspection config -----
+ // The infoTypes of information to match
+ $personNameInfoType = (new InfoType())
+ ->setName('PERSON_NAME');
+ $phoneNumberInfoType = (new InfoType())
+ ->setName('PHONE_NUMBER');
+ $infoTypes = [$personNameInfoType, $phoneNumberInfoType];
-// Whether to include the matching string in the response
-$includeQuote = true;
+ // Whether to include the matching string in the response
+ $includeQuote = true;
-// The minimum likelihood required before returning a match
-$minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
+ // The minimum likelihood required before returning a match
+ $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
-// Specify finding limits
-$limits = (new FindingLimits())
- ->setMaxFindingsPerRequest($maxFindings);
+ // Specify finding limits
+ $limits = (new FindingLimits())
+ ->setMaxFindingsPerRequest($maxFindings);
-// Create the configuration object
-$inspectConfig = (new InspectConfig())
- ->setMinLikelihood($minLikelihood)
- ->setLimits($limits)
- ->setInfoTypes($infoTypes)
- ->setIncludeQuote($includeQuote);
+ // Create the configuration object
+ $inspectConfig = (new InspectConfig())
+ ->setMinLikelihood($minLikelihood)
+ ->setLimits($limits)
+ ->setInfoTypes($infoTypes)
+ ->setIncludeQuote($includeQuote);
-// Construct inspection template
-$inspectTemplate = (new InspectTemplate())
- ->setInspectConfig($inspectConfig)
- ->setDisplayName($displayName)
- ->setDescription($description);
+ // Construct inspection template
+ $inspectTemplate = (new InspectTemplate())
+ ->setInspectConfig($inspectConfig)
+ ->setDisplayName($displayName)
+ ->setDescription($description);
-// Run request
-$parent = "projects/$callingProjectId/locations/global";
-$template = $dlp->createInspectTemplate($parent, $inspectTemplate, [
- 'templateId' => $templateId
-]);
+ // Run request
+ $parent = "projects/$callingProjectId/locations/global";
+ $template = $dlp->createInspectTemplate($parent, $inspectTemplate, [
+ 'templateId' => $templateId
+ ]);
-// Print results
-printf('Successfully created template %s' . PHP_EOL, $template->getName());
+ // Print results
+ printf('Successfully created template %s' . PHP_EOL, $template->getName());
+}
// [END dlp_create_inspect_template]
+
+// 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 8d2715785d..55ad1f2cc0 100644
--- a/dlp/src/create_trigger.php
+++ b/dlp/src/create_trigger.php
@@ -22,24 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 3 || count($argv) > 9) {
- return print("Usage: php create_trigger.php CALLING_PROJECT BUCKET [TRIGGER] [DISPLAY_NAME] [DESCRIPTION] [SCAN_PERIOD] [AUTO_POPULATE_TIMESPAN] [MAX_FINDINGS]\n");
-}
-list($_, $callingProjectId, $bucketName) = $argv;
-$triggerId = isset($argv[3]) ? $argv[3] : '';
-$displayName = isset($argv[4]) ? $argv[4] : '';
-$description = isset($argv[5]) ? $argv[5] : '';
-$scanPeriod = isset($argv[6]) ? (int) $argv[6] : 1;
-$autoPopulateTimespan = isset($argv[7]) ? (bool) $argv[7] : false;
-$maxFindings = isset($argv[8]) ? (int) $argv[8] : 0;
+namespace Google\Cloud\Samples\Dlp;
// [START dlp_create_trigger]
-/**
- * Create a Data Loss Prevention API job trigger.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\JobTrigger;
use Google\Cloud\Dlp\V2\JobTrigger\Trigger;
@@ -56,84 +41,101 @@
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Protobuf\Duration;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $bucketName = 'The name of the bucket to scan';
-// $triggerId = ''; // (Optional) The name of the trigger to be created';
-// $displayName = ''; // (Optional) The human-readable name to give the trigger';
-// $description = ''; // (Optional) A description for the trigger to be created';
-// $scanPeriod = 1; // (Optional) How often to wait between scans, in days (minimum = 1 day)
-// $autoPopulateTimespan = true; // (Optional) Automatically limit scan to new content only
-// $maxFindings = 0; // (Optional) The maximum number of findings to report per request (0 = server maximum)
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-
-// ----- Construct job config -----
-// The infoTypes of information to match
-$personNameInfoType = (new InfoType())
- ->setName('PERSON_NAME');
-$phoneNumberInfoType = (new InfoType())
- ->setName('PHONE_NUMBER');
-$infoTypes = [$personNameInfoType, $phoneNumberInfoType];
-
-// The minimum likelihood required before returning a match
-$minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
-
-// Specify finding limits
-$limits = (new FindingLimits())
- ->setMaxFindingsPerRequest($maxFindings);
-
-// Create the inspectConfig object
-$inspectConfig = (new InspectConfig())
- ->setMinLikelihood($minLikelihood)
- ->setLimits($limits)
- ->setInfoTypes($infoTypes);
-
-// Create triggers
-$duration = (new Duration())
- ->setSeconds($scanPeriod * 60 * 60 * 24);
-
-$schedule = (new Schedule())
- ->setRecurrencePeriodDuration($duration);
-
-$triggerObject = (new Trigger())
- ->setSchedule($schedule);
-
-// Create the storageConfig object
-$fileSet = (new CloudStorageOptions_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())
- ->setEnableAutoPopulationOfTimespanConfig($autoPopulateTimespan);
-
-$storageConfig = (new StorageConfig())
- ->setCloudStorageOptions($storageOptions)
- ->setTimespanConfig($timespanConfig);
-
-// Construct the jobConfig object
-$jobConfig = (new InspectJobConfig())
- ->setInspectConfig($inspectConfig)
- ->setStorageConfig($storageConfig);
-
-// ----- Construct trigger object -----
-$jobTriggerObject = (new JobTrigger())
- ->setTriggers([$triggerObject])
- ->setInspectJob($jobConfig)
- ->setStatus(Status::HEALTHY)
- ->setDisplayName($displayName)
- ->setDescription($description);
-
-// Run trigger creation request
-$parent = "projects/$callingProjectId/locations/global";
-$trigger = $dlp->createJobTrigger($parent, $jobTriggerObject, [
- 'triggerId' => $triggerId
-]);
-
-// Print results
-printf('Successfully created trigger %s' . PHP_EOL, $trigger->getName());
+/**
+ * Create a Data Loss Prevention API job trigger.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $bucketName The name of the bucket to scan
+ * @param string $triggerId (Optional) The name of the trigger to be created
+ * @param string $displayName (Optional) The human-readable name to give the trigger
+ * @param string $description (Optional) A description for the trigger to be created
+ * @param int $scanPeriod (Optional) How often to wait between scans, in days (minimum = 1 day)
+ * @param bool $autoPopulateTimespan (Optional) Automatically limit scan to new content only
+ * @param int $maxFindings (Optional) The maximum number of findings to report per request (0 = server maximum)
+ */
+function create_trigger(
+ string $callingProjectId,
+ string $bucketName,
+ string $triggerId = '',
+ string $displayName = '',
+ string $description = '',
+ int $scanPeriod = 0,
+ bool $autoPopulateTimespan = false,
+ int $maxFindings = 0
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // ----- Construct job config -----
+ // The infoTypes of information to match
+ $personNameInfoType = (new InfoType())
+ ->setName('PERSON_NAME');
+ $phoneNumberInfoType = (new InfoType())
+ ->setName('PHONE_NUMBER');
+ $infoTypes = [$personNameInfoType, $phoneNumberInfoType];
+
+ // The minimum likelihood required before returning a match
+ $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
+
+ // Specify finding limits
+ $limits = (new FindingLimits())
+ ->setMaxFindingsPerRequest($maxFindings);
+
+ // Create the inspectConfig object
+ $inspectConfig = (new InspectConfig())
+ ->setMinLikelihood($minLikelihood)
+ ->setLimits($limits)
+ ->setInfoTypes($infoTypes);
+
+ // Create triggers
+ $duration = (new Duration())
+ ->setSeconds($scanPeriod * 60 * 60 * 24);
+
+ $schedule = (new Schedule())
+ ->setRecurrencePeriodDuration($duration);
+
+ $triggerObject = (new Trigger())
+ ->setSchedule($schedule);
+
+ // Create the storageConfig object
+ $fileSet = (new CloudStorageOptions_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())
+ ->setEnableAutoPopulationOfTimespanConfig($autoPopulateTimespan);
+
+ $storageConfig = (new StorageConfig())
+ ->setCloudStorageOptions($storageOptions)
+ ->setTimespanConfig($timespanConfig);
+
+ // Construct the jobConfig object
+ $jobConfig = (new InspectJobConfig())
+ ->setInspectConfig($inspectConfig)
+ ->setStorageConfig($storageConfig);
+
+ // ----- Construct trigger object -----
+ $jobTriggerObject = (new JobTrigger())
+ ->setTriggers([$triggerObject])
+ ->setInspectJob($jobConfig)
+ ->setStatus(Status::HEALTHY)
+ ->setDisplayName($displayName)
+ ->setDescription($description);
+
+ // Run trigger creation request
+ $parent = "projects/$callingProjectId/locations/global";
+ $trigger = $dlp->createJobTrigger($parent, $jobTriggerObject, [
+ 'triggerId' => $triggerId
+ ]);
+
+ // Print results
+ printf('Successfully created trigger %s' . PHP_EOL, $trigger->getName());
+}
// [END dlp_create_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/deidentify_dates.php b/dlp/src/deidentify_dates.php
index c791f6c1a1..a802bee8d6 100644
--- a/dlp/src/deidentify_dates.php
+++ b/dlp/src/deidentify_dates.php
@@ -22,21 +22,11 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 7 || count($argv) > 10) {
- return print("Usage: php deidentify_dates.php CALLING_PROJECT INPUT_CSV OUTPUT_CSV DATE_FIELDS LOWER_BOUND_DAYS UPPER_BOUND_DAYS [CONTEXT_FIELDS] [KEY_NAME] [WRAPPED_KEY]\n");
-}
-list($_, $callingProjectId, $inputCsvFile, $outputCsvFile, $dateFieldNames, $lowerBoundDays, $upperBoundDays) = $argv;
-$contextFieldName = isset($argv[7]) ? $argv[7] : '';
-$keyName = isset($argv[8]) ? $argv[8] : '';
-$wrappedKey = isset($argv[9]) ? $argv[9] : '';
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_deidentify_date_shift]
-/**
- * Deidentify dates in a CSV file by pseudorandomly shifting them.
- */
+use DateTime;
+use Exception;
use Google\Cloud\Dlp\V2\ContentItem;
use Google\Cloud\Dlp\V2\CryptoKey;
use Google\Cloud\Dlp\V2\DateShiftConfig;
@@ -52,138 +42,154 @@
use Google\Cloud\Dlp\V2\Value;
use Google\Type\Date;
-/** Uncomment and populate these variables in your code */
-// $callingProject = 'The GCP Project ID to run the API call under';
-// $inputCsvFile = 'The path to the CSV file to deidentify';
-// $outputCsvFile = 'The path to save the date-shifted CSV file to';
-// $dateFieldNames = 'The comma-separated list of (date) fields in the CSV file to date shift';
-// $lowerBoundDays = 'The maximum number of days to shift a date backward';
-// $upperBoundDays = 'The maximum number of days to shift a date forward';
/**
+ * Deidentify dates in a CSV file by pseudorandomly shifting them.
* If contextFieldName is not specified, a random shift amount will be used for every row.
- * If contextFieldName is specified, then 'wrappedKey' and 'keyName' must also be set
+ * If contextFieldName is specified, then 'wrappedKey' and 'keyName' must also be set.
+ *
+ * @param string $callingProjectId The GCP Project ID to run the API call under
+ * @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 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
*/
-// $contextFieldName = ''; (Optional) The column to determine date shift amount based on
-// $keyName = ''; // Optional) The encrypted ('wrapped') AES-256 key to use when shifting dates
-// $wrappedKey = ''; // (Optional) The name of the Cloud KMS key used to encrypt (wrap) the AES-256 key
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-
-// Read a CSV file
-$csvLines = file($inputCsvFile, FILE_IGNORE_NEW_LINES);
-$csvHeaders = explode(',', $csvLines[0]);
-$csvRows = array_slice($csvLines, 1);
-
-// Convert CSV file into protobuf objects
-$tableHeaders = array_map(function ($csvHeader) {
- return (new FieldId)->setName($csvHeader);
-}, $csvHeaders);
-
-$tableRows = array_map(function ($csvRow) {
- $rowValues = array_map(function ($csvValue) {
- if ($csvDate = DateTime::createFromFormat('m/d/Y', $csvValue)) {
- $date = (new Date())
- ->setYear((int) $csvDate->format('Y'))
- ->setMonth((int) $csvDate->format('m'))
- ->setDay((int) $csvDate->format('d'));
- return (new Value())
- ->setDateValue($date);
- } else {
- return (new Value())
- ->setStringValue($csvValue);
- }
- }, explode(',', $csvRow));
-
- return (new Row())
- ->setValues($rowValues);
-}, $csvRows);
-
-// Convert date fields into protobuf objects
-$dateFields = array_map(function ($dateFieldName) {
- return (new FieldId())->setName($dateFieldName);
-}, explode(',', $dateFieldNames));
-
-// Construct the table object
-$table = (new Table())
- ->setHeaders($tableHeaders)
- ->setRows($tableRows);
-
-$item = (new ContentItem())
- ->setTable($table);
-
-// Construct dateShiftConfig
-$dateShiftConfig = (new DateShiftConfig())
- ->setLowerBoundDays($lowerBoundDays)
- ->setUpperBoundDays($upperBoundDays);
-
-if ($contextFieldName && $keyName && $wrappedKey) {
- $contextField = (new FieldId())
- ->setName($contextFieldName);
-
- // Create the wrapped crypto key configuration object
- $kmsWrappedCryptoKey = (new KmsWrappedCryptoKey())
- ->setWrappedKey(base64_decode($wrappedKey))
- ->setCryptoKeyName($keyName);
-
- $cryptoKey = (new CryptoKey())
- ->setKmsWrapped($kmsWrappedCryptoKey);
-
- $dateShiftConfig
- ->setContext($contextField)
- ->setCryptoKey($cryptoKey);
-} elseif ($contextFieldName || $keyName || $wrappedKey) {
- throw new Exception('You must set either ALL or NONE of {$contextFieldName, $keyName, $wrappedKey}!');
-}
-
-// Create the information transform configuration objects
-$primitiveTransformation = (new PrimitiveTransformation())
- ->setDateShiftConfig($dateShiftConfig);
-
-$fieldTransformation = (new FieldTransformation())
- ->setPrimitiveTransformation($primitiveTransformation)
- ->setFields($dateFields);
-
-$recordTransformations = (new RecordTransformations())
- ->setFieldTransformations([$fieldTransformation]);
-
-// Create the deidentification configuration object
-$deidentifyConfig = (new DeidentifyConfig())
- ->setRecordTransformations($recordTransformations);
-
-$parent = "projects/$callingProjectId/locations/global";
-
-// Run request
-$response = $dlp->deidentifyContent([
- 'parent' => $parent,
- 'deidentifyConfig' => $deidentifyConfig,
- 'item' => $item
-]);
+function deidentify_dates(
+ string $callingProjectId,
+ string $inputCsvFile,
+ string $outputCsvFile,
+ string $dateFieldNames,
+ string $lowerBoundDays,
+ string $upperBoundDays,
+ string $contextFieldName = '',
+ string $keyName = '',
+ string $wrappedKey = ''
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // Read a CSV file
+ $csvLines = file($inputCsvFile, FILE_IGNORE_NEW_LINES);
+ $csvHeaders = explode(',', $csvLines[0]);
+ $csvRows = array_slice($csvLines, 1);
+
+ // Convert CSV file into protobuf objects
+ $tableHeaders = array_map(function ($csvHeader) {
+ return (new FieldId)->setName($csvHeader);
+ }, $csvHeaders);
+
+ $tableRows = array_map(function ($csvRow) {
+ $rowValues = array_map(function ($csvValue) {
+ if ($csvDate = DateTime::createFromFormat('m/d/Y', $csvValue)) {
+ $date = (new Date())
+ ->setYear((int) $csvDate->format('Y'))
+ ->setMonth((int) $csvDate->format('m'))
+ ->setDay((int) $csvDate->format('d'));
+ return (new Value())
+ ->setDateValue($date);
+ } else {
+ return (new Value())
+ ->setStringValue($csvValue);
+ }
+ }, explode(',', $csvRow));
+
+ return (new Row())
+ ->setValues($rowValues);
+ }, $csvRows);
+
+ // Convert date fields into protobuf objects
+ $dateFields = array_map(function ($dateFieldName) {
+ return (new FieldId())->setName($dateFieldName);
+ }, explode(',', $dateFieldNames));
+
+ // Construct the table object
+ $table = (new Table())
+ ->setHeaders($tableHeaders)
+ ->setRows($tableRows);
+
+ $item = (new ContentItem())
+ ->setTable($table);
+
+ // Construct dateShiftConfig
+ $dateShiftConfig = (new DateShiftConfig())
+ ->setLowerBoundDays($lowerBoundDays)
+ ->setUpperBoundDays($upperBoundDays);
+
+ if ($contextFieldName && $keyName && $wrappedKey) {
+ $contextField = (new FieldId())
+ ->setName($contextFieldName);
+
+ // Create the wrapped crypto key configuration object
+ $kmsWrappedCryptoKey = (new KmsWrappedCryptoKey())
+ ->setWrappedKey(base64_decode($wrappedKey))
+ ->setCryptoKeyName($keyName);
+
+ $cryptoKey = (new CryptoKey())
+ ->setKmsWrapped($kmsWrappedCryptoKey);
+
+ $dateShiftConfig
+ ->setContext($contextField)
+ ->setCryptoKey($cryptoKey);
+ } elseif ($contextFieldName || $keyName || $wrappedKey) {
+ throw new Exception('You must set either ALL or NONE of {$contextFieldName, $keyName, $wrappedKey}!');
+ }
-// Check for errors
-foreach ($response->getOverview()->getTransformationSummaries() as $summary) {
- foreach ($summary->getResults() as $result) {
- if ($details = $result->getDetails()) {
- printf('Error: %s' . PHP_EOL, $details);
- return;
+ // Create the information transform configuration objects
+ $primitiveTransformation = (new PrimitiveTransformation())
+ ->setDateShiftConfig($dateShiftConfig);
+
+ $fieldTransformation = (new FieldTransformation())
+ ->setPrimitiveTransformation($primitiveTransformation)
+ ->setFields($dateFields);
+
+ $recordTransformations = (new RecordTransformations())
+ ->setFieldTransformations([$fieldTransformation]);
+
+ // Create the deidentification configuration object
+ $deidentifyConfig = (new DeidentifyConfig())
+ ->setRecordTransformations($recordTransformations);
+
+ $parent = "projects/$callingProjectId/locations/global";
+
+ // Run request
+ $response = $dlp->deidentifyContent([
+ 'parent' => $parent,
+ 'deidentifyConfig' => $deidentifyConfig,
+ 'item' => $item
+ ]);
+
+ // Check for errors
+ foreach ($response->getOverview()->getTransformationSummaries() as $summary) {
+ foreach ($summary->getResults() as $result) {
+ if ($details = $result->getDetails()) {
+ printf('Error: %s' . PHP_EOL, $details);
+ return;
+ }
}
}
-}
-// Save the results to a file
-$csvRef = fopen($outputCsvFile, 'w');
-fputcsv($csvRef, $csvHeaders);
-foreach ($response->getItem()->getTable()->getRows() as $tableRow) {
- $values = array_map(function ($tableValue) {
- if ($tableValue->getStringValue()) {
- return $tableValue->getStringValue();
- }
- $protoDate = $tableValue->getDateValue();
- $date = mktime(0, 0, 0, $protoDate->getMonth(), $protoDate->getDay(), $protoDate->getYear());
- return strftime('%D', $date);
- }, iterator_to_array($tableRow->getValues()));
- fputcsv($csvRef, $values);
-};
-fclose($csvRef);
-printf('Deidentified dates written to %s' . PHP_EOL, $outputCsvFile);
+ // Save the results to a file
+ $csvRef = fopen($outputCsvFile, 'w');
+ fputcsv($csvRef, $csvHeaders);
+ foreach ($response->getItem()->getTable()->getRows() as $tableRow) {
+ $values = array_map(function ($tableValue) {
+ if ($tableValue->getStringValue()) {
+ return $tableValue->getStringValue();
+ }
+ $protoDate = $tableValue->getDateValue();
+ $date = mktime(0, 0, 0, $protoDate->getMonth(), $protoDate->getDay(), $protoDate->getYear());
+ return strftime('%D', $date);
+ }, iterator_to_array($tableRow->getValues()));
+ fputcsv($csvRef, $values);
+ };
+ fclose($csvRef);
+ printf('Deidentified dates written to %s' . PHP_EOL, $outputCsvFile);
+}
# [END dlp_deidentify_date_shift]
+
+// 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/deidentify_fpe.php b/dlp/src/deidentify_fpe.php
index dd4bda8305..bfe9027101 100644
--- a/dlp/src/deidentify_fpe.php
+++ b/dlp/src/deidentify_fpe.php
@@ -22,19 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 5 || count($argv) > 6) {
- return print("Usage: php deidentify_fpe.php CALLING_PROJECT STRING KEY_NAME WRAPPED_KEY [SURROGATE_TYPE_NAME]\n");
-}
-list($_, $callingProjectId, $string, $keyName, $wrappedKey) = $argv;
-$surrogateTypeName = isset($argv[5]) ? $argv[5] : '';
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_deidentify_fpe]
-/**
- * Deidentify a string using Format-Preserving Encryption (FPE).
- */
use Google\Cloud\Dlp\V2\CryptoReplaceFfxFpeConfig;
use Google\Cloud\Dlp\V2\CryptoReplaceFfxFpeConfig\FfxCommonNativeAlphabet;
use Google\Cloud\Dlp\V2\CryptoKey;
@@ -47,73 +37,87 @@
use Google\Cloud\Dlp\V2\InfoTypeTransformations;
use Google\Cloud\Dlp\V2\ContentItem;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The GCP Project ID to run the API call under';
-// $string = 'The string to deidentify';
-// $keyName = 'The name of the Cloud KMS key used to encrypt (wrap) the AES-256 key';
-// $wrappedKey = 'The name of the Cloud KMS key use, encrypted with the KMS key in $keyName';
-// $surrogateTypeName = ''; // (Optional) surrogate custom info type to enable reidentification
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-
-// The infoTypes of information to mask
-$ssnInfoType = (new InfoType())
- ->setName('US_SOCIAL_SECURITY_NUMBER');
-$infoTypes = [$ssnInfoType];
-
-// Create the wrapped crypto key configuration object
-$kmsWrappedCryptoKey = (new KmsWrappedCryptoKey())
- ->setWrappedKey(base64_decode($wrappedKey))
- ->setCryptoKeyName($keyName);
-
-// The set of characters to replace sensitive ones with
-// For more information, see https://cloud.google.com/dlp/docs/reference/rest/V2/organizations.deidentifyTemplates#ffxcommonnativealphabet
-$commonAlphabet = FfxCommonNativeAlphabet::NUMERIC;
-
-// Create the crypto key configuration object
-$cryptoKey = (new CryptoKey())
- ->setKmsWrapped($kmsWrappedCryptoKey);
-
-// Create the crypto FFX FPE configuration object
-$cryptoReplaceFfxFpeConfig = (new CryptoReplaceFfxFpeConfig())
- ->setCryptoKey($cryptoKey)
- ->setCommonAlphabet($commonAlphabet);
-
-if ($surrogateTypeName) {
- $surrogateType = (new InfoType())
- ->setName($surrogateTypeName);
- $cryptoReplaceFfxFpeConfig->setSurrogateInfoType($surrogateType);
+/**
+ * Deidentify a string using Format-Preserving Encryption (FPE).
+ *
+ * @param string $callingProjectId The GCP Project ID to run the API call under
+ * @param string $string The string to deidentify
+ * @param string $keyName The name of the Cloud KMS key used to encrypt (wrap) the AES-256 key
+ * @param string $wrappedKey The name of the Cloud KMS key use, encrypted with the KMS key in $keyName
+ * @param string $surrogateTypeName (Optional) surrogate custom info type to enable reidentification
+ */
+function deidentify_fpe(
+ string $callingProjectId,
+ string $string,
+ string $keyName,
+ string $wrappedKey,
+ string $surrogateTypeName = ''
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // The infoTypes of information to mask
+ $ssnInfoType = (new InfoType())
+ ->setName('US_SOCIAL_SECURITY_NUMBER');
+ $infoTypes = [$ssnInfoType];
+
+ // Create the wrapped crypto key configuration object
+ $kmsWrappedCryptoKey = (new KmsWrappedCryptoKey())
+ ->setWrappedKey(base64_decode($wrappedKey))
+ ->setCryptoKeyName($keyName);
+
+ // The set of characters to replace sensitive ones with
+ // For more information, see https://cloud.google.com/dlp/docs/reference/rest/V2/organizations.deidentifyTemplates#ffxcommonnativealphabet
+ $commonAlphabet = FfxCommonNativeAlphabet::NUMERIC;
+
+ // Create the crypto key configuration object
+ $cryptoKey = (new CryptoKey())
+ ->setKmsWrapped($kmsWrappedCryptoKey);
+
+ // Create the crypto FFX FPE configuration object
+ $cryptoReplaceFfxFpeConfig = (new CryptoReplaceFfxFpeConfig())
+ ->setCryptoKey($cryptoKey)
+ ->setCommonAlphabet($commonAlphabet);
+
+ if ($surrogateTypeName) {
+ $surrogateType = (new InfoType())
+ ->setName($surrogateTypeName);
+ $cryptoReplaceFfxFpeConfig->setSurrogateInfoType($surrogateType);
+ }
+
+ // Create the information transform configuration objects
+ $primitiveTransformation = (new PrimitiveTransformation())
+ ->setCryptoReplaceFfxFpeConfig($cryptoReplaceFfxFpeConfig);
+
+ $infoTypeTransformation = (new InfoTypeTransformation())
+ ->setPrimitiveTransformation($primitiveTransformation)
+ ->setInfoTypes($infoTypes);
+
+ $infoTypeTransformations = (new InfoTypeTransformations())
+ ->setTransformations([$infoTypeTransformation]);
+
+ // Create the deidentification configuration object
+ $deidentifyConfig = (new DeidentifyConfig())
+ ->setInfoTypeTransformations($infoTypeTransformations);
+
+ $content = (new ContentItem())
+ ->setValue($string);
+
+ $parent = "projects/$callingProjectId/locations/global";
+
+ // Run request
+ $response = $dlp->deidentifyContent([
+ 'parent' => $parent,
+ 'deidentifyConfig' => $deidentifyConfig,
+ 'item' => $content
+ ]);
+
+ // Print the results
+ $deidentifiedValue = $response->getItem()->getValue();
+ print($deidentifiedValue);
}
-
-// Create the information transform configuration objects
-$primitiveTransformation = (new PrimitiveTransformation())
- ->setCryptoReplaceFfxFpeConfig($cryptoReplaceFfxFpeConfig);
-
-$infoTypeTransformation = (new InfoTypeTransformation())
- ->setPrimitiveTransformation($primitiveTransformation)
- ->setInfoTypes($infoTypes);
-
-$infoTypeTransformations = (new InfoTypeTransformations())
- ->setTransformations([$infoTypeTransformation]);
-
-// Create the deidentification configuration object
-$deidentifyConfig = (new DeidentifyConfig())
- ->setInfoTypeTransformations($infoTypeTransformations);
-
-$content = (new ContentItem())
- ->setValue($string);
-
-$parent = "projects/$callingProjectId/locations/global";
-
-// Run request
-$response = $dlp->deidentifyContent([
- 'parent' => $parent,
- 'deidentifyConfig' => $deidentifyConfig,
- 'item' => $content
-]);
-
-// Print the results
-$deidentifiedValue = $response->getItem()->getValue();
-print($deidentifiedValue);
# [END dlp_deidentify_fpe]
+
+// 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/deidentify_mask.php b/dlp/src/deidentify_mask.php
index 7796599505..d38cf8d77d 100644
--- a/dlp/src/deidentify_mask.php
+++ b/dlp/src/deidentify_mask.php
@@ -22,20 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 3 || count($argv) > 5) {
- return print("Usage: php deidentify_mask.php CALLING_PROJECT STRING [NUMBER_TO_MASK] [MASKING_CHARACTER]\n");
-}
-list($_, $callingProjectId, $string) = $argv;
-$numberToMask = isset($argv[3]) ? $argv[3] : 0;
-$maskingCharacter = isset($argv[4]) ? $argv[4] : 'x';
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_deidentify_masking]
-/**
- * Deidentify sensitive data in a string by masking it with a character.
- */
use Google\Cloud\Dlp\V2\CharacterMaskConfig;
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
@@ -45,53 +34,66 @@
use Google\Cloud\Dlp\V2\InfoTypeTransformations;
use Google\Cloud\Dlp\V2\ContentItem;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The GCP Project ID to run the API call under';
-// $string = 'The string to deidentify';
-// $numberToMask = 0; // (Optional) The maximum number of sensitive characters to mask in a match
-// $maskingCharacter = 'x'; // (Optional) The character to mask matching sensitive data with
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-
-// The infoTypes of information to mask
-$ssnInfoType = (new InfoType())
- ->setName('US_SOCIAL_SECURITY_NUMBER');
-$infoTypes = [$ssnInfoType];
-
-// Create the masking configuration object
-$maskConfig = (new CharacterMaskConfig())
- ->setMaskingCharacter($maskingCharacter)
- ->setNumberToMask($numberToMask);
-
-// Create the information transform configuration objects
-$primitiveTransformation = (new PrimitiveTransformation())
- ->setCharacterMaskConfig($maskConfig);
-
-$infoTypeTransformation = (new InfoTypeTransformation())
- ->setPrimitiveTransformation($primitiveTransformation)
- ->setInfoTypes($infoTypes);
-
-$infoTypeTransformations = (new InfoTypeTransformations())
- ->setTransformations([$infoTypeTransformation]);
-
-// Create the deidentification configuration object
-$deidentifyConfig = (new DeidentifyConfig())
- ->setInfoTypeTransformations($infoTypeTransformations);
-
-$item = (new ContentItem())
- ->setValue($string);
-
-$parent = "projects/$callingProjectId/locations/global";
-
-// Run request
-$response = $dlp->deidentifyContent([
- 'parent' => $parent,
- 'deidentifyConfig' => $deidentifyConfig,
- 'item' => $item
-]);
-
-// Print the results
-$deidentifiedValue = $response->getItem()->getValue();
-print($deidentifiedValue);
+/**
+ * Deidentify sensitive data in a string by masking it with a character.
+ *
+ * @param string $callingProjectId The GCP Project ID to run the API call under
+ * @param string $string The string to deidentify
+ * @param int $numberToMask (Optional) The maximum number of sensitive characters to mask in a match
+ * @param string $maskingCharacter (Optional) The character to mask matching sensitive data with (defaults to "x")
+ */
+function deidentify_mask(
+ string $callingProjectId,
+ string $string,
+ int $numberToMask = 0,
+ string $maskingCharacter = 'x'
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // The infoTypes of information to mask
+ $ssnInfoType = (new InfoType())
+ ->setName('US_SOCIAL_SECURITY_NUMBER');
+ $infoTypes = [$ssnInfoType];
+
+ // Create the masking configuration object
+ $maskConfig = (new CharacterMaskConfig())
+ ->setMaskingCharacter($maskingCharacter)
+ ->setNumberToMask($numberToMask);
+
+ // Create the information transform configuration objects
+ $primitiveTransformation = (new PrimitiveTransformation())
+ ->setCharacterMaskConfig($maskConfig);
+
+ $infoTypeTransformation = (new InfoTypeTransformation())
+ ->setPrimitiveTransformation($primitiveTransformation)
+ ->setInfoTypes($infoTypes);
+
+ $infoTypeTransformations = (new InfoTypeTransformations())
+ ->setTransformations([$infoTypeTransformation]);
+
+ // Create the deidentification configuration object
+ $deidentifyConfig = (new DeidentifyConfig())
+ ->setInfoTypeTransformations($infoTypeTransformations);
+
+ $item = (new ContentItem())
+ ->setValue($string);
+
+ $parent = "projects/$callingProjectId/locations/global";
+
+ // Run request
+ $response = $dlp->deidentifyContent([
+ 'parent' => $parent,
+ 'deidentifyConfig' => $deidentifyConfig,
+ 'item' => $item
+ ]);
+
+ // Print the results
+ $deidentifiedValue = $response->getItem()->getValue();
+ print($deidentifiedValue);
+}
# [END dlp_deidentify_masking]
+
+// 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/delete_inspect_template.php b/dlp/src/delete_inspect_template.php
index fe68a16cef..b3fcaa6d1e 100644
--- a/dlp/src/delete_inspect_template.php
+++ b/dlp/src/delete_inspect_template.php
@@ -22,31 +22,33 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 3) {
- return print("Usage: php delete_inspect_template.php CALLING_PROJECT TEMPLATE\n");
-}
-list($_, $callingProjectId, $templateId) = $argv;
+namespace Google\Cloud\Samples\Dlp;
// [START dlp_delete_inspect_template]
+use Google\Cloud\Dlp\V2\DlpServiceClient;
+
/**
* Delete a DLP inspection configuration template.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $templateId The name of the template to delete
*/
-use Google\Cloud\Dlp\V2\DlpServiceClient;
-
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $templateId = 'The name of the template to delete';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-
-// Run template deletion request
-$templateName = "projects/$callingProjectId/locations/global/inspectTemplates/$templateId";
-$dlp->deleteInspectTemplate($templateName);
-
-// Print results
-printf('Successfully deleted template %s' . PHP_EOL, $templateName);
+function delete_inspect_template(
+ string $callingProjectId,
+ string $templateId
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // Run template deletion request
+ $templateName = "projects/$callingProjectId/locations/global/inspectTemplates/$templateId";
+ $dlp->deleteInspectTemplate($templateName);
+
+ // Print results
+ printf('Successfully deleted template %s' . PHP_EOL, $templateName);
+}
// [END dlp_delete_inspect_template]
+
+// 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/delete_job.php b/dlp/src/delete_job.php
index 6b9adf0474..9503558c00 100644
--- a/dlp/src/delete_job.php
+++ b/dlp/src/delete_job.php
@@ -22,30 +22,30 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 2) {
- return print("Usage: php delete_job.php JOB_ID\n");
-}
-list($_, $jobId) = $argv;
+namespace Google\Cloud\Samples\Dlp;
// [START dlp_delete_job]
+use Google\Cloud\Dlp\V2\DlpServiceClient;
+
/**
* Delete results of a Data Loss Prevention API job
+ *
+ * @param string $jobId The name of the job whose results should be deleted
*/
-use Google\Cloud\Dlp\V2\DlpServiceClient;
-
-/** Uncomment and populate these variables in your code */
-// $jobId = 'The name of the job whose results should be deleted';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
+function delete_job(string $jobId): void
+{
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
-// Run job-deletion request
-// The Parent project ID is automatically extracted from this parameter
-$dlp->deleteDlpJob($jobId);
+ // Run job-deletion request
+ // The Parent project ID is automatically extracted from this parameter
+ $dlp->deleteDlpJob($jobId);
-// Print status
-printf('Successfully deleted job %s' . PHP_EOL, $jobId);
+ // Print status
+ printf('Successfully deleted job %s' . PHP_EOL, $jobId);
+}
// [END dlp_delete_job]
+
+// 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/delete_trigger.php b/dlp/src/delete_trigger.php
index 07afcf4e03..ad7c643695 100644
--- a/dlp/src/delete_trigger.php
+++ b/dlp/src/delete_trigger.php
@@ -22,32 +22,32 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 3) {
- return print("Usage: php delete_trigger.php CALLING_PROJECT_ID TRIGGER_ID\n");
-}
-list($_, $callingProjectId, $triggerId) = $argv;
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_delete_trigger]
+use Google\Cloud\Dlp\V2\DlpServiceClient;
+
/**
* Delete a Data Loss Prevention API job trigger.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $triggerId The name of the trigger to be deleted.
*/
-use Google\Cloud\Dlp\V2\DlpServiceClient;
-
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $triggerId = 'The name of the trigger to be deleted.';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-
-// Run request
-// The Parent project ID is automatically extracted from this parameter
-$triggerName = "projects/$callingProjectId/locations/global/jobTriggers/$triggerId";
-$response = $dlp->deleteJobTrigger($triggerName);
-
-// Print the results
-printf('Successfully deleted trigger %s' . PHP_EOL, $triggerName);
+function delete_trigger(string $callingProjectId, string $triggerId): void
+{
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // Run request
+ // The Parent project ID is automatically extracted from this parameter
+ $triggerName = "projects/$callingProjectId/locations/global/jobTriggers/$triggerId";
+ $response = $dlp->deleteJobTrigger($triggerName);
+
+ // Print the results
+ printf('Successfully deleted trigger %s' . PHP_EOL, $triggerName);
+}
# [END dlp_delete_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/inspect_bigquery.php b/dlp/src/inspect_bigquery.php
index f48ccb1ac6..6bd13fd4c3 100644
--- a/dlp/src/inspect_bigquery.php
+++ b/dlp/src/inspect_bigquery.php
@@ -22,19 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 7 || count($argv) > 8) {
- return print("Usage: php inspect_bigquery.php CALLING_PROJECT DATA_PROJECT TOPIC SUBSCRIPTION DATASET TABLE [MAX_FINDINGS]\n");
-}
-list($_, $callingProjectId, $dataProjectId, $topicId, $subscriptionId, $datasetId, $tableId) = $argv;
-$maxFindings = isset($argv[7]) ? (int) $argv[7] : 0;
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_inspect_bigquery]
-/**
- * Inspect a BigQuery table , using Pub/Sub for job status notifications.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\BigQueryOptions;
use Google\Cloud\Dlp\V2\InfoType;
@@ -49,124 +39,139 @@
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\PubSub\PubSubClient;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $dataProjectId = 'The project ID containing the target Datastore';
-// $topicId = 'The name of the Pub/Sub topic to notify once the job completes';
-// $subscriptionId = 'The name of the Pub/Sub subscription to use when listening for job';
-// $datasetId = 'The ID of the dataset to inspect';
-// $tableId = 'The ID of the table to inspect';
-// $columnName = 'The name of the column to compute risk metrics for, e.g. "age"';
-// $maxFindings = 0; // (Optional) The maximum number of findings to report per request (0 = server maximum)
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-$pubsub = new PubSubClient();
-$topic = $pubsub->topic($topicId);
-
-// The infoTypes of information to match
-$personNameInfoType = (new InfoType())
- ->setName('PERSON_NAME');
-$creditCardNumberInfoType = (new InfoType())
- ->setName('CREDIT_CARD_NUMBER');
-$infoTypes = [$personNameInfoType, $creditCardNumberInfoType];
-
-// The minimum likelihood required before returning a match
-$minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
-
-// Specify finding limits
-$limits = (new FindingLimits())
- ->setMaxFindingsPerRequest($maxFindings);
-
-// Construct items to be inspected
-$bigqueryTable = (new BigQueryTable())
- ->setProjectId($dataProjectId)
- ->setDatasetId($datasetId)
- ->setTableId($tableId);
-
-$bigQueryOptions = (new BigQueryOptions())
- ->setTableReference($bigqueryTable);
-
-$storageConfig = (new StorageConfig())
- ->setBigQueryOptions($bigQueryOptions);
-
-// Construct the inspect config object
-$inspectConfig = (new InspectConfig())
- ->setMinLikelihood($minLikelihood)
- ->setLimits($limits)
- ->setInfoTypes($infoTypes);
-
-// Construct the action to run when job completes
-$pubSubAction = (new PublishToPubSub())
- ->setTopic($topic->name());
-
-$action = (new Action())
- ->setPubSub($pubSubAction);
-
-// 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) {
- print('No findings.' . PHP_EOL);
- } else {
- foreach ($infoTypeStats as $infoTypeStat) {
- printf(
- ' Found %s instance(s) of infoType %s' . PHP_EOL,
- $infoTypeStat->getCount(),
- $infoTypeStat->getInfoType()->getName()
- );
+/**
+ * Inspect a BigQuery table , using Pub/Sub for job status notifications.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $dataProjectId The project ID containing the target Datastore
+ * @param string $topicId The name of the Pub/Sub topic to notify once the job completes
+ * @param string $subscriptionId The name of the Pub/Sub subscription to use when listening for job
+ * @param string $datasetId The ID of the dataset to inspect
+ * @param string $tableId The ID of the table to inspect
+ * @param int $maxFindings (Optional) The maximum number of findings to report per request (0 = server maximum)
+ */
+function inspect_bigquery(
+ string $callingProjectId,
+ string $dataProjectId,
+ string $topicId,
+ string $subscriptionId,
+ string $datasetId,
+ string $tableId,
+ int $maxFindings = 0
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+ $pubsub = new PubSubClient();
+ $topic = $pubsub->topic($topicId);
+
+ // The infoTypes of information to match
+ $personNameInfoType = (new InfoType())
+ ->setName('PERSON_NAME');
+ $creditCardNumberInfoType = (new InfoType())
+ ->setName('CREDIT_CARD_NUMBER');
+ $infoTypes = [$personNameInfoType, $creditCardNumberInfoType];
+
+ // The minimum likelihood required before returning a match
+ $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
+
+ // Specify finding limits
+ $limits = (new FindingLimits())
+ ->setMaxFindingsPerRequest($maxFindings);
+
+ // Construct items to be inspected
+ $bigqueryTable = (new BigQueryTable())
+ ->setProjectId($dataProjectId)
+ ->setDatasetId($datasetId)
+ ->setTableId($tableId);
+
+ $bigQueryOptions = (new BigQueryOptions())
+ ->setTableReference($bigqueryTable);
+
+ $storageConfig = (new StorageConfig())
+ ->setBigQueryOptions($bigQueryOptions);
+
+ // Construct the inspect config object
+ $inspectConfig = (new InspectConfig())
+ ->setMinLikelihood($minLikelihood)
+ ->setLimits($limits)
+ ->setInfoTypes($infoTypes);
+
+ // Construct the action to run when job completes
+ $pubSubAction = (new PublishToPubSub())
+ ->setTopic($topic->name());
+
+ $action = (new Action())
+ ->setPubSub($pubSubAction);
+
+ // 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
}
}
- 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.');
+ 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) {
+ print('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]
+
+// 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.php b/dlp/src/inspect_datastore.php
index 0375e8b867..970ba07df7 100644
--- a/dlp/src/inspect_datastore.php
+++ b/dlp/src/inspect_datastore.php
@@ -22,19 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 7 || count($argv) > 8) {
- return print("Usage: php inspect_datastore.php CALLING_PROJECT DATA_PROJECT TOPIC SUBSCRIPTION KIND NAMESPACE [MAX_FINDINGS]\n");
-}
-list($_, $callingProjectId, $dataProjectId, $topicId, $subscriptionId, $kind, $namespaceId) = $argv;
-$maxFindings = isset($argv[7]) ? (int) $argv[7] : 0;
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_inspect_datastore]
-/**
- * Inspect Datastore, using Pub/Sub for job status notifications.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\DatastoreOptions;
use Google\Cloud\Dlp\V2\InfoType;
@@ -50,123 +40,139 @@
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\PubSub\PubSubClient;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $dataProjectId = 'The project ID containing the target Datastore';
-// $topicId = 'The name of the Pub/Sub topic to notify once the job completes';
-// $subscriptionId = 'The name of the Pub/Sub subscription to use when listening for job';
-// $kind = 'The datastore kind to inspect';
-// $namespaceId = 'The ID namespace of the Datastore document to inspect';
-// $maxFindings = 0; // (Optional) The maximum number of findings to report per request (0 = server maximum)
-
-// Instantiate clients
-$dlp = new DlpServiceClient();
-$pubsub = new PubSubClient();
-$topic = $pubsub->topic($topicId);
-
-// The infoTypes of information to match
-$personNameInfoType = (new InfoType())
- ->setName('PERSON_NAME');
-$phoneNumberInfoType = (new InfoType())
- ->setName('PHONE_NUMBER');
-$infoTypes = [$personNameInfoType, $phoneNumberInfoType];
-
-// The minimum likelihood required before returning a match
-$minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
-
-// Specify finding limits
-$limits = (new FindingLimits())
- ->setMaxFindingsPerRequest($maxFindings);
-
-// Construct items to be inspected
-$partitionId = (new PartitionId())
- ->setProjectId($dataProjectId)
- ->setNamespaceId($namespaceId);
-
-$kindExpression = (new KindExpression())
- ->setName($kind);
-
-$datastoreOptions = (new DatastoreOptions())
- ->setPartitionId($partitionId)
- ->setKind($kindExpression);
-
-// Construct the inspect config object
-$inspectConfig = (new InspectConfig())
- ->setInfoTypes($infoTypes)
- ->setMinLikelihood($minLikelihood)
- ->setLimits($limits);
-
-// Construct the storage config object
-$storageConfig = (new StorageConfig())
- ->setDatastoreOptions($datastoreOptions);
-
-// Construct the action to run when job completes
-$pubSubAction = (new PublishToPubSub())
- ->setTopic($topic->name());
-
-$action = (new Action())
- ->setPubSub($pubSubAction);
-
-// 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) {
- print('No findings.' . PHP_EOL);
- } else {
- foreach ($infoTypeStats as $infoTypeStat) {
- printf(' Found %s instance(s) of infoType %s' . PHP_EOL, $infoTypeStat->getCount(), $infoTypeStat->getInfoType()->getName());
+/**
+ * Inspect Datastore, using Pub/Sub for job status notifications.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $dataProjectId The project ID containing the target Datastore
+ * @param string $topicId The name of the Pub/Sub topic to notify once the job completes
+ * @param string $subscriptionId The name of the Pub/Sub subscription to use when listening for job
+ * @param string $kind The datastore kind to inspect
+ * @param string $namespaceId The ID namespace of the Datastore document to inspect
+ * @param int $maxFindings (Optional) The maximum number of findings to report per request (0 = server maximum)
+ */
+function inspect_datastore(
+ string $callingProjectId,
+ string $dataProjectId,
+ string $topicId,
+ string $subscriptionId,
+ string $kind,
+ string $namespaceId,
+ int $maxFindings = 0
+): void {
+ // Instantiate clients
+ $dlp = new DlpServiceClient();
+ $pubsub = new PubSubClient();
+ $topic = $pubsub->topic($topicId);
+
+ // The infoTypes of information to match
+ $personNameInfoType = (new InfoType())
+ ->setName('PERSON_NAME');
+ $phoneNumberInfoType = (new InfoType())
+ ->setName('PHONE_NUMBER');
+ $infoTypes = [$personNameInfoType, $phoneNumberInfoType];
+
+ // The minimum likelihood required before returning a match
+ $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
+
+ // Specify finding limits
+ $limits = (new FindingLimits())
+ ->setMaxFindingsPerRequest($maxFindings);
+
+ // Construct items to be inspected
+ $partitionId = (new PartitionId())
+ ->setProjectId($dataProjectId)
+ ->setNamespaceId($namespaceId);
+
+ $kindExpression = (new KindExpression())
+ ->setName($kind);
+
+ $datastoreOptions = (new DatastoreOptions())
+ ->setPartitionId($partitionId)
+ ->setKind($kindExpression);
+
+ // Construct the inspect config object
+ $inspectConfig = (new InspectConfig())
+ ->setInfoTypes($infoTypes)
+ ->setMinLikelihood($minLikelihood)
+ ->setLimits($limits);
+
+ // Construct the storage config object
+ $storageConfig = (new StorageConfig())
+ ->setDatastoreOptions($datastoreOptions);
+
+ // Construct the action to run when job completes
+ $pubSubAction = (new PublishToPubSub())
+ ->setTopic($topic->name());
+
+ $action = (new Action())
+ ->setPubSub($pubSubAction);
+
+ // 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
}
}
- 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:
- print('Unexpected job state.');
+ 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) {
+ print('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:
+ print('Unexpected job state.');
+ }
}
# [END dlp_inspect_datastore]
+
+// 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 ba97f7e788..82526a2fc3 100644
--- a/dlp/src/inspect_gcs.php
+++ b/dlp/src/inspect_gcs.php
@@ -22,19 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 6 || count($argv) > 7) {
- return print("Usage: php inspect_datastore.php CALLING_PROJECT TOPIC SUBSCRIPTION BUCKET FILE [MAX_FINDINGS]\n");
-}
-list($_, $callingProjectId, $topicId, $subscriptionId, $bucketId, $file) = $argv;
-$maxFindings = isset($argv[6]) ? (int) $argv[6] : 0;
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_inspect_gcs]
-/**
- * Inspect a file stored on Google Cloud Storage , using Pub/Sub for job status notifications.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\CloudStorageOptions;
use Google\Cloud\Dlp\V2\CloudStorageOptions\FileSet;
@@ -49,120 +39,135 @@
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\PubSub\PubSubClient;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $topicId = 'The name of the Pub/Sub topic to notify once the job completes';
-// $subscriptionId = 'The name of the Pub/Sub subscription to use when listening for job';
-// $bucketId = 'The name of the bucket where the file resides';
-// $file = 'The path to the file within the bucket to inspect. Can contain wildcards e.g. "my-image.*"';
-// $maxFindings = 0; // (Optional) The maximum number of findings to report per request (0 = server maximum)
-
-// Instantiate a client.
-$dlp = new DlpServiceClient([
- 'projectId' => $callingProjectId,
-]);
-$pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
-]);
-$topic = $pubsub->topic($topicId);
-
-// The infoTypes of information to match
-$personNameInfoType = (new InfoType())
- ->setName('PERSON_NAME');
-$creditCardNumberInfoType = (new InfoType())
- ->setName('CREDIT_CARD_NUMBER');
-$infoTypes = [$personNameInfoType, $creditCardNumberInfoType];
-
-// The minimum likelihood required before returning a match
-$minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
-
-// Specify finding limits
-$limits = (new FindingLimits())
- ->setMaxFindingsPerRequest($maxFindings);
-
-// Construct items to be inspected
-$fileSet = (new FileSet())
- ->setUrl('gs://' . $bucketId . '/' . $file);
-
-$cloudStorageOptions = (new CloudStorageOptions())
- ->setFileSet($fileSet);
-
-$storageConfig = (new StorageConfig())
- ->setCloudStorageOptions($cloudStorageOptions);
-
-// Construct the inspect config object
-$inspectConfig = (new InspectConfig())
- ->setMinLikelihood($minLikelihood)
- ->setLimits($limits)
- ->setInfoTypes($infoTypes);
-
-// Construct the action to run when job completes
-$pubSubAction = (new PublishToPubSub())
- ->setTopic($topic->name());
-
-$action = (new Action())
- ->setPubSub($pubSubAction);
-
-// 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) {
- print('No findings.' . PHP_EOL);
- } else {
- foreach ($infoTypeStats as $infoTypeStat) {
- printf(' Found %s instance(s) of infoType %s' . PHP_EOL, $infoTypeStat->getCount(), $infoTypeStat->getInfoType()->getName());
+/**
+ * Inspect a file stored on Google Cloud Storage , using Pub/Sub for job status notifications.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $topicId The name of the Pub/Sub topic to notify once the job completes
+ * @param string $subscriptionId The name of the Pub/Sub subscription to use when listening for job
+ * @param string $bucketId The name of the bucket where the file resides
+ * @param string $file The path to the file within the bucket to inspect. Can contain wildcards e.g. "my-image.*"
+ * @param int $maxFindings (Optional) The maximum number of findings to report per request (0 = server maximum)
+ */
+function inspect_gcs(
+ string $callingProjectId,
+ string $topicId,
+ string $subscriptionId,
+ string $bucketId,
+ string $file,
+ int $maxFindings = 0
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $pubsub = new PubSubClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $topic = $pubsub->topic($topicId);
+
+ // The infoTypes of information to match
+ $personNameInfoType = (new InfoType())
+ ->setName('PERSON_NAME');
+ $creditCardNumberInfoType = (new InfoType())
+ ->setName('CREDIT_CARD_NUMBER');
+ $infoTypes = [$personNameInfoType, $creditCardNumberInfoType];
+
+ // The minimum likelihood required before returning a match
+ $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
+
+ // Specify finding limits
+ $limits = (new FindingLimits())
+ ->setMaxFindingsPerRequest($maxFindings);
+
+ // Construct items to be inspected
+ $fileSet = (new FileSet())
+ ->setUrl('gs://' . $bucketId . '/' . $file);
+
+ $cloudStorageOptions = (new CloudStorageOptions())
+ ->setFileSet($fileSet);
+
+ $storageConfig = (new StorageConfig())
+ ->setCloudStorageOptions($cloudStorageOptions);
+
+ // Construct the inspect config object
+ $inspectConfig = (new InspectConfig())
+ ->setMinLikelihood($minLikelihood)
+ ->setLimits($limits)
+ ->setInfoTypes($infoTypes);
+
+ // Construct the action to run when job completes
+ $pubSubAction = (new PublishToPubSub())
+ ->setTopic($topic->name());
+
+ $action = (new Action())
+ ->setPubSub($pubSubAction);
+
+ // 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
}
}
- 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:
- print('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ 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) {
+ print('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:
+ print('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
}
# [END dlp_inspect_gcs]
+
+// 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_image_file.php b/dlp/src/inspect_image_file.php
index 699068126f..2bd11910c8 100644
--- a/dlp/src/inspect_image_file.php
+++ b/dlp/src/inspect_image_file.php
@@ -21,13 +21,7 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/bigquery/api/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 3) {
- return printf("Usage: php %s PROJECT_ID FILEPATH\n", __FILE__);
-}
-list($_, $projectId, $filepath) = $argv;
+namespace Google\Cloud\Samples\Dlp;
// [START dlp_inspect_image_file]
use Google\Cloud\Dlp\V2\DlpServiceClient;
@@ -38,50 +32,57 @@
use Google\Cloud\Dlp\V2\ByteContentItem\BytesType;
use Google\Cloud\Dlp\V2\Likelihood;
-/** Uncomment and populate these variables in your code */
-// $projectId = 'YOUR_PROJECT_ID';
-// $filepath = 'path/to/image.png';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
+/**
+ * @param string $projectId
+ * @param string $filepath
+ */
+function inspect_image_file(string $projectId, string $filepath): void
+{
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
-// Get the bytes of the file
-$fileBytes = (new ByteContentItem())
- ->setType(BytesType::IMAGE_PNG)
- ->setData(file_get_contents($filepath));
+ // Get the bytes of the file
+ $fileBytes = (new ByteContentItem())
+ ->setType(BytesType::IMAGE_PNG)
+ ->setData(file_get_contents($filepath));
-// Construct request
-$parent = "projects/$projectId/locations/global";
-$item = (new ContentItem())
- ->setByteItem($fileBytes);
-$inspectConfig = (new InspectConfig())
- // The infoTypes of information to match
- ->setInfoTypes([
- (new InfoType())->setName('PHONE_NUMBER'),
- (new InfoType())->setName('EMAIL_ADDRESS'),
- (new InfoType())->setName('CREDIT_CARD_NUMBER')
- ])
- // Whether to include the matching string
- ->setIncludeQuote(true);
+ // Construct request
+ $parent = "projects/$projectId/locations/global";
+ $item = (new ContentItem())
+ ->setByteItem($fileBytes);
+ $inspectConfig = (new InspectConfig())
+ // The infoTypes of information to match
+ ->setInfoTypes([
+ (new InfoType())->setName('PHONE_NUMBER'),
+ (new InfoType())->setName('EMAIL_ADDRESS'),
+ (new InfoType())->setName('CREDIT_CARD_NUMBER')
+ ])
+ // Whether to include the matching string
+ ->setIncludeQuote(true);
-// Run request
-$response = $dlp->inspectContent([
- 'parent' => $parent,
- 'inspectConfig' => $inspectConfig,
- 'item' => $item
-]);
+ // Run request
+ $response = $dlp->inspectContent([
+ 'parent' => $parent,
+ 'inspectConfig' => $inspectConfig,
+ 'item' => $item
+ ]);
-// Print the results
-$findings = $response->getResult()->getFindings();
-if (count($findings) == 0) {
- print('No findings.' . PHP_EOL);
-} else {
- print('Findings:' . PHP_EOL);
- foreach ($findings as $finding) {
- print(' Quote: ' . $finding->getQuote() . PHP_EOL);
- print(' Info type: ' . $finding->getInfoType()->getName() . PHP_EOL);
- $likelihoodString = Likelihood::name($finding->getLikelihood());
- print(' Likelihood: ' . $likelihoodString . PHP_EOL);
+ // Print the results
+ $findings = $response->getResult()->getFindings();
+ if (count($findings) == 0) {
+ print('No findings.' . PHP_EOL);
+ } else {
+ print('Findings:' . PHP_EOL);
+ foreach ($findings as $finding) {
+ print(' Quote: ' . $finding->getQuote() . PHP_EOL);
+ print(' Info type: ' . $finding->getInfoType()->getName() . PHP_EOL);
+ $likelihoodString = Likelihood::name($finding->getLikelihood());
+ print(' Likelihood: ' . $likelihoodString . PHP_EOL);
+ }
}
}
// [END dlp_inspect_image_file]
+
+// 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_string.php b/dlp/src/inspect_string.php
index 18a110d130..b7f8e1ac70 100644
--- a/dlp/src/inspect_string.php
+++ b/dlp/src/inspect_string.php
@@ -21,13 +21,7 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/bigquery/api/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 3) {
- return printf("Usage: php %s PROJECT_ID STRING\n", __FILE__);
-}
-list($_, $projectId, $textToInspect) = $argv;
+namespace Google\Cloud\Samples\Dlp;
// [START dlp_inspect_string]
use Google\Cloud\Dlp\V2\DlpServiceClient;
@@ -36,45 +30,52 @@
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\Likelihood;
-/** Uncomment and populate these variables in your code */
-// $projectId = 'YOUR_PROJECT_ID';
-// $textToInspect = 'My name is Gary and my email is gary@example.com';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
+/**
+ * @param string $projectId
+ * @param string $textToInspect
+ */
+function inspect_string(string $projectId, string $textToInspect): void
+{
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
-// Construct request
-$parent = "projects/$projectId/locations/global";
-$item = (new ContentItem())
- ->setValue($textToInspect);
-$inspectConfig = (new InspectConfig())
- // The infoTypes of information to match
- ->setInfoTypes([
- (new InfoType())->setName('PHONE_NUMBER'),
- (new InfoType())->setName('EMAIL_ADDRESS'),
- (new InfoType())->setName('CREDIT_CARD_NUMBER')
- ])
- // Whether to include the matching string
- ->setIncludeQuote(true);
+ // Construct request
+ $parent = "projects/$projectId/locations/global";
+ $item = (new ContentItem())
+ ->setValue($textToInspect);
+ $inspectConfig = (new InspectConfig())
+ // The infoTypes of information to match
+ ->setInfoTypes([
+ (new InfoType())->setName('PHONE_NUMBER'),
+ (new InfoType())->setName('EMAIL_ADDRESS'),
+ (new InfoType())->setName('CREDIT_CARD_NUMBER')
+ ])
+ // Whether to include the matching string
+ ->setIncludeQuote(true);
-// Run request
-$response = $dlp->inspectContent([
- 'parent' => $parent,
- 'inspectConfig' => $inspectConfig,
- 'item' => $item
-]);
+ // Run request
+ $response = $dlp->inspectContent([
+ 'parent' => $parent,
+ 'inspectConfig' => $inspectConfig,
+ 'item' => $item
+ ]);
-// Print the results
-$findings = $response->getResult()->getFindings();
-if (count($findings) == 0) {
- print('No findings.' . PHP_EOL);
-} else {
- print('Findings:' . PHP_EOL);
- foreach ($findings as $finding) {
- print(' Quote: ' . $finding->getQuote() . PHP_EOL);
- print(' Info type: ' . $finding->getInfoType()->getName() . PHP_EOL);
- $likelihoodString = Likelihood::name($finding->getLikelihood());
- print(' Likelihood: ' . $likelihoodString . PHP_EOL);
+ // Print the results
+ $findings = $response->getResult()->getFindings();
+ if (count($findings) == 0) {
+ print('No findings.' . PHP_EOL);
+ } else {
+ print('Findings:' . PHP_EOL);
+ foreach ($findings as $finding) {
+ print(' Quote: ' . $finding->getQuote() . PHP_EOL);
+ print(' Info type: ' . $finding->getInfoType()->getName() . PHP_EOL);
+ $likelihoodString = Likelihood::name($finding->getLikelihood());
+ print(' Likelihood: ' . $likelihoodString . PHP_EOL);
+ }
}
}
// [END dlp_inspect_string]
+
+// 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_text_file.php b/dlp/src/inspect_text_file.php
index 0845a40673..c6fa091594 100644
--- a/dlp/src/inspect_text_file.php
+++ b/dlp/src/inspect_text_file.php
@@ -21,13 +21,7 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/bigquery/api/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 3) {
- return printf("Usage: php %s PROJECT_ID FILEPATH\n", __FILE__);
-}
-list($_, $projectId, $filepath) = $argv;
+namespace Google\Cloud\Samples\Dlp;
// [START dlp_inspect_text_file]
use Google\Cloud\Dlp\V2\DlpServiceClient;
@@ -38,50 +32,57 @@
use Google\Cloud\Dlp\V2\ByteContentItem\BytesType;
use Google\Cloud\Dlp\V2\Likelihood;
-/** Uncomment and populate these variables in your code */
-// $projectId = 'YOUR_PROJECT_ID';
-// $filepath = 'path/to/image.png';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
+/**
+ * @param string $projectId
+ * @param string $filepath
+ */
+function inspect_text_file(string $projectId, string $filepath): void
+{
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
-// Get the bytes of the file
-$fileBytes = (new ByteContentItem())
- ->setType(BytesType::TEXT_UTF8)
- ->setData(file_get_contents($filepath));
+ // Get the bytes of the file
+ $fileBytes = (new ByteContentItem())
+ ->setType(BytesType::TEXT_UTF8)
+ ->setData(file_get_contents($filepath));
-// Construct request
-$parent = "projects/$projectId/locations/global";
-$item = (new ContentItem())
- ->setByteItem($fileBytes);
-$inspectConfig = (new InspectConfig())
- // The infoTypes of information to match
- ->setInfoTypes([
- (new InfoType())->setName('PHONE_NUMBER'),
- (new InfoType())->setName('EMAIL_ADDRESS'),
- (new InfoType())->setName('CREDIT_CARD_NUMBER')
- ])
- // Whether to include the matching string
- ->setIncludeQuote(true);
+ // Construct request
+ $parent = "projects/$projectId/locations/global";
+ $item = (new ContentItem())
+ ->setByteItem($fileBytes);
+ $inspectConfig = (new InspectConfig())
+ // The infoTypes of information to match
+ ->setInfoTypes([
+ (new InfoType())->setName('PHONE_NUMBER'),
+ (new InfoType())->setName('EMAIL_ADDRESS'),
+ (new InfoType())->setName('CREDIT_CARD_NUMBER')
+ ])
+ // Whether to include the matching string
+ ->setIncludeQuote(true);
-// Run request
-$response = $dlp->inspectContent([
- 'parent' => $parent,
- 'inspectConfig' => $inspectConfig,
- 'item' => $item
-]);
+ // Run request
+ $response = $dlp->inspectContent([
+ 'parent' => $parent,
+ 'inspectConfig' => $inspectConfig,
+ 'item' => $item
+ ]);
-// Print the results
-$findings = $response->getResult()->getFindings();
-if (count($findings) == 0) {
- print('No findings.' . PHP_EOL);
-} else {
- print('Findings:' . PHP_EOL);
- foreach ($findings as $finding) {
- print(' Quote: ' . $finding->getQuote() . PHP_EOL);
- print(' Info type: ' . $finding->getInfoType()->getName() . PHP_EOL);
- $likelihoodString = Likelihood::name($finding->getLikelihood());
- print(' Likelihood: ' . $likelihoodString . PHP_EOL);
+ // Print the results
+ $findings = $response->getResult()->getFindings();
+ if (count($findings) == 0) {
+ print('No findings.' . PHP_EOL);
+ } else {
+ print('Findings:' . PHP_EOL);
+ foreach ($findings as $finding) {
+ print(' Quote: ' . $finding->getQuote() . PHP_EOL);
+ print(' Info type: ' . $finding->getInfoType()->getName() . PHP_EOL);
+ $likelihoodString = Likelihood::name($finding->getLikelihood());
+ print(' Likelihood: ' . $likelihoodString . PHP_EOL);
+ }
}
}
// [END dlp_inspect_text_file]
+
+// 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.php b/dlp/src/k_anonymity.php
index 6d1cde854e..7068dd321d 100644
--- a/dlp/src/k_anonymity.php
+++ b/dlp/src/k_anonymity.php
@@ -22,18 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 8) {
- return print("Usage: php k_anonymity.php CALLING_PROJECT DATA_PROJECT TOPIC SUBSCRIPTION DATASET TABLE QUASI_ID_NAMES\n");
-}
-list($_, $callingProjectId, $dataProjectId, $topicId, $subscriptionId, $datasetId, $tableId, $quasiIdNames) = $argv;
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_k_anomymity]
-/**
- * Computes the k-anonymity of a column set in a Google BigQuery table.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\RiskAnalysisJobConfig;
use Google\Cloud\Dlp\V2\BigQueryTable;
@@ -45,128 +36,144 @@
use Google\Cloud\Dlp\V2\FieldId;
use Google\Cloud\PubSub\PubSubClient;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $dataProjectId = 'The project ID containing the target Datastore';
-// $topicId = 'The name of the Pub/Sub topic to notify once the job completes';
-// $subscriptionId = 'The name of the Pub/Sub subscription to use when listening for job';
-// $datasetId = 'The ID of the dataset to inspect';
-// $tableId = 'The ID of the table to inspect';
-// $quasiIdNames = 'Comma-separated list of columns that form a composite key (quasi-identifiers)';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient([
- 'projectId' => $callingProjectId,
-]);
-$pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
-]);
-$topic = $pubsub->topic($topicId);
-
-// Construct risk analysis config
-$quasiIds = array_map(
- function ($id) {
- return (new FieldId())->setName($id);
- },
- explode(',', $quasiIdNames)
-);
-
-$statsConfig = (new KAnonymityConfig())
- ->setQuasiIds($quasiIds);
-
-$privacyMetric = (new PrivacyMetric())
- ->setKAnonymityConfig($statsConfig);
-
-// Construct items to be analyzed
-$bigqueryTable = (new BigQueryTable())
- ->setProjectId($dataProjectId)
- ->setDatasetId($datasetId)
- ->setTableId($tableId);
-
-// Construct the action to run when job completes
-$pubSubAction = (new PublishToPubSub())
- ->setTopic($topic->name());
-
-$action = (new Action())
- ->setPubSub($pubSubAction);
-
-// Construct risk analysis job config to run
-$riskJob = (new RiskAnalysisJobConfig())
- ->setPrivacyMetric($privacyMetric)
- ->setSourceTable($bigqueryTable)
- ->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, [
- 'riskJob' => $riskJob
-]);
-
-// 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
+/**
+ * Computes the k-anonymity of a column set in a Google BigQuery table.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $dataProjectId The project ID containing the target Datastore
+ * @param string $topicId The name of the Pub/Sub topic to notify once the job completes
+ * @param string $subscriptionId The name of the Pub/Sub subscription to use when listening for job
+ * @param string $datasetId The ID of the dataset to inspect
+ * @param string $tableId The ID of the table to inspect
+ * @param string[] $quasiIdNames Array columns that form a composite key (quasi-identifiers)
+ */
+function k_anonymity(
+ string $callingProjectId,
+ string $dataProjectId,
+ string $topicId,
+ string $subscriptionId,
+ string $datasetId,
+ string $tableId,
+ array $quasiIdNames
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $pubsub = new PubSubClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $topic = $pubsub->topic($topicId);
+
+ // Construct risk analysis config
+ $quasiIds = array_map(
+ function ($id) {
+ return (new FieldId())->setName($id);
+ },
+ $quasiIdNames
+ );
+
+ $statsConfig = (new KAnonymityConfig())
+ ->setQuasiIds($quasiIds);
+
+ $privacyMetric = (new PrivacyMetric())
+ ->setKAnonymityConfig($statsConfig);
+
+ // Construct items to be analyzed
+ $bigqueryTable = (new BigQueryTable())
+ ->setProjectId($dataProjectId)
+ ->setDatasetId($datasetId)
+ ->setTableId($tableId);
+
+ // Construct the action to run when job completes
+ $pubSubAction = (new PublishToPubSub())
+ ->setTopic($topic->name());
+
+ $action = (new Action())
+ ->setPubSub($pubSubAction);
+
+ // Construct risk analysis job config to run
+ $riskJob = (new RiskAnalysisJobConfig())
+ ->setPrivacyMetric($privacyMetric)
+ ->setSourceTable($bigqueryTable)
+ ->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, [
+ 'riskJob' => $riskJob
+ ]);
+
+ // 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:
- $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
- print(' Quasi-ID values:' . PHP_EOL);
- foreach ($valueBucket->getQuasiIdsValues() as $index => $value) {
- print(' ' . $value->serializeToJsonString() . PHP_EOL);
- }
+ 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:
+ $histBuckets = $job->getRiskDetails()->getKAnonymityResult()->getEquivalenceClassHistogramBuckets();
+
+ foreach ($histBuckets as $bucketIndex => $histBucket) {
+ // Print bucket stats
+ printf('Bucket %s:' . PHP_EOL, $bucketIndex);
printf(
- ' Class size: %s' . PHP_EOL,
- $valueBucket->getEquivalenceClassSize()
+ ' 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
+ print(' 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.');
+ 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_anomymity]
+
+// 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_map.php b/dlp/src/k_map.php
index 726eae4b02..01889add68 100644
--- a/dlp/src/k_map.php
+++ b/dlp/src/k_map.php
@@ -22,22 +22,10 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 10) {
- return print("Usage: php k_map.php CALLING_PROJECT DATA_PROJECT TOPIC SUBSCRIPTION DATASET TABLE REGION_CODE QUASI_ID_NAMES INFO_TYPES\n");
-}
-list($_, $callingProjectId, $dataProjectId, $topicId, $subscriptionId, $datasetId, $tableId, $regionCode, $quasiIdNames, $infoTypes) = $argv;
-
-// Convert comma-separated lists to arrays
-$quasiIdNames = explode(',', $quasiIdNames);
-$infoTypes = explode(',', $infoTypes);
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_k_map]
-/**
- * Computes the k-map risk estimation of a column set in a Google BigQuery table.
- */
+use Exception;
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\RiskAnalysisJobConfig;
@@ -51,145 +39,163 @@
use Google\Cloud\Dlp\V2\FieldId;
use Google\Cloud\PubSub\PubSubClient;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $dataProjectId = 'The project ID containing the target Datastore';
-// $topicId = 'The name of the Pub/Sub topic to notify once the job completes';
-// $subscriptionId = 'The name of the Pub/Sub subscription to use when listening for job';
-// $datasetId = 'The ID of the dataset to inspect';
-// $tableId = 'The ID of the table to inspect';
-// $regionCode = 'The ISO 3166-1 region code that the data is representative of';
-// $quasiIdNames = ['array columns that form a composite key (quasi-identifiers)'];
-// $infoTypes = ['array of infoTypes corresponding to the chosen quasi-identifiers'];
-
-// Instantiate a client.
-$dlp = new DlpServiceClient([
- 'projectId' => $callingProjectId,
-]);
-$pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
-]);
-$topic = $pubsub->topic($topicId);
-
-// Verify input
-if (count($infoTypes) != count($quasiIdNames)) {
- throw new Exception('Number of infoTypes and number of quasi-identifiers must be equal!');
-}
+/**
+ * Computes the k-map risk estimation of a column set in a Google BigQuery table.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $dataProjectId The project ID containing the target Datastore
+ * @param string $topicId The name of the Pub/Sub topic to notify once the job completes
+ * @param string $subscriptionId The name of the Pub/Sub subscription to use when listening for job
+ * @param string $datasetId The ID of the dataset to inspect
+ * @param string $tableId The ID of the table to inspect
+ * @param string $regionCode The ISO 3166-1 region code that the data is representative of
+ * @param string[] $quasiIdNames Array columns that form a composite key (quasi-identifiers)
+ * @param string[] $infoTypes Array of infoTypes corresponding to the chosen quasi-identifiers
+ */
+function k_map(
+ string $callingProjectId,
+ string $dataProjectId,
+ string $topicId,
+ string $subscriptionId,
+ string $datasetId,
+ string $tableId,
+ string $regionCode,
+ array $quasiIdNames,
+ array $infoTypes
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $pubsub = new PubSubClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $topic = $pubsub->topic($topicId);
+
+ // Verify input
+ if (count($infoTypes) != count($quasiIdNames)) {
+ throw new Exception('Number of infoTypes and number of quasi-identifiers must be equal!');
+ }
-// Map infoTypes to quasi-ids
-$quasiIdObjects = array_map(function ($quasiId, $infoType) {
- $quasiIdField = (new FieldId())
- ->setName($quasiId);
-
- $quasiIdType = (new InfoType())
- ->setName($infoType);
-
- $quasiIdObject = (new TaggedField())
- ->setInfoType($quasiIdType)
- ->setField($quasiIdField);
-
- return $quasiIdObject;
-}, $quasiIdNames, $infoTypes);
-
-// Construct analysis config
-$statsConfig = (new KMapEstimationConfig())
- ->setQuasiIds($quasiIdObjects)
- ->setRegionCode($regionCode);
-
-$privacyMetric = (new PrivacyMetric())
- ->setKMapEstimationConfig($statsConfig);
-
-// Construct items to be analyzed
-$bigqueryTable = (new BigQueryTable())
- ->setProjectId($dataProjectId)
- ->setDatasetId($datasetId)
- ->setTableId($tableId);
-
-// Construct the action to run when job completes
-$pubSubAction = (new PublishToPubSub())
- ->setTopic($topic->name());
-
-$action = (new Action())
- ->setPubSub($pubSubAction);
-
-// Construct risk analysis job config to run
-$riskJob = (new RiskAnalysisJobConfig())
- ->setPrivacyMetric($privacyMetric)
- ->setSourceTable($bigqueryTable)
- ->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, [
- 'riskJob' => $riskJob
-]);
-
-// 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
+ // Map infoTypes to quasi-ids
+ $quasiIdObjects = array_map(function ($quasiId, $infoType) {
+ $quasiIdField = (new FieldId())
+ ->setName($quasiId);
+
+ $quasiIdType = (new InfoType())
+ ->setName($infoType);
+
+ $quasiIdObject = (new TaggedField())
+ ->setInfoType($quasiIdType)
+ ->setField($quasiIdField);
+
+ return $quasiIdObject;
+ }, $quasiIdNames, $infoTypes);
+
+ // Construct analysis config
+ $statsConfig = (new KMapEstimationConfig())
+ ->setQuasiIds($quasiIdObjects)
+ ->setRegionCode($regionCode);
+
+ $privacyMetric = (new PrivacyMetric())
+ ->setKMapEstimationConfig($statsConfig);
+
+ // Construct items to be analyzed
+ $bigqueryTable = (new BigQueryTable())
+ ->setProjectId($dataProjectId)
+ ->setDatasetId($datasetId)
+ ->setTableId($tableId);
+
+ // Construct the action to run when job completes
+ $pubSubAction = (new PublishToPubSub())
+ ->setTopic($topic->name());
+
+ $action = (new Action())
+ ->setPubSub($pubSubAction);
+
+ // Construct risk analysis job config to run
+ $riskJob = (new RiskAnalysisJobConfig())
+ ->setPrivacyMetric($privacyMetric)
+ ->setSourceTable($bigqueryTable)
+ ->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, [
+ 'riskJob' => $riskJob
+ ]);
+
+ // 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:
- $histBuckets = $job->getRiskDetails()->getKMapEstimationResult()->getKMapEstimationHistogram();
-
- foreach ($histBuckets as $bucketIndex => $histBucket) {
- // Print bucket stats
- printf('Bucket %s:' . PHP_EOL, $bucketIndex);
- printf(
- ' Anonymity range: [%s, %s]' . PHP_EOL,
- $histBucket->getMinAnonymity(),
- $histBucket->getMaxAnonymity()
- );
- printf(' Size: %s' . PHP_EOL, $histBucket->getBucketSize());
-
- // Print bucket values
- foreach ($histBucket->getBucketValues() as $percent => $valueBucket) {
+ 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:
+ $histBuckets = $job->getRiskDetails()->getKMapEstimationResult()->getKMapEstimationHistogram();
+
+ foreach ($histBuckets as $bucketIndex => $histBucket) {
+ // Print bucket stats
+ printf('Bucket %s:' . PHP_EOL, $bucketIndex);
printf(
- ' Estimated k-map anonymity: %s' . PHP_EOL,
- $valueBucket->getEstimatedAnonymity()
+ ' Anonymity range: [%s, %s]' . PHP_EOL,
+ $histBucket->getMinAnonymity(),
+ $histBucket->getMaxAnonymity()
);
-
- // Pretty-print quasi-ID values
- print(' Values: ' . PHP_EOL);
- foreach ($valueBucket->getQuasiIdsValues() as $index => $value) {
- print(' ' . $value->serializeToJsonString() . PHP_EOL);
+ printf(' Size: %s' . PHP_EOL, $histBucket->getBucketSize());
+
+ // Print bucket values
+ foreach ($histBucket->getBucketValues() as $percent => $valueBucket) {
+ printf(
+ ' Estimated k-map anonymity: %s' . PHP_EOL,
+ $valueBucket->getEstimatedAnonymity()
+ );
+
+ // Pretty-print quasi-ID values
+ print(' Values: ' . PHP_EOL);
+ foreach ($valueBucket->getQuasiIdsValues() as $index => $value) {
+ print(' ' . $value->serializeToJsonString() . PHP_EOL);
+ }
}
}
- }
- 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:
- print('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ 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:
+ print('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
}
# [END dlp_k_map]
+
+// 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/l_diversity.php b/dlp/src/l_diversity.php
index 127428862e..26b95a3e32 100644
--- a/dlp/src/l_diversity.php
+++ b/dlp/src/l_diversity.php
@@ -22,21 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 9) {
- return print("Usage: php l_diversity.php CALLING_PROJECT DATA_PROJECT TOPIC SUBSCRIPTION DATASET TABLE SENSITIVE_ATTRIBUTE QUASI_ID_NAMES\n");
-}
-list($_, $callingProjectId, $dataProjectId, $topicId, $subscriptionId, $datasetId, $tableId, $sensitiveAttribute, $quasiIdNames) = $argv;
-
-// Convert comma-separated list to arrays
-$quasiIdNames = explode(',', $quasiIdNames);
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_l_diversity]
-/**
- * Computes the l-diversity of a column set in a Google BigQuery table.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\RiskAnalysisJobConfig;
use Google\Cloud\Dlp\V2\BigQueryTable;
@@ -48,143 +36,160 @@
use Google\Cloud\Dlp\V2\FieldId;
use Google\Cloud\PubSub\PubSubClient;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $dataProjectId = 'The project ID containing the target Datastore';
-// $topicId = 'The name of the Pub/Sub topic to notify once the job completes';
-// $subscriptionId = 'The name of the Pub/Sub subscription to use when listening for job';
-// $datasetId = 'The ID of the dataset to inspect';
-// $tableId = 'The ID of the table to inspect';
-// $sensitiveAttribute = 'The column to measure l-diversity relative to, e.g. "firstName"';
-// $quasiIdNames = ['array columns that form a composite key (quasi-identifiers)'];
-
-// Instantiate a client.
-$dlp = new DlpServiceClient([
- 'projectId' => $callingProjectId,
-]);
-$pubsub = new PubSubClient([
- 'projectId' => $callingProjectId,
-]);
-$topic = $pubsub->topic($topicId);
-
-// Construct risk analysis config
-$quasiIds = array_map(
- function ($id) {
- return (new FieldId())->setName($id);
- },
- $quasiIdNames
-);
-
-$sensitiveField = (new FieldId())
- ->setName($sensitiveAttribute);
-
-$statsConfig = (new LDiversityConfig())
- ->setQuasiIds($quasiIds)
- ->setSensitiveAttribute($sensitiveField);
-
-$privacyMetric = (new PrivacyMetric())
- ->setLDiversityConfig($statsConfig);
-
-// Construct items to be analyzed
-$bigqueryTable = (new BigQueryTable())
- ->setProjectId($dataProjectId)
- ->setDatasetId($datasetId)
- ->setTableId($tableId);
-
-// Construct the action to run when job completes
-$pubSubAction = (new PublishToPubSub())
- ->setTopic($topic->name());
-
-$action = (new Action())
- ->setPubSub($pubSubAction);
-
-// Construct risk analysis job config to run
-$riskJob = (new RiskAnalysisJobConfig())
- ->setPrivacyMetric($privacyMetric)
- ->setSourceTable($bigqueryTable)
- ->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, [
- 'riskJob' => $riskJob
-]);
-
-// 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
+/**
+ * Computes the l-diversity of a column set in a Google BigQuery table.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $dataProjectId The project ID containing the target Datastore
+ * @param string $topicId The name of the Pub/Sub topic to notify once the job completes
+ * @param string $subscriptionId The name of the Pub/Sub subscription to use when listening for job
+ * @param string $datasetId The ID of the dataset to inspect
+ * @param string $tableId The ID of the table to inspect
+ * @param string $sensitiveAttribute The column to measure l-diversity relative to, e.g. "firstName"
+ * @param string[] $quasiIdNames Array columns that form a composite key (quasi-identifiers)
+ */
+function l_diversity(
+ string $callingProjectId,
+ string $dataProjectId,
+ string $topicId,
+ string $subscriptionId,
+ string $datasetId,
+ string $tableId,
+ string $sensitiveAttribute,
+ array $quasiIdNames
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $pubsub = new PubSubClient([
+ 'projectId' => $callingProjectId,
+ ]);
+ $topic = $pubsub->topic($topicId);
+
+ // Construct risk analysis config
+ $quasiIds = array_map(
+ function ($id) {
+ return (new FieldId())->setName($id);
+ },
+ $quasiIdNames
+ );
+
+ $sensitiveField = (new FieldId())
+ ->setName($sensitiveAttribute);
+
+ $statsConfig = (new LDiversityConfig())
+ ->setQuasiIds($quasiIds)
+ ->setSensitiveAttribute($sensitiveField);
+
+ $privacyMetric = (new PrivacyMetric())
+ ->setLDiversityConfig($statsConfig);
+
+ // Construct items to be analyzed
+ $bigqueryTable = (new BigQueryTable())
+ ->setProjectId($dataProjectId)
+ ->setDatasetId($datasetId)
+ ->setTableId($tableId);
+
+ // Construct the action to run when job completes
+ $pubSubAction = (new PublishToPubSub())
+ ->setTopic($topic->name());
+
+ $action = (new Action())
+ ->setPubSub($pubSubAction);
+
+ // Construct risk analysis job config to run
+ $riskJob = (new RiskAnalysisJobConfig())
+ ->setPrivacyMetric($privacyMetric)
+ ->setSourceTable($bigqueryTable)
+ ->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, [
+ 'riskJob' => $riskJob
+ ]);
+
+ // 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:
- $histBuckets = $job->getRiskDetails()->getLDiversityResult()->getSensitiveValueFrequencyHistogramBuckets();
-
- foreach ($histBuckets as $bucketIndex => $histBucket) {
- // Print bucket stats
- printf('Bucket %s:' . PHP_EOL, $bucketIndex);
- printf(
- ' Bucket size range: [%s, %s]' . PHP_EOL,
- $histBucket->getSensitiveValueFrequencyLowerBound(),
- $histBucket->getSensitiveValueFrequencyUpperBound()
- );
-
- // Print bucket values
- foreach ($histBucket->getBucketValues() as $percent => $valueBucket) {
+ 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:
+ $histBuckets = $job->getRiskDetails()->getLDiversityResult()->getSensitiveValueFrequencyHistogramBuckets();
+
+ foreach ($histBuckets as $bucketIndex => $histBucket) {
+ // Print bucket stats
+ printf('Bucket %s:' . PHP_EOL, $bucketIndex);
printf(
- ' Class size: %s' . PHP_EOL,
- $valueBucket->getEquivalenceClassSize()
+ ' Bucket size range: [%s, %s]' . PHP_EOL,
+ $histBucket->getSensitiveValueFrequencyLowerBound(),
+ $histBucket->getSensitiveValueFrequencyUpperBound()
);
- // Pretty-print quasi-ID values
- print(' Quasi-ID values:' . PHP_EOL);
- foreach ($valueBucket->getQuasiIdsValues() as $index => $value) {
- print(' ' . $value->serializeToJsonString() . PHP_EOL);
- }
-
- // Pretty-print sensitive values
- $topValues = $valueBucket->getTopSensitiveValues();
- foreach ($topValues as $topValue) {
+ // Print bucket values
+ foreach ($histBucket->getBucketValues() as $percent => $valueBucket) {
printf(
- ' Sensitive value %s occurs %s time(s).' . PHP_EOL,
- $topValue->getValue()->serializeToJsonString(),
- $topValue->getCount()
+ ' Class size: %s' . PHP_EOL,
+ $valueBucket->getEquivalenceClassSize()
);
+
+ // Pretty-print quasi-ID values
+ print(' Quasi-ID values:' . PHP_EOL);
+ foreach ($valueBucket->getQuasiIdsValues() as $index => $value) {
+ print(' ' . $value->serializeToJsonString() . PHP_EOL);
+ }
+
+ // Pretty-print sensitive values
+ $topValues = $valueBucket->getTopSensitiveValues();
+ foreach ($topValues as $topValue) {
+ printf(
+ ' Sensitive value %s occurs %s time(s).' . PHP_EOL,
+ $topValue->getValue()->serializeToJsonString(),
+ $topValue->getCount()
+ );
+ }
}
}
- }
- 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.');
+ 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_l_diversity]
+
+// 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/list_info_types.php b/dlp/src/list_info_types.php
index a378a7f39a..e08bd7b143 100644
--- a/dlp/src/list_info_types.php
+++ b/dlp/src/list_info_types.php
@@ -22,41 +22,40 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) > 3) {
- return print("Usage: php list_info_types.php [FILTER] [LANGUAGE_CODE]\n");
-}
-$filter = isset($argv[1]) ? $argv[1] : '';
-$languageCode = isset($argv[2]) ? $argv[2] : '';
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_list_info_types]
+use Google\Cloud\Dlp\V2\DlpServiceClient;
+
/**
* Lists all Info Types for the Data Loss Prevention (DLP) API.
+ *
+ * @param string $filter (Optional) filter to use
+ * @param string $languageCode (Optional) language code, empty for 'en-US'
*/
-use Google\Cloud\Dlp\V2\DlpServiceClient;
-
-/** Uncomment and populate these variables in your code */
-// $filter = ''; // (Optional) filter to use, empty for ''.
-// $languageCode = ''; // (Optional) language code, empty for 'en-US'.
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-
-// Run request
-$response = $dlp->listInfoTypes([
- 'languageCode' => $languageCode,
- 'filter' => $filter
-]);
-
-// Print the results
-print('Info Types:' . PHP_EOL);
-foreach ($response->getInfoTypes() as $infoType) {
- printf(
- ' %s (%s)' . PHP_EOL,
- $infoType->getDisplayName(),
- $infoType->getName()
- );
+function list_info_types(string $filter = '', string $languageCode = ''): void
+{
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // Run request
+ $response = $dlp->listInfoTypes([
+ 'languageCode' => $languageCode,
+ 'filter' => $filter
+ ]);
+
+ // Print the results
+ print('Info Types:' . PHP_EOL);
+ foreach ($response->getInfoTypes() as $infoType) {
+ printf(
+ ' %s (%s)' . PHP_EOL,
+ $infoType->getDisplayName(),
+ $infoType->getName()
+ );
+ }
}
# [END dlp_list_info_types]
+
+// 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/list_inspect_templates.php b/dlp/src/list_inspect_templates.php
index dfc9d6936e..b791963bee 100644
--- a/dlp/src/list_inspect_templates.php
+++ b/dlp/src/list_inspect_templates.php
@@ -22,49 +22,49 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 2) {
- return print("Usage: php list_inspect_templates.php CALLING_PROJECT\n");
-}
-list($_, $callingProjectId) = $argv;
+namespace Google\Cloud\Samples\Dlp;
// [START dlp_list_inspect_templates]
+use Google\Cloud\Dlp\V2\DlpServiceClient;
+
/**
* List DLP inspection configuration templates.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
*/
-use Google\Cloud\Dlp\V2\DlpServiceClient;
-
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
+function list_inspect_templates(string $callingProjectId): void
+{
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
-// Instantiate a client.
-$dlp = new DlpServiceClient();
+ $parent = "projects/$callingProjectId/locations/global";
-$parent = "projects/$callingProjectId/locations/global";
+ // Run request
+ $response = $dlp->listInspectTemplates($parent);
-// Run request
-$response = $dlp->listInspectTemplates($parent);
+ // Print results
+ $templates = $response->iterateAllElements();
-// Print results
-$templates = $response->iterateAllElements();
+ foreach ($templates as $template) {
+ printf('Template %s' . PHP_EOL, $template->getName());
+ printf(' Created: %s' . PHP_EOL, $template->getCreateTime()->getSeconds());
+ printf(' Updated: %s' . PHP_EOL, $template->getUpdateTime()->getSeconds());
+ printf(' Display Name: %s' . PHP_EOL, $template->getDisplayName());
+ printf(' Description: %s' . PHP_EOL, $template->getDescription());
-foreach ($templates as $template) {
- printf('Template %s' . PHP_EOL, $template->getName());
- printf(' Created: %s' . PHP_EOL, $template->getCreateTime()->getSeconds());
- printf(' Updated: %s' . PHP_EOL, $template->getUpdateTime()->getSeconds());
- printf(' Display Name: %s' . PHP_EOL, $template->getDisplayName());
- printf(' Description: %s' . PHP_EOL, $template->getDescription());
-
- $inspectConfig = $template->getInspectConfig();
- if ($inspectConfig === null) {
- print(' No inspect config.' . PHP_EOL);
- } else {
- printf(' Minimum likelihood: %s' . PHP_EOL, $inspectConfig->getMinLikelihood());
- printf(' Include quotes: %s' . PHP_EOL, $inspectConfig->getIncludeQuote());
- $limits = $inspectConfig->getLimits();
- printf(' Max findings per request: %s' . PHP_EOL, $limits->getMaxFindingsPerRequest());
+ $inspectConfig = $template->getInspectConfig();
+ if ($inspectConfig === null) {
+ print(' No inspect config.' . PHP_EOL);
+ } else {
+ printf(' Minimum likelihood: %s' . PHP_EOL, $inspectConfig->getMinLikelihood());
+ printf(' Include quotes: %s' . PHP_EOL, $inspectConfig->getIncludeQuote());
+ $limits = $inspectConfig->getLimits();
+ printf(' Max findings per request: %s' . PHP_EOL, $limits->getMaxFindingsPerRequest());
+ }
}
}
// [END dlp_list_inspect_templates]
+
+// 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/list_jobs.php b/dlp/src/list_jobs.php
index 273e5b0a8e..61ed9a41c9 100644
--- a/dlp/src/list_jobs.php
+++ b/dlp/src/list_jobs.php
@@ -22,60 +22,59 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 2 || count($argv) > 3) {
- return print("Usage: php list_jobs.php CALLING_PROJECT [FILTER]\n");
-}
-list($_, $callingProjectId) = $argv;
-$filter = isset($argv[2]) ? $argv[2] : '';
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_list_jobs]
-/**
- * List Data Loss Prevention API jobs corresponding to a given filter.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\DlpJob\JobState;
use Google\Cloud\Dlp\V2\DlpJobType;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $filter = 'The filter expression to use';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
+/**
+ * List Data Loss Prevention API jobs corresponding to a given filter.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $filter The filter expression to use
+ */
+function list_jobs(string $callingProjectId, string $filter): void
+{
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
-// The type of job to list (either 'INSPECT_JOB' or 'REDACT_JOB')
-$jobType = DlpJobType::INSPECT_JOB;
+ // The type of job to list (either 'INSPECT_JOB' or 'REDACT_JOB')
+ $jobType = DlpJobType::INSPECT_JOB;
-// Run job-listing request
-// For more information and filter syntax,
-// @see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
-$parent = "projects/$callingProjectId/locations/global";
-$response = $dlp->listDlpJobs($parent, [
- 'filter' => $filter,
- 'type' => $jobType
-]);
+ // Run job-listing request
+ // For more information and filter syntax,
+ // @see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
+ $parent = "projects/$callingProjectId/locations/global";
+ $response = $dlp->listDlpJobs($parent, [
+ 'filter' => $filter,
+ 'type' => $jobType
+ ]);
-// Print job list
-$jobs = $response->iterateAllElements();
-foreach ($jobs as $job) {
- printf('Job %s status: %s' . PHP_EOL, $job->getName(), $job->getState());
- $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
+ // Print job list
+ $jobs = $response->iterateAllElements();
+ foreach ($jobs as $job) {
+ printf('Job %s status: %s' . PHP_EOL, $job->getName(), $job->getState());
+ $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
- if ($job->getState() == JobState::DONE) {
- if (count($infoTypeStats) > 0) {
- foreach ($infoTypeStats as $infoTypeStat) {
- printf(
- ' Found %s instance(s) of type %s' . PHP_EOL,
- $infoTypeStat->getCount(),
- $infoTypeStat->getInfoType()->getName()
- );
+ if ($job->getState() == JobState::DONE) {
+ if (count($infoTypeStats) > 0) {
+ foreach ($infoTypeStats as $infoTypeStat) {
+ printf(
+ ' Found %s instance(s) of type %s' . PHP_EOL,
+ $infoTypeStat->getCount(),
+ $infoTypeStat->getInfoType()->getName()
+ );
+ }
+ } else {
+ print(' No findings.' . PHP_EOL);
}
- } else {
- print(' No findings.' . PHP_EOL);
}
}
}
# [END dlp_list_jobs]
+
+// 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/list_triggers.php b/dlp/src/list_triggers.php
index 304103f32f..5c42a731b6 100644
--- a/dlp/src/list_triggers.php
+++ b/dlp/src/list_triggers.php
@@ -22,43 +22,43 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 2) {
- return print("Usage: php list_triggers.php CALLING_PROJECT\n");
-}
-list($_, $callingProjectId) = $argv;
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_list_triggers]
+use Google\Cloud\Dlp\V2\DlpServiceClient;
+
/**
* List Data Loss Prevention API job triggers.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
*/
-use Google\Cloud\Dlp\V2\DlpServiceClient;
-
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
+function list_triggers(string $callingProjectId): void
+{
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
-// Instantiate a client.
-$dlp = new DlpServiceClient();
+ $parent = "projects/$callingProjectId/locations/global";
-$parent = "projects/$callingProjectId/locations/global";
+ // Run request
+ $response = $dlp->listJobTriggers($parent);
-// Run request
-$response = $dlp->listJobTriggers($parent);
-
-// Print results
-$triggers = $response->iterateAllElements();
-foreach ($triggers as $trigger) {
- printf('Trigger %s' . PHP_EOL, $trigger->getName());
- printf(' Created: %s' . PHP_EOL, $trigger->getCreateTime()->getSeconds());
- printf(' Updated: %s' . PHP_EOL, $trigger->getUpdateTime()->getSeconds());
- printf(' Display Name: %s' . PHP_EOL, $trigger->getDisplayName());
- printf(' Description: %s' . PHP_EOL, $trigger->getDescription());
- printf(' Status: %s' . PHP_EOL, $trigger->getStatus());
- printf(' Error count: %s' . PHP_EOL, count($trigger->getErrors()));
- $timespanConfig = $trigger->getInspectJob()->getStorageConfig()->getTimespanConfig();
- printf(' Auto-populates timespan config: %s' . PHP_EOL,
- ($timespanConfig && $timespanConfig->getEnableAutoPopulationOfTimespanConfig() ? 'yes' : 'no'));
+ // Print results
+ $triggers = $response->iterateAllElements();
+ foreach ($triggers as $trigger) {
+ printf('Trigger %s' . PHP_EOL, $trigger->getName());
+ printf(' Created: %s' . PHP_EOL, $trigger->getCreateTime()->getSeconds());
+ printf(' Updated: %s' . PHP_EOL, $trigger->getUpdateTime()->getSeconds());
+ printf(' Display Name: %s' . PHP_EOL, $trigger->getDisplayName());
+ printf(' Description: %s' . PHP_EOL, $trigger->getDescription());
+ printf(' Status: %s' . PHP_EOL, $trigger->getStatus());
+ printf(' Error count: %s' . PHP_EOL, count($trigger->getErrors()));
+ $timespanConfig = $trigger->getInspectJob()->getStorageConfig()->getTimespanConfig();
+ printf(' Auto-populates timespan config: %s' . PHP_EOL,
+ ($timespanConfig && $timespanConfig->getEnableAutoPopulationOfTimespanConfig() ? 'yes' : 'no'));
+ }
}
# [END dlp_list_triggers]
+
+// 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/numerical_stats.php b/dlp/src/numerical_stats.php
index 4e83840cf4..7468fce951 100644
--- a/dlp/src/numerical_stats.php
+++ b/dlp/src/numerical_stats.php
@@ -22,18 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 8) {
- return print("Usage: php numerical_stats.php CALLING_PROJECT DATA_PROJECT TOPIC SUBSCRIPTION DATASET TABLE COLUMN\n");
-}
-list($_, $callingProjectId, $dataProjectId, $topicId, $subscriptionId, $datasetId, $tableId, $columnName) = $argv;
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_numerical_stats]
-/**
- * Computes risk metrics of a column of numbers in a Google BigQuery table.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\RiskAnalysisJobConfig;
use Google\Cloud\Dlp\V2\BigQueryTable;
@@ -45,122 +36,138 @@
use Google\Cloud\Dlp\V2\PrivacyMetric;
use Google\Cloud\Dlp\V2\FieldId;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $dataProjectId = 'The project ID containing the target Datastore';
-// $topicId = 'The name of the Pub/Sub topic to notify once the job completes';
-// $subscriptionId = 'The name of the Pub/Sub subscription to use when listening for job';
-// $datasetId = 'The ID of the BigQuery dataset to inspect';
-// $tableId = 'The ID of the BigQuery table to inspect';
-// $columnName = 'The name of the column to compute risk metrics for, e.g. "age"';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient([
- 'projectId' => $callingProjectId
-]);
-$pubsub = new PubSubClient([
- 'projectId' => $callingProjectId
-]);
-$topic = $pubsub->topic($topicId);
-
-// Construct risk analysis config
-$columnField = (new FieldId())
- ->setName($columnName);
-
-$statsConfig = (new NumericalStatsConfig())
- ->setField($columnField);
-
-$privacyMetric = (new PrivacyMetric())
- ->setNumericalStatsConfig($statsConfig);
-
-// Construct items to be analyzed
-$bigqueryTable = (new BigQueryTable())
- ->setProjectId($dataProjectId)
- ->setDatasetId($datasetId)
- ->setTableId($tableId);
-
-// Construct the action to run when job completes
-$pubSubAction = (new PublishToPubSub())
- ->setTopic($topic->name());
-
-$action = (new Action())
- ->setPubSub($pubSubAction);
-
-// Construct risk analysis job config to run
-$riskJob = (new RiskAnalysisJobConfig())
- ->setPrivacyMetric($privacyMetric)
- ->setSourceTable($bigqueryTable)
- ->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, [
- 'riskJob' => $riskJob
-]);
-
-// 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
-
-// Helper function to convert Protobuf values to strings
-$valueToString = function ($value) {
- $json = json_decode($value->serializeToJsonString(), true);
- return array_shift($json);
-};
-
-// Print finding counts
-printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
-switch ($job->getState()) {
- case JobState::DONE:
- $results = $job->getRiskDetails()->getNumericalStatsResult();
- printf(
- 'Value range: [%s, %s]' . PHP_EOL,
- $valueToString($results->getMinValue()),
- $valueToString($results->getMaxValue())
- );
-
- // Only print unique values
- $lastValue = null;
- foreach ($results->getQuantileValues() as $percent => $quantileValue) {
- $value = $valueToString($quantileValue);
- if ($value != $lastValue) {
- printf('Value at %s quantile: %s' . PHP_EOL, $percent, $value);
- $lastValue = $value;
+/**
+ * Computes risk metrics of a column of numbers in a Google BigQuery table.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $dataProjectId The project ID containing the target Datastore
+ * @param string $topicId The name of the Pub/Sub topic to notify once the job completes
+ * @param string $subscriptionId The name of the Pub/Sub subscription to use when listening for job
+ * @param string $datasetId The ID of the BigQuery dataset to inspect
+ * @param string $tableId The ID of the BigQuery table to inspect
+ * @param string $columnName The name of the column to compute risk metrics for, e.g. "age"
+ */
+function numerical_stats(
+ string $callingProjectId,
+ string $dataProjectId,
+ string $topicId,
+ string $subscriptionId,
+ string $datasetId,
+ string $tableId,
+ string $columnName
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient([
+ 'projectId' => $callingProjectId
+ ]);
+ $pubsub = new PubSubClient([
+ 'projectId' => $callingProjectId
+ ]);
+ $topic = $pubsub->topic($topicId);
+
+ // Construct risk analysis config
+ $columnField = (new FieldId())
+ ->setName($columnName);
+
+ $statsConfig = (new NumericalStatsConfig())
+ ->setField($columnField);
+
+ $privacyMetric = (new PrivacyMetric())
+ ->setNumericalStatsConfig($statsConfig);
+
+ // Construct items to be analyzed
+ $bigqueryTable = (new BigQueryTable())
+ ->setProjectId($dataProjectId)
+ ->setDatasetId($datasetId)
+ ->setTableId($tableId);
+
+ // Construct the action to run when job completes
+ $pubSubAction = (new PublishToPubSub())
+ ->setTopic($topic->name());
+
+ $action = (new Action())
+ ->setPubSub($pubSubAction);
+
+ // Construct risk analysis job config to run
+ $riskJob = (new RiskAnalysisJobConfig())
+ ->setPrivacyMetric($privacyMetric)
+ ->setSourceTable($bigqueryTable)
+ ->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, [
+ 'riskJob' => $riskJob
+ ]);
+
+ // 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
+
+ // Helper function to convert Protobuf values to strings
+ $valueToString = function ($value) {
+ $json = json_decode($value->serializeToJsonString(), true);
+ return array_shift($json);
+ };
+
+ // Print finding counts
+ printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
+ switch ($job->getState()) {
+ case JobState::DONE:
+ $results = $job->getRiskDetails()->getNumericalStatsResult();
+ printf(
+ 'Value range: [%s, %s]' . PHP_EOL,
+ $valueToString($results->getMinValue()),
+ $valueToString($results->getMaxValue())
+ );
+
+ // Only print unique values
+ $lastValue = null;
+ foreach ($results->getQuantileValues() as $percent => $quantileValue) {
+ $value = $valueToString($quantileValue);
+ if ($value != $lastValue) {
+ printf('Value at %s quantile: %s' . PHP_EOL, $percent, $value);
+ $lastValue = $value;
+ }
+ }
- 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:
- print('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ 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:
+ print('Unexpected job state. Most likely, the job is either running or has not yet started.');
+ }
}
# [END dlp_numerical_stats]
+
+// 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/redact_image.php b/dlp/src/redact_image.php
index ecc923ace8..88c80e07bc 100644
--- a/dlp/src/redact_image.php
+++ b/dlp/src/redact_image.php
@@ -22,18 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) != 4) {
- return print("Usage: php redact_image.php CALLING_PROJECT IMAGE_PATH OUTPUT_PATH\n");
-}
-list($_, $callingProjectId, $imagePath, $outputPath) = $argv;
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_redact_image]
-/**
- * Redact sensitive data from an image.
- */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
@@ -41,67 +32,79 @@
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\ByteContentItem;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The project ID to run the API call under';
-// $imagePath = 'The local filepath of the image to inspect';
-// $outputPath = 'The local filepath to save the resulting image to';
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-
-// The infoTypes of information to match
-$phoneNumberInfoType = (new InfoType())
- ->setName('PHONE_NUMBER');
-$infoTypes = [$phoneNumberInfoType];
-
-// The minimum likelihood required before returning a match
-$minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
-
-// Whether to include the matching string in the response
-$includeQuote = true;
-
-// Create the configuration object
-$inspectConfig = (new InspectConfig())
- ->setMinLikelihood($minLikelihood)
- ->setInfoTypes($infoTypes);
-
-// Read image file into a buffer
-$imageRef = fopen($imagePath, 'rb');
-$imageBytes = fread($imageRef, filesize($imagePath));
-fclose($imageRef);
-
-// Get the image's content type
-$typeConstant = (int) array_search(
- mime_content_type($imagePath),
- [false, 'image/jpeg', 'image/bmp', 'image/png', 'image/svg']
-);
-
-// Create the byte-storing object
-$byteContent = (new ByteContentItem())
- ->setType($typeConstant)
- ->setData($imageBytes);
-
-// Create the image redaction config objects
-$imageRedactionConfigs = [];
-foreach ($infoTypes as $infoType) {
- $config = (new ImageRedactionConfig())
- ->setInfoType($infoType);
- $imageRedactionConfigs[] = $config;
+/**
+ * Redact sensitive data from an image.
+ *
+ * @param string $callingProjectId The project ID to run the API call under
+ * @param string $imagePath The local filepath of the image to inspect
+ * @param string $outputPath The local filepath to save the resulting image to
+ */
+function redact_image(
+ string $callingProjectId,
+ string $imagePath,
+ string $outputPath
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // The infoTypes of information to match
+ $phoneNumberInfoType = (new InfoType())
+ ->setName('PHONE_NUMBER');
+ $infoTypes = [$phoneNumberInfoType];
+
+ // The minimum likelihood required before returning a match
+ $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;
+
+ // Whether to include the matching string in the response
+ $includeQuote = true;
+
+ // Create the configuration object
+ $inspectConfig = (new InspectConfig())
+ ->setMinLikelihood($minLikelihood)
+ ->setInfoTypes($infoTypes);
+
+ // Read image file into a buffer
+ $imageRef = fopen($imagePath, 'rb');
+ $imageBytes = fread($imageRef, filesize($imagePath));
+ fclose($imageRef);
+
+ // Get the image's content type
+ $typeConstant = (int) array_search(
+ mime_content_type($imagePath),
+ [false, 'image/jpeg', 'image/bmp', 'image/png', 'image/svg']
+ );
+
+ // Create the byte-storing object
+ $byteContent = (new ByteContentItem())
+ ->setType($typeConstant)
+ ->setData($imageBytes);
+
+ // Create the image redaction config objects
+ $imageRedactionConfigs = [];
+ foreach ($infoTypes as $infoType) {
+ $config = (new ImageRedactionConfig())
+ ->setInfoType($infoType);
+ $imageRedactionConfigs[] = $config;
+ }
+
+ $parent = "projects/$callingProjectId/locations/global";
+
+ // Run request
+ $response = $dlp->redactImage([
+ 'parent' => $parent,
+ 'inspectConfig' => $inspectConfig,
+ 'byteItem' => $byteContent,
+ 'imageRedactionConfigs' => $imageRedactionConfigs
+ ]);
+
+ // Save result to file
+ file_put_contents($outputPath, $response->getRedactedImage());
+
+ // Print completion message
+ print('Redacted image saved to ' . $outputPath . PHP_EOL);
}
-
-$parent = "projects/$callingProjectId/locations/global";
-
-// Run request
-$response = $dlp->redactImage([
- 'parent' => $parent,
- 'inspectConfig' => $inspectConfig,
- 'byteItem' => $byteContent,
- 'imageRedactionConfigs' => $imageRedactionConfigs
-]);
-
-// Save result to file
-file_put_contents($outputPath, $response->getRedactedImage());
-
-// Print completion message
-print('Redacted image saved to ' . $outputPath . PHP_EOL);
# [END dlp_redact_image]
+
+// 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/reidentify_fpe.php b/dlp/src/reidentify_fpe.php
index 17e3929063..6791cf1739 100644
--- a/dlp/src/reidentify_fpe.php
+++ b/dlp/src/reidentify_fpe.php
@@ -22,19 +22,9 @@
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/dlp/README.md
*/
-// Include Google Cloud dependendencies using Composer
-require_once __DIR__ . '/../vendor/autoload.php';
-
-if (count($argv) < 5 || count($argv) > 6) {
- return print("Usage: php reidentify_fpe.php CALLING_PROJECT STRING KEY_NAME WRAPPED_KEY [SURROGATE_TYPE_NAME]\n");
-}
-list($_, $callingProjectId, $string, $keyName, $wrappedKey) = $argv;
-$surrogateTypeName = isset($argv[5]) ? $argv[5] : '';
+namespace Google\Cloud\Samples\Dlp;
# [START dlp_reidentify_fpe]
-/**
- * Reidentify a deidentified string using Format-Preserving Encryption (FPE).
- */
use Google\Cloud\Dlp\V2\CryptoReplaceFfxFpeConfig;
use Google\Cloud\Dlp\V2\CryptoReplaceFfxFpeConfig\FfxCommonNativeAlphabet;
use Google\Cloud\Dlp\V2\CryptoKey;
@@ -50,79 +40,93 @@
use Google\Cloud\Dlp\V2\DeidentifyConfig;
use Google\Cloud\Dlp\V2\CustomInfoType\SurrogateType;
-/** Uncomment and populate these variables in your code */
-// $callingProjectId = 'The GCP Project ID to run the API call under';
-// $string = 'The string to reidentify';
-// $keyName = 'The name of the Cloud KMS key used to encrypt (wrap) the AES-256 key';
-// $wrappedKey = 'The name of the Cloud KMS key use, encrypted with the KMS key in $keyName';
-// $surrogateTypeName = ''; // (Optional) Surrogate custom info type to enable reidentification
-
-// Instantiate a client.
-$dlp = new DlpServiceClient();
-
-// The infoTypes of information to mask
-$ssnInfoType = (new InfoType())
- ->setName('US_SOCIAL_SECURITY_NUMBER');
-$infoTypes = [$ssnInfoType];
-
-// The set of characters to replace sensitive ones with
-// For more information, see https://cloud.google.com/dlp/docs/reference/rest/v2/organizations.deidentifyTemplates#ffxcommonnativealphabet
-$commonAlphabet = FfxCommonNativeAlphabet::NUMERIC;
-
-// Create the wrapped crypto key configuration object
-$kmsWrappedCryptoKey = (new KmsWrappedCryptoKey())
- ->setWrappedKey(base64_decode($wrappedKey))
- ->setCryptoKeyName($keyName);
-
-// Create the crypto key configuration object
-$cryptoKey = (new CryptoKey())
- ->setKmsWrapped($kmsWrappedCryptoKey);
-
-// Create the surrogate type object
-$surrogateType = (new InfoType())
- ->setName($surrogateTypeName);
-
-$customInfoType = (new CustomInfoType())
- ->setInfoType($surrogateType)
- ->setSurrogateType(new SurrogateType());
-
-// Create the crypto FFX FPE configuration object
-$cryptoReplaceFfxFpeConfig = (new CryptoReplaceFfxFpeConfig())
- ->setCryptoKey($cryptoKey)
- ->setCommonAlphabet($commonAlphabet)
- ->setSurrogateInfoType($surrogateType);
-
-// Create the information transform configuration objects
-$primitiveTransformation = (new PrimitiveTransformation())
- ->setCryptoReplaceFfxFpeConfig($cryptoReplaceFfxFpeConfig);
-
-$infoTypeTransformation = (new InfoTypeTransformation())
- ->setPrimitiveTransformation($primitiveTransformation);
-
-$infoTypeTransformations = (new InfoTypeTransformations())
- ->setTransformations([$infoTypeTransformation]);
-
-// Create the inspect configuration object
-$inspectConfig = (new InspectConfig())
- ->setCustomInfoTypes([$customInfoType]);
-
-// Create the reidentification configuration object
-$reidentifyConfig = (new DeidentifyConfig())
- ->setInfoTypeTransformations($infoTypeTransformations);
-
-$item = (new ContentItem())
- ->setValue($string);
-
-$parent = "projects/$callingProjectId/locations/global";
-
-// Run request
-$response = $dlp->reidentifyContent($parent, [
- 'reidentifyConfig' => $reidentifyConfig,
- 'inspectConfig' => $inspectConfig,
- 'item' => $item
-]);
-
-// Print the results
-$reidentifiedValue = $response->getItem()->getValue();
-print($reidentifiedValue);
+/**
+ * Reidentify a deidentified string using Format-Preserving Encryption (FPE).
+ *
+ * @param string $callingProjectId The GCP Project ID to run the API call under
+ * @param string $string The string to reidentify
+ * @param string $keyName The name of the Cloud KMS key used to encrypt (wrap) the AES-256 key
+ * @param string $wrappedKey The name of the Cloud KMS key use, encrypted with the KMS key in $keyName
+ * @param string $surrogateTypeName (Optional) Surrogate custom info type to enable reidentification
+ */
+function reidentify_fpe(
+ string $callingProjectId,
+ string $string,
+ string $keyName,
+ string $wrappedKey,
+ string $surrogateTypeName
+): void {
+ // Instantiate a client.
+ $dlp = new DlpServiceClient();
+
+ // The infoTypes of information to mask
+ $ssnInfoType = (new InfoType())
+ ->setName('US_SOCIAL_SECURITY_NUMBER');
+ $infoTypes = [$ssnInfoType];
+
+ // The set of characters to replace sensitive ones with
+ // For more information, see https://cloud.google.com/dlp/docs/reference/rest/v2/organizations.deidentifyTemplates#ffxcommonnativealphabet
+ $commonAlphabet = FfxCommonNativeAlphabet::NUMERIC;
+
+ // Create the wrapped crypto key configuration object
+ $kmsWrappedCryptoKey = (new KmsWrappedCryptoKey())
+ ->setWrappedKey(base64_decode($wrappedKey))
+ ->setCryptoKeyName($keyName);
+
+ // Create the crypto key configuration object
+ $cryptoKey = (new CryptoKey())
+ ->setKmsWrapped($kmsWrappedCryptoKey);
+
+ // Create the surrogate type object
+ $surrogateType = (new InfoType())
+ ->setName($surrogateTypeName);
+
+ $customInfoType = (new CustomInfoType())
+ ->setInfoType($surrogateType)
+ ->setSurrogateType(new SurrogateType());
+
+ // Create the crypto FFX FPE configuration object
+ $cryptoReplaceFfxFpeConfig = (new CryptoReplaceFfxFpeConfig())
+ ->setCryptoKey($cryptoKey)
+ ->setCommonAlphabet($commonAlphabet)
+ ->setSurrogateInfoType($surrogateType);
+
+ // Create the information transform configuration objects
+ $primitiveTransformation = (new PrimitiveTransformation())
+ ->setCryptoReplaceFfxFpeConfig($cryptoReplaceFfxFpeConfig);
+
+ $infoTypeTransformation = (new InfoTypeTransformation())
+ ->setPrimitiveTransformation($primitiveTransformation);
+
+ $infoTypeTransformations = (new InfoTypeTransformations())
+ ->setTransformations([$infoTypeTransformation]);
+
+ // Create the inspect configuration object
+ $inspectConfig = (new InspectConfig())
+ ->setCustomInfoTypes([$customInfoType]);
+
+ // Create the reidentification configuration object
+ $reidentifyConfig = (new DeidentifyConfig())
+ ->setInfoTypeTransformations($infoTypeTransformations);
+
+ $item = (new ContentItem())
+ ->setValue($string);
+
+ $parent = "projects/$callingProjectId/locations/global";
+
+ // Run request
+ $response = $dlp->reidentifyContent($parent, [
+ 'reidentifyConfig' => $reidentifyConfig,
+ 'inspectConfig' => $inspectConfig,
+ 'item' => $item
+ ]);
+
+ // Print the results
+ $reidentifiedValue = $response->getItem()->getValue();
+ print($reidentifiedValue);
+}
# [END dlp_reidentify_fpe]
+
+// 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 0dcef24fee..b453a32af4 100644
--- a/dlp/test/dlpLongRunningTest.php
+++ b/dlp/test/dlpLongRunningTest.php
@@ -54,7 +54,7 @@ public function testInspectDatastore()
$kind = 'Person';
$namespace = 'DLP';
- $output = $this->runSnippet('inspect_datastore', [
+ $output = $this->runFunctionSnippet('inspect_datastore', [
self::$projectId,
self::$projectId,
self::$topic->name(),
@@ -67,7 +67,7 @@ public function testInspectDatastore()
public function testInspectBigquery()
{
- $output = $this->runSnippet('inspect_bigquery', [
+ $output = $this->runFunctionSnippet('inspect_bigquery', [
self::$projectId,
self::$projectId,
self::$topic->name(),
@@ -83,7 +83,7 @@ public function testInspectGCS()
$bucketName = $this->requireEnv('GOOGLE_STORAGE_BUCKET');
$objectName = 'dlp/harmful.csv';
- $output = $this->runSnippet('inspect_gcs', [
+ $output = $this->runFunctionSnippet('inspect_gcs', [
self::$projectId,
self::$topic->name(),
self::$subscription->name(),
@@ -97,7 +97,7 @@ public function testNumericalStats()
{
$columnName = 'Age';
- $output = $this->runSnippet('numerical_stats', [
+ $output = $this->runFunctionSnippet('numerical_stats', [
self::$projectId, // calling project
self::$projectId, // data project
self::$topic->name(),
@@ -115,7 +115,7 @@ public function testCategoricalStats()
{
$columnName = 'Gender';
- $output = $this->runSnippet('categorical_stats', [
+ $output = $this->runFunctionSnippet('categorical_stats', [
self::$projectId, // calling project
self::$projectId, // data project
self::$topic->name(),
@@ -134,7 +134,7 @@ public function testKAnonymity()
{
$quasiIds = 'Age,Gender';
- $output = $this->runSnippet('k_anonymity', [
+ $output = $this->runFunctionSnippet('k_anonymity', [
self::$projectId, // calling project
self::$projectId, // data project
self::$topic->name(),
@@ -152,7 +152,7 @@ public function testLDiversity()
$sensitiveAttribute = 'Name';
$quasiIds = 'Age,Gender';
- $output = $this->runSnippet('l_diversity', [
+ $output = $this->runFunctionSnippet('l_diversity', [
self::$projectId, // calling project
self::$projectId, // data project
self::$topic->name(),
@@ -173,7 +173,7 @@ public function testKMap()
$quasiIds = 'Age,Gender';
$infoTypes = 'AGE,GENDER';
- $output = $this->runSnippet('k_map', [
+ $output = $this->runFunctionSnippet('k_map', [
self::$projectId,
self::$projectId,
self::$topic->name(),
diff --git a/dlp/test/dlpTest.php b/dlp/test/dlpTest.php
index 73bae7e2c2..7b34de839a 100644
--- a/dlp/test/dlpTest.php
+++ b/dlp/test/dlpTest.php
@@ -31,7 +31,7 @@ class dlpTest extends TestCase
public function testInspectImageFile()
{
- $output = $this->runSnippet('inspect_image_file', [
+ $output = $this->runFunctionSnippet('inspect_image_file', [
self::$projectId,
__DIR__ . '/data/test.png'
]);
@@ -41,7 +41,7 @@ public function testInspectImageFile()
public function testInspectTextFile()
{
- $output = $this->runSnippet('inspect_text_file', [
+ $output = $this->runFunctionSnippet('inspect_text_file', [
self::$projectId,
__DIR__ . '/data/test.txt'
]);
@@ -51,7 +51,7 @@ public function testInspectTextFile()
public function testInspectString()
{
- $output = $this->runSnippet('inspect_string', [
+ $output = $this->runFunctionSnippet('inspect_string', [
self::$projectId,
'My name is Gary Smith and my email is gary@example.com'
]);
@@ -62,13 +62,13 @@ public function testInspectString()
public function testListInfoTypes()
{
// list all info types
- $output = $this->runSnippet('list_info_types');
+ $output = $this->runFunctionSnippet('list_info_types');
$this->assertStringContainsString('US_DEA_NUMBER', $output);
$this->assertStringContainsString('AMERICAN_BANKERS_CUSIP_ID', $output);
// list info types with a filter
- $output = $this->runSnippet(
+ $output = $this->runFunctionSnippet(
'list_info_types',
['supported_by=RISK_ANALYSIS']
);
@@ -81,7 +81,7 @@ public function testRedactImage()
$imagePath = __DIR__ . '/data/test.png';
$outputPath = __DIR__ . '/data/redact.output.png';
- $output = $this->runSnippet('redact_image', [
+ $output = $this->runFunctionSnippet('redact_image', [
self::$projectId,
$imagePath,
$outputPath,
@@ -95,7 +95,7 @@ public function testRedactImage()
public function testDeidentifyMask()
{
$numberToMask = 5;
- $output = $this->runSnippet('deidentify_mask', [
+ $output = $this->runFunctionSnippet('deidentify_mask', [
self::$projectId,
'My SSN is 372819127.',
$numberToMask,
@@ -114,7 +114,7 @@ public function testDeidentifyDates()
$upperBoundDays = 5;
$contextField = 'name';
- $output = $this->runSnippet('deidentify_dates', [
+ $output = $this->runFunctionSnippet('deidentify_dates', [
self::$projectId,
$inputCsv,
$outputCsv,
@@ -146,7 +146,7 @@ public function testDeidReidFPE()
$string = 'My SSN is 372819127.';
$surrogateType = 'SSN_TOKEN';
- $deidOutput = $this->runSnippet('deidentify_fpe', [
+ $deidOutput = $this->runFunctionSnippet('deidentify_fpe', [
self::$projectId,
$string,
$keyName,
@@ -155,7 +155,7 @@ public function testDeidReidFPE()
]);
$this->assertRegExp('/My SSN is SSN_TOKEN\(9\):\d+/', $deidOutput);
- $reidOutput = $this->runSnippet('reidentify_fpe', [
+ $reidOutput = $this->runFunctionSnippet('reidentify_fpe', [
self::$projectId,
$deidOutput,
$keyName,
@@ -179,7 +179,7 @@ public function testTriggers()
$scanPeriod = 1;
$autoPopulateTimespan = true;
- $output = $this->runSnippet('create_trigger', [
+ $output = $this->runFunctionSnippet('create_trigger', [
self::$projectId,
$bucketName,
$triggerId,
@@ -191,13 +191,13 @@ public function testTriggers()
$fullTriggerId = sprintf('projects/%s/locations/global/jobTriggers/%s', self::$projectId, $triggerId);
$this->assertStringContainsString('Successfully created trigger ' . $fullTriggerId, $output);
- $output = $this->runSnippet('list_triggers', [self::$projectId]);
+ $output = $this->runFunctionSnippet('list_triggers', [self::$projectId]);
$this->assertStringContainsString('Trigger ' . $fullTriggerId, $output);
$this->assertStringContainsString('Display Name: ' . $displayName, $output);
$this->assertStringContainsString('Description: ' . $description, $output);
$this->assertStringContainsString('Auto-populates timespan config: yes', $output);
- $output = $this->runSnippet('delete_trigger', [
+ $output = $this->runFunctionSnippet('delete_trigger', [
self::$projectId,
$triggerId
]);
@@ -211,7 +211,7 @@ public function testInspectTemplates()
$templateId = uniqid('my-php-test-inspect-template-');
$fullTemplateId = sprintf('projects/%s/locations/global/inspectTemplates/%s', self::$projectId, $templateId);
- $output = $this->runSnippet('create_inspect_template', [
+ $output = $this->runFunctionSnippet('create_inspect_template', [
self::$projectId,
$templateId,
$displayName,
@@ -219,12 +219,12 @@ public function testInspectTemplates()
]);
$this->assertStringContainsString('Successfully created template ' . $fullTemplateId, $output);
- $output = $this->runSnippet('list_inspect_templates', [self::$projectId]);
+ $output = $this->runFunctionSnippet('list_inspect_templates', [self::$projectId]);
$this->assertStringContainsString('Template ' . $fullTemplateId, $output);
$this->assertStringContainsString('Display Name: ' . $displayName, $output);
$this->assertStringContainsString('Description: ' . $description, $output);
- $output = $this->runSnippet('delete_inspect_template', [
+ $output = $this->runFunctionSnippet('delete_inspect_template', [
self::$projectId,
$templateId
]);
@@ -243,7 +243,7 @@ public function testJobs()
);
$jobIdRegex = "~projects/.*/dlpJobs/i-\d+~";
- $output = $this->runSnippet('list_jobs', [
+ $output = $this->runFunctionSnippet('list_jobs', [
self::$projectId,
$filter,
]);
@@ -252,7 +252,7 @@ public function testJobs()
preg_match($jobIdRegex, $output, $jobIds);
$jobId = $jobIds[0];
- $output = $this->runSnippet(
+ $output = $this->runFunctionSnippet(
'delete_job',
[$jobId]
);
diff --git a/endpoints/getting-started/app.php b/endpoints/getting-started/app.php
index c854f3f0a9..832cd6dbbe 100644
--- a/endpoints/getting-started/app.php
+++ b/endpoints/getting-started/app.php
@@ -71,7 +71,7 @@
->withHeader('Content-Type', 'application/json');
});
-function get_user_info(Request $request)
+function get_user_info(Request $request): void
{
// Retrieves the authenication information from Google Cloud Endpoints.
$encoded_info = $request->getHeaderLine('X-Endpoint-API-UserInfo');
diff --git a/firestore/src/City.php b/firestore/src/City.php
index 1ceb1108bb..578963ee9d 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/data_delete_collection.php b/firestore/src/data_delete_collection.php
index d1f63ff329..de0e8adfc0 100644
--- a/firestore/src/data_delete_collection.php
+++ b/firestore/src/data_delete_collection.php
@@ -34,7 +34,7 @@
*/
# [START fs_delete_collection]
# [START firestore_data_delete_collection]
-function data_delete_collection(string $projectId, string $collectionName, int $batchSize)
+function data_delete_collection(string $projectId, string $collectionName, int $batchSize): void
{
// Create the Cloud Firestore client
$db = new FirestoreClient([
diff --git a/firestore/src/setup_client_create.php b/firestore/src/setup_client_create.php
index 89a4b35bdf..109df1470b 100644
--- a/firestore/src/setup_client_create.php
+++ b/firestore/src/setup_client_create.php
@@ -30,7 +30,7 @@
/**
* Initialize Cloud Firestore with default project ID.
*/
-function setup_client_create(string $projectId = null)
+function setup_client_create(string $projectId = null): void
{
// Create the Cloud Firestore client
if (empty($projectId)) {
diff --git a/firestore/src/solution_sharded_counter_create.php b/firestore/src/solution_sharded_counter_create.php
index 05a29e9281..f11bbc2e11 100644
--- a/firestore/src/solution_sharded_counter_create.php
+++ b/firestore/src/solution_sharded_counter_create.php
@@ -41,7 +41,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 e92dc19e79..169c915219 100644
--- a/firestore/src/solution_sharded_counter_increment.php
+++ b/firestore/src/solution_sharded_counter_increment.php
@@ -46,8 +46,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/functions/concepts_build_extension/index.php b/functions/concepts_build_extension/index.php
index 1bf869d191..71459a3f22 100644
--- a/functions/concepts_build_extension/index.php
+++ b/functions/concepts_build_extension/index.php
@@ -23,7 +23,7 @@
use Psr\Http\Message\ServerRequestInterface;
-function helloBuildExtension(ServerRequestInterface $request)
+function helloBuildExtension(ServerRequestInterface $request): void
{
return helloworld_from_extension();
}
diff --git a/functions/firebase_auth/index.php b/functions/firebase_auth/index.php
index 27b048eff1..a9b78dcb34 100644
--- a/functions/firebase_auth/index.php
+++ b/functions/firebase_auth/index.php
@@ -19,7 +19,7 @@
use Google\CloudFunctions\CloudEvent;
-function firebaseAuth(CloudEvent $cloudevent)
+function firebaseAuth(CloudEvent $cloudevent): void
{
$log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
$data = $cloudevent->getData();
diff --git a/functions/firebase_firestore/index.php b/functions/firebase_firestore/index.php
index 249e524a6c..4dd919197f 100644
--- a/functions/firebase_firestore/index.php
+++ b/functions/firebase_firestore/index.php
@@ -19,7 +19,7 @@
use Google\CloudFunctions\CloudEvent;
-function firebaseFirestore(CloudEvent $cloudevent)
+function firebaseFirestore(CloudEvent $cloudevent): void
{
$log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
diff --git a/functions/firebase_firestore_reactive/index.php b/functions/firebase_firestore_reactive/index.php
index f308858c73..1b22265a2d 100644
--- a/functions/firebase_firestore_reactive/index.php
+++ b/functions/firebase_firestore_reactive/index.php
@@ -20,7 +20,7 @@
use Google\Cloud\Firestore\FirestoreClient;
use Google\CloudFunctions\CloudEvent;
-function firebaseReactive(CloudEvent $cloudevent)
+function firebaseReactive(CloudEvent $cloudevent): void
{
$log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
$data = $cloudevent->getData();
diff --git a/functions/firebase_remote_config/index.php b/functions/firebase_remote_config/index.php
index 9a8cb3a2c1..6104d11f65 100644
--- a/functions/firebase_remote_config/index.php
+++ b/functions/firebase_remote_config/index.php
@@ -19,7 +19,7 @@
use Google\CloudFunctions\CloudEvent;
-function firebaseRemoteConfig(CloudEvent $cloudevent)
+function firebaseRemoteConfig(CloudEvent $cloudevent): void
{
$log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
diff --git a/functions/firebase_rtdb/index.php b/functions/firebase_rtdb/index.php
index 8121bfbeaf..26778bc9ce 100644
--- a/functions/firebase_rtdb/index.php
+++ b/functions/firebase_rtdb/index.php
@@ -19,7 +19,7 @@
use Google\CloudFunctions\CloudEvent;
-function firebaseRTDB(CloudEvent $cloudevent)
+function firebaseRTDB(CloudEvent $cloudevent): void
{
$log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
diff --git a/functions/helloworld_storage/index.php b/functions/helloworld_storage/index.php
index a2a1e5046f..610b3afa23 100644
--- a/functions/helloworld_storage/index.php
+++ b/functions/helloworld_storage/index.php
@@ -27,7 +27,7 @@
// match the first parameter.
FunctionsFramework::cloudEvent('helloGCS', 'helloGCS');
-function helloGCS(CloudEventInterface $cloudevent)
+function helloGCS(CloudEventInterface $cloudevent): void
{
// This function supports all Cloud Storage event types.
$log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
diff --git a/iap/composer.json b/iap/composer.json
index 63ccfb7fda..2ea5ce0920 100644
--- a/iap/composer.json
+++ b/iap/composer.json
@@ -1,7 +1,7 @@
{
"require": {
"kelvinmo/simplejwt": "^0.5.1",
- "google/auth":"^1.8.0",
+ "google/auth":"^1.20.1",
"guzzlehttp/guzzle": "~7.4.0"
},
"autoload": {
diff --git a/iap/src/make_iap_request.php b/iap/src/make_iap_request.php
index beb1372dfa..097579ced9 100644
--- a/iap/src/make_iap_request.php
+++ b/iap/src/make_iap_request.php
@@ -34,7 +34,7 @@
* @param string $url The Identity-Aware Proxy-protected URL to fetch.
* @param string $clientId The client ID used by Identity-Aware Proxy.
*/
-function make_iap_request($url, $clientId)
+function make_iap_request($url, $clientId): void
{
// create middleware, using the client ID as the target audience for IAP
$middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($clientId);
diff --git a/iap/src/validate_jwt.php b/iap/src/validate_jwt.php
index 73c8a892fc..020831a6a5 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 f8cbc2dba2..9583009450 100644
--- a/kms/src/create_key_asymmetric_decrypt.php
+++ b/kms/src/create_key_asymmetric_decrypt.php
@@ -30,7 +30,7 @@ function create_key_asymmetric_decrypt_sample(
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 43ac42fc0f..8312dc3829 100644
--- a/kms/src/create_key_asymmetric_sign.php
+++ b/kms/src/create_key_asymmetric_sign.php
@@ -30,7 +30,7 @@ function create_key_asymmetric_sign_sample(
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 ab8bf178db..351e592aae 100644
--- a/kms/src/create_key_hsm.php
+++ b/kms/src/create_key_hsm.php
@@ -31,7 +31,7 @@ function create_key_hsm_sample(
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 63ac2bf06d..433bd8b26c 100644
--- a/kms/src/create_key_labels.php
+++ b/kms/src/create_key_labels.php
@@ -29,7 +29,7 @@ function create_key_labels_sample(
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 80090884c4..5f839224bd 100644
--- a/kms/src/create_key_mac.php
+++ b/kms/src/create_key_mac.php
@@ -30,7 +30,7 @@ function create_key_mac_sample(
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 6b3fa6b28d..f811a872eb 100644
--- a/kms/src/create_key_ring.php
+++ b/kms/src/create_key_ring.php
@@ -25,7 +25,7 @@ function create_key_ring_sample(
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 f7c02cbbc9..933ca281e2 100644
--- a/kms/src/create_key_rotation_schedule.php
+++ b/kms/src/create_key_rotation_schedule.php
@@ -31,7 +31,7 @@ function create_key_rotation_schedule_sample(
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 292c2fd29c..d80e0b6016 100644
--- a/kms/src/create_key_symmetric_encrypt_decrypt.php
+++ b/kms/src/create_key_symmetric_encrypt_decrypt.php
@@ -29,7 +29,7 @@ function create_key_symmetric_encrypt_decrypt_sample(
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 b4fccd12e6..f6ee2a3432 100644
--- a/kms/src/create_key_version.php
+++ b/kms/src/create_key_version.php
@@ -26,7 +26,7 @@ function create_key_version_sample(
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/decrypt_asymmetric.php b/kms/src/decrypt_asymmetric.php
index 7d5777d55f..ee5440b20a 100644
--- a/kms/src/decrypt_asymmetric.php
+++ b/kms/src/decrypt_asymmetric.php
@@ -20,6 +20,9 @@
// [START kms_decrypt_asymmetric]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\AsymmetricDecryptResponse
+ */
function decrypt_asymmetric_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/decrypt_symmetric.php b/kms/src/decrypt_symmetric.php
index c6af149dff..537d9bd0b5 100644
--- a/kms/src/decrypt_symmetric.php
+++ b/kms/src/decrypt_symmetric.php
@@ -20,6 +20,9 @@
// [START kms_decrypt_symmetric]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\DecryptResponse
+ */
function decrypt_symmetric_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/destroy_key_version.php b/kms/src/destroy_key_version.php
index 1b8bfc6e74..fa71f3184f 100644
--- a/kms/src/destroy_key_version.php
+++ b/kms/src/destroy_key_version.php
@@ -20,6 +20,9 @@
// [START kms_destroy_key_version]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\CryptoKeyVersion
+ */
function destroy_key_version_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/disable_key_version.php b/kms/src/disable_key_version.php
index dc07f45f5d..36cf1941d7 100644
--- a/kms/src/disable_key_version.php
+++ b/kms/src/disable_key_version.php
@@ -29,7 +29,7 @@ function disable_key_version_sample(
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 e99281cb69..d87bd3fd5e 100644
--- a/kms/src/enable_key_version.php
+++ b/kms/src/enable_key_version.php
@@ -29,7 +29,7 @@ function enable_key_version_sample(
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 62cbf524b6..42e4d45068 100644
--- a/kms/src/encrypt_asymmetric.php
+++ b/kms/src/encrypt_asymmetric.php
@@ -25,7 +25,7 @@ function encrypt_asymmetric_sample(
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/encrypt_symmetric.php b/kms/src/encrypt_symmetric.php
index 0f508cce42..4eb064f6ce 100644
--- a/kms/src/encrypt_symmetric.php
+++ b/kms/src/encrypt_symmetric.php
@@ -20,6 +20,9 @@
// [START kms_encrypt_symmetric]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\EncryptResponse
+ */
function encrypt_symmetric_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/generate_random_bytes.php b/kms/src/generate_random_bytes.php
index 1a0493c822..8dc332faae 100644
--- a/kms/src/generate_random_bytes.php
+++ b/kms/src/generate_random_bytes.php
@@ -21,6 +21,9 @@
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\ProtectionLevel;
+/**
+ * @return \Google\Cloud\Kms\V1\GenerateRandomBytesResponse
+ */
function generate_random_bytes_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/get_key_labels.php b/kms/src/get_key_labels.php
index c57ecd19f2..9d1e9c2e69 100644
--- a/kms/src/get_key_labels.php
+++ b/kms/src/get_key_labels.php
@@ -20,6 +20,9 @@
// [START kms_get_key_labels]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\CryptoKey
+ */
function get_key_labels_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/get_key_version_attestation.php b/kms/src/get_key_version_attestation.php
index 0adc9acf75..cd1a741739 100644
--- a/kms/src/get_key_version_attestation.php
+++ b/kms/src/get_key_version_attestation.php
@@ -20,6 +20,9 @@
// [START kms_get_key_version_attestation]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\KeyOperationAttestation
+ */
function get_key_version_attestation_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/get_public_key.php b/kms/src/get_public_key.php
index 5043a18c0c..be311837e0 100644
--- a/kms/src/get_public_key.php
+++ b/kms/src/get_public_key.php
@@ -20,6 +20,9 @@
// [START kms_get_public_key]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\PublicKey
+ */
function get_public_key_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/iam_add_member.php b/kms/src/iam_add_member.php
index 6971a190f2..ef46bc92e0 100644
--- a/kms/src/iam_add_member.php
+++ b/kms/src/iam_add_member.php
@@ -21,6 +21,9 @@
use Google\Cloud\Iam\V1\Binding;
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Iam\V1\Policy
+ */
function iam_add_member_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/iam_get_policy.php b/kms/src/iam_get_policy.php
index 95f77ab9ec..a597afc769 100644
--- a/kms/src/iam_get_policy.php
+++ b/kms/src/iam_get_policy.php
@@ -20,6 +20,9 @@
// [START kms_iam_get_policy]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Iam\V1\Policy
+ */
function iam_get_policy_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/iam_remove_member.php b/kms/src/iam_remove_member.php
index 1d139cba64..8b69d0c509 100644
--- a/kms/src/iam_remove_member.php
+++ b/kms/src/iam_remove_member.php
@@ -28,7 +28,7 @@ function iam_remove_member_sample(
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/quickstart.php b/kms/src/quickstart.php
index bf5f88cb44..3915fd89c9 100644
--- a/kms/src/quickstart.php
+++ b/kms/src/quickstart.php
@@ -20,6 +20,9 @@
// [START kms_quickstart]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\ApiCore\PagedListResponse
+ */
function quickstart_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1'
diff --git a/kms/src/restore_key_version.php b/kms/src/restore_key_version.php
index d4c002fe3e..6f426c00f9 100644
--- a/kms/src/restore_key_version.php
+++ b/kms/src/restore_key_version.php
@@ -20,6 +20,9 @@
// [START kms_restore_key_version]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\CryptoKeyVersion
+ */
function restore_key_version_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/sign_asymmetric.php b/kms/src/sign_asymmetric.php
index 51f3830c7a..7bf3846b74 100644
--- a/kms/src/sign_asymmetric.php
+++ b/kms/src/sign_asymmetric.php
@@ -21,6 +21,9 @@
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\Digest;
+/**
+ * @return \Google\Cloud\Kms\V1\AsymmetricSignResponse
+ */
function sign_asymmetric_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/sign_mac.php b/kms/src/sign_mac.php
index f7a36a7144..26c16267ea 100644
--- a/kms/src/sign_mac.php
+++ b/kms/src/sign_mac.php
@@ -20,6 +20,9 @@
// [START kms_sign_mac]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\MacSignResponse
+ */
function sign_mac_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/update_key_add_rotation.php b/kms/src/update_key_add_rotation.php
index 6d614c1491..5dcaab5e13 100644
--- a/kms/src/update_key_add_rotation.php
+++ b/kms/src/update_key_add_rotation.php
@@ -29,7 +29,7 @@ function update_key_add_rotation_sample(
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 a8f8aa80df..f3fd702aff 100644
--- a/kms/src/update_key_remove_labels.php
+++ b/kms/src/update_key_remove_labels.php
@@ -27,7 +27,7 @@ function update_key_remove_labels_sample(
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 d49772a44a..9a35d054e0 100644
--- a/kms/src/update_key_remove_rotation.php
+++ b/kms/src/update_key_remove_rotation.php
@@ -27,7 +27,7 @@ function update_key_remove_rotation_sample(
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_set_primary.php b/kms/src/update_key_set_primary.php
index 9d4174639f..15d0e4a557 100644
--- a/kms/src/update_key_set_primary.php
+++ b/kms/src/update_key_set_primary.php
@@ -20,6 +20,9 @@
// [START kms_update_key_set_primary]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\CryptoKey
+ */
function update_key_set_primary_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/kms/src/update_key_update_labels.php b/kms/src/update_key_update_labels.php
index f107b89b8b..6435bcf550 100644
--- a/kms/src/update_key_update_labels.php
+++ b/kms/src/update_key_update_labels.php
@@ -27,7 +27,7 @@ function update_key_update_labels_sample(
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 b6b810df34..d790d97d5c 100644
--- a/kms/src/verify_asymmetric_ec.php
+++ b/kms/src/verify_asymmetric_ec.php
@@ -28,7 +28,7 @@ function verify_asymmetric_ec_sample(
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 f740910f83..1eed056c7d 100644
--- a/kms/src/verify_asymmetric_rsa.php
+++ b/kms/src/verify_asymmetric_rsa.php
@@ -26,7 +26,7 @@ function verify_asymmetric_rsa_sample(
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/kms/src/verify_mac.php b/kms/src/verify_mac.php
index 88feb313ef..b13376d150 100644
--- a/kms/src/verify_mac.php
+++ b/kms/src/verify_mac.php
@@ -20,6 +20,9 @@
// [START kms_verify_mac]
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
+/**
+ * @return \Google\Cloud\Kms\V1\MacVerifyResponse
+ */
function verify_mac_sample(
string $projectId = 'my-project',
string $locationId = 'us-east1',
diff --git a/logging/src/log_entry_functions.php b/logging/src/log_entry_functions.php
index fce7e4e1c8..cee78b0802 100644
--- a/logging/src/log_entry_functions.php
+++ b/logging/src/log_entry_functions.php
@@ -33,7 +33,7 @@
* @param string $loggerName The name of the logger.
* @param string $message The log message.
*/
-function write_log($projectId, $loggerName, $message)
+function write_log($projectId, $loggerName, $message): void
{
$logging = new LoggingClient(['projectId' => $projectId]);
$logger = $logging->logger($loggerName, [
@@ -57,7 +57,7 @@ function write_log($projectId, $loggerName, $message)
* @param string $projectId The Google project ID.
* @param string $loggerName The name of the logger.
*/
-function list_entries($projectId, $loggerName)
+function list_entries($projectId, $loggerName): void
{
$logging = new LoggingClient(['projectId' => $projectId]);
$loggerFullName = sprintf('projects/%s/logs/%s', $projectId, $loggerName);
@@ -96,7 +96,7 @@ function list_entries($projectId, $loggerName)
* @param string $projectId The Google project ID.
* @param string $loggerName The name of the logger.
*/
-function delete_logger($projectId, $loggerName)
+function delete_logger($projectId, $loggerName): void
{
$logging = new LoggingClient(['projectId' => $projectId]);
$logger = $logging->logger($loggerName);
diff --git a/logging/src/sink_functions.php b/logging/src/sink_functions.php
index 8db530ef43..bb0cdabaf1 100644
--- a/logging/src/sink_functions.php
+++ b/logging/src/sink_functions.php
@@ -30,7 +30,7 @@
* @param string $destination The destination of the sink.
* @param string $filterString The filter for the sink.
*/
-function create_sink($projectId, $sinkName, $destination, $filterString)
+function create_sink($projectId, $sinkName, $destination, $filterString): void
{
$logging = new LoggingClient(['projectId' => $projectId]);
$logging->createSink(
@@ -48,7 +48,7 @@ function create_sink($projectId, $sinkName, $destination, $filterString)
* @param string $projectId The Google project ID.
* @param string $sinkName The name of the sink.
*/
-function delete_sink($projectId, $sinkName)
+function delete_sink($projectId, $sinkName): void
{
$logging = new LoggingClient(['projectId' => $projectId]);
$logging->sink($sinkName)->delete();
@@ -62,7 +62,7 @@ function delete_sink($projectId, $sinkName)
*
* @param string $projectId
*/
-function list_sinks($projectId)
+function list_sinks($projectId): void
{
$logging = new LoggingClient(['projectId' => $projectId]);
$sinks = $logging->sinks();
@@ -84,10 +84,10 @@ function list_sinks($projectId)
* Update a log sink.
*
* @param string $projectId
- * @param string sinkName
+ * @param string $sinkName
* @param string $filterString
*/
-function update_sink($projectId, $sinkName, $filterString)
+function update_sink($projectId, $sinkName, $filterString): void
{
$logging = new LoggingClient(['projectId' => $projectId]);
$sink = $logging->sink($sinkName);
diff --git a/logging/src/write_with_monolog_logger.php b/logging/src/write_with_monolog_logger.php
index 4554e4943d..54621a0495 100644
--- a/logging/src/write_with_monolog_logger.php
+++ b/logging/src/write_with_monolog_logger.php
@@ -28,8 +28,10 @@
* @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_monolog_logger($projectId, $loggerName, $message, $level = LogLevel::WARNING)
+function write_with_monolog_logger($projectId, $loggerName, $message, $level = LogLevel::WARNING): void
{
$logging = new LoggingClient([
'projectId' => $projectId
diff --git a/logging/src/write_with_psr_logger.php b/logging/src/write_with_psr_logger.php
index 8f5daf23ee..f531b14f10 100644
--- a/logging/src/write_with_psr_logger.php
+++ b/logging/src/write_with_psr_logger.php
@@ -26,8 +26,10 @@
* @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($projectId, $loggerName, $message, $level = LogLevel::WARNING)
+function write_with_psr_logger($projectId, $loggerName, $message, $level = LogLevel::WARNING): void
{
$logging = new LoggingClient(['projectId' => $projectId]);
$logger = $logging->psrLogger($loggerName);
diff --git a/media/transcoder/src/create_job_from_ad_hoc.php b/media/transcoder/src/create_job_from_ad_hoc.php
index 96d25fd8f4..4694d6d89e 100644
--- a/media/transcoder/src/create_job_from_ad_hoc.php
+++ b/media/transcoder/src/create_job_from_ad_hoc.php
@@ -41,7 +41,7 @@
* @param string $inputUri Uri of the video in the Cloud Storage bucket.
* @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
*/
-function create_job_from_ad_hoc($projectId, $location, $inputUri, $outputUri)
+function create_job_from_ad_hoc($projectId, $location, $inputUri, $outputUri): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/create_job_from_preset.php b/media/transcoder/src/create_job_from_preset.php
index 2ec16b8b37..446bc54d37 100644
--- a/media/transcoder/src/create_job_from_preset.php
+++ b/media/transcoder/src/create_job_from_preset.php
@@ -37,7 +37,7 @@
* @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
* @param string $preset The preset template (for example, "preset/web-hd").
*/
-function create_job_from_preset($projectId, $location, $inputUri, $outputUri, $preset)
+function create_job_from_preset($projectId, $location, $inputUri, $outputUri, $preset): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/create_job_from_template.php b/media/transcoder/src/create_job_from_template.php
index dc5ade47e0..4f8f48be67 100644
--- a/media/transcoder/src/create_job_from_template.php
+++ b/media/transcoder/src/create_job_from_template.php
@@ -37,7 +37,7 @@
* @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
* @param string $templateId The job template ID.
*/
-function create_job_from_template($projectId, $location, $inputUri, $outputUri, $templateId)
+function create_job_from_template($projectId, $location, $inputUri, $outputUri, $templateId): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/create_job_template.php b/media/transcoder/src/create_job_template.php
index cffa891cf8..9076cf80b2 100644
--- a/media/transcoder/src/create_job_template.php
+++ b/media/transcoder/src/create_job_template.php
@@ -40,7 +40,7 @@
* @param string $location The location of the job template.
* @param string $templateId The user-defined template ID.
*/
-function create_job_template($projectId, $location, $templateId)
+function create_job_template($projectId, $location, $templateId): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/create_job_with_animated_overlay.php b/media/transcoder/src/create_job_with_animated_overlay.php
index 4f4138fd73..0955302188 100644
--- a/media/transcoder/src/create_job_with_animated_overlay.php
+++ b/media/transcoder/src/create_job_with_animated_overlay.php
@@ -44,7 +44,7 @@
* @param string $overlayImageUri Uri of the JPEG image for the overlay in the Cloud Storage bucket. Must be a JPEG.
* @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
*/
-function create_job_with_animated_overlay($projectId, $location, $inputUri, $overlayImageUri, $outputUri)
+function create_job_with_animated_overlay($projectId, $location, $inputUri, $overlayImageUri, $outputUri): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/create_job_with_concatenated_inputs.php b/media/transcoder/src/create_job_with_concatenated_inputs.php
index ad304c4b12..f1983644d1 100644
--- a/media/transcoder/src/create_job_with_concatenated_inputs.php
+++ b/media/transcoder/src/create_job_with_concatenated_inputs.php
@@ -49,17 +49,17 @@
* @param float $endTimeInput2 End time, in fractional seconds, relative to the second input video timeline.
* @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
*/
-function create_job_with_concatenated_inputs($projectId, $location, $input1Uri, $startTimeInput1, $endTimeInput1, $input2Uri, $startTimeInput2, $endTimeInput2, $outputUri)
+function create_job_with_concatenated_inputs($projectId, $location, $input1Uri, $startTimeInput1, $endTimeInput1, $input2Uri, $startTimeInput2, $endTimeInput2, $outputUri): void
{
$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/transcoder/src/create_job_with_periodic_images_spritesheet.php b/media/transcoder/src/create_job_with_periodic_images_spritesheet.php
index 944c683916..3e1c35ad11 100644
--- a/media/transcoder/src/create_job_with_periodic_images_spritesheet.php
+++ b/media/transcoder/src/create_job_with_periodic_images_spritesheet.php
@@ -44,7 +44,7 @@
* @param string $inputUri Uri of the video in the Cloud Storage bucket.
* @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
*/
-function create_job_with_periodic_images_spritesheet($projectId, $location, $inputUri, $outputUri)
+function create_job_with_periodic_images_spritesheet($projectId, $location, $inputUri, $outputUri): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/create_job_with_set_number_images_spritesheet.php b/media/transcoder/src/create_job_with_set_number_images_spritesheet.php
index f58591cfc8..b0c3b0f08a 100644
--- a/media/transcoder/src/create_job_with_set_number_images_spritesheet.php
+++ b/media/transcoder/src/create_job_with_set_number_images_spritesheet.php
@@ -43,7 +43,7 @@
* @param string $inputUri Uri of the video in the Cloud Storage bucket.
* @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
*/
-function create_job_with_set_number_images_spritesheet($projectId, $location, $inputUri, $outputUri)
+function create_job_with_set_number_images_spritesheet($projectId, $location, $inputUri, $outputUri): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/create_job_with_static_overlay.php b/media/transcoder/src/create_job_with_static_overlay.php
index 8ba1e1eeb6..3d64ad4693 100644
--- a/media/transcoder/src/create_job_with_static_overlay.php
+++ b/media/transcoder/src/create_job_with_static_overlay.php
@@ -44,7 +44,7 @@
* @param string $overlayImageUri Uri of the JPEG image for the overlay in the Cloud Storage bucket. Must be a JPEG.
* @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
*/
-function create_job_with_static_overlay($projectId, $location, $inputUri, $overlayImageUri, $outputUri)
+function create_job_with_static_overlay($projectId, $location, $inputUri, $overlayImageUri, $outputUri): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/delete_job.php b/media/transcoder/src/delete_job.php
index a492163909..d3c0a5523d 100644
--- a/media/transcoder/src/delete_job.php
+++ b/media/transcoder/src/delete_job.php
@@ -34,7 +34,7 @@
* @param string $location The location of the job.
* @param string $jobId The job ID.
*/
-function delete_job($projectId, $location, $jobId)
+function delete_job($projectId, $location, $jobId): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/delete_job_template.php b/media/transcoder/src/delete_job_template.php
index 9f31ffaea9..3048f1cd05 100644
--- a/media/transcoder/src/delete_job_template.php
+++ b/media/transcoder/src/delete_job_template.php
@@ -34,7 +34,7 @@
* @param string $location The location of the job template.
* @param string $templateId The user-defined template ID.
*/
-function delete_job_template($projectId, $location, $templateId)
+function delete_job_template($projectId, $location, $templateId): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/get_job.php b/media/transcoder/src/get_job.php
index 55fa92611a..0c23aa8ad0 100644
--- a/media/transcoder/src/get_job.php
+++ b/media/transcoder/src/get_job.php
@@ -34,7 +34,7 @@
* @param string $location The location of the job.
* @param string $jobId The job ID.
*/
-function get_job($projectId, $location, $jobId)
+function get_job($projectId, $location, $jobId): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/get_job_state.php b/media/transcoder/src/get_job_state.php
index 4a24a899fa..d38ab61390 100644
--- a/media/transcoder/src/get_job_state.php
+++ b/media/transcoder/src/get_job_state.php
@@ -35,7 +35,7 @@
* @param string $location The location of the job.
* @param string $jobId The job ID.
*/
-function get_job_state($projectId, $location, $jobId)
+function get_job_state($projectId, $location, $jobId): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/get_job_template.php b/media/transcoder/src/get_job_template.php
index f4aca36f40..32b41d9b3c 100644
--- a/media/transcoder/src/get_job_template.php
+++ b/media/transcoder/src/get_job_template.php
@@ -34,7 +34,7 @@
* @param string $location The location of the job template.
* @param string $templateId The user-defined template ID.
*/
-function get_job_template($projectId, $location, $templateId)
+function get_job_template($projectId, $location, $templateId): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/list_job_templates.php b/media/transcoder/src/list_job_templates.php
index ec9a3767f2..bf44a586da 100644
--- a/media/transcoder/src/list_job_templates.php
+++ b/media/transcoder/src/list_job_templates.php
@@ -33,7 +33,7 @@
* @param string $projectId The ID of your Google Cloud Platform project.
* @param string $location The location of the job templates.
*/
-function list_job_templates($projectId, $location)
+function list_job_templates($projectId, $location): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/media/transcoder/src/list_jobs.php b/media/transcoder/src/list_jobs.php
index 7bd44d7643..26fce8a36b 100644
--- a/media/transcoder/src/list_jobs.php
+++ b/media/transcoder/src/list_jobs.php
@@ -33,7 +33,7 @@
* @param string $projectId The ID of your Google Cloud Platform project.
* @param string $location The location of the jobs.
*/
-function list_jobs($projectId, $location)
+function list_jobs($projectId, $location): void
{
// Instantiate a client.
$transcoderServiceClient = new TranscoderServiceClient();
diff --git a/monitoring/src/alert_backup_policies.php b/monitoring/src/alert_backup_policies.php
index 1a8918e280..d57101f761 100644
--- a/monitoring/src/alert_backup_policies.php
+++ b/monitoring/src/alert_backup_policies.php
@@ -32,7 +32,7 @@
*
* @param string $projectId Your project ID
*/
-function alert_backup_policies($projectId)
+function alert_backup_policies($projectId): void
{
$alertClient = new AlertPolicyServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/alert_create_channel.php b/monitoring/src/alert_create_channel.php
index ecb0adc44c..1c1fbb38a3 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_create_policy.php b/monitoring/src/alert_create_policy.php
index 9f587b4fb7..74fe6f8d98 100644
--- a/monitoring/src/alert_create_policy.php
+++ b/monitoring/src/alert_create_policy.php
@@ -35,7 +35,7 @@
/**
* @param string $projectId Your project ID
*/
-function alert_create_policy($projectId)
+function alert_create_policy($projectId): void
{
$alertClient = new AlertPolicyServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/alert_delete_channel.php b/monitoring/src/alert_delete_channel.php
index 8f5c76fc89..d27a6ca675 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_enable_policies.php b/monitoring/src/alert_enable_policies.php
index e3fc61a59d..4e9557eb00 100644
--- a/monitoring/src/alert_enable_policies.php
+++ b/monitoring/src/alert_enable_policies.php
@@ -35,7 +35,7 @@
* @param string $filter Only enable/disable alert policies that match a filter.
* See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering
*/
-function alert_enable_policies($projectId, $enable = true, $filter = null)
+function alert_enable_policies($projectId, $enable = true, $filter = null): void
{
$alertClient = new AlertPolicyServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/alert_list_channels.php b/monitoring/src/alert_list_channels.php
index 3f49451fe9..8b0e7f47d0 100644
--- a/monitoring/src/alert_list_channels.php
+++ b/monitoring/src/alert_list_channels.php
@@ -29,7 +29,7 @@
/**
* @param string $projectId Your project ID
*/
-function alert_list_channels($projectId)
+function alert_list_channels($projectId): void
{
$channelClient = new NotificationChannelServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/alert_list_policies.php b/monitoring/src/alert_list_policies.php
index a7e997de24..87391c9824 100644
--- a/monitoring/src/alert_list_policies.php
+++ b/monitoring/src/alert_list_policies.php
@@ -35,7 +35,7 @@
*
* @param string $projectId Your project ID
*/
-function alert_list_policies($projectId)
+function alert_list_policies($projectId): void
{
$alertClient = new AlertPolicyServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/alert_replace_channels.php b/monitoring/src/alert_replace_channels.php
index 76cbe4ee46..535e99daa0 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 2722a6a791..56b0656b74 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/create_metric.php b/monitoring/src/create_metric.php
index 2e800b8d03..95bd718017 100644
--- a/monitoring/src/create_metric.php
+++ b/monitoring/src/create_metric.php
@@ -40,7 +40,7 @@
*
* @param string $projectId Your project ID
*/
-function create_metric($projectId)
+function create_metric($projectId): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/create_uptime_check.php b/monitoring/src/create_uptime_check.php
index f842514771..fe3c0bcffb 100644
--- a/monitoring/src/create_uptime_check.php
+++ b/monitoring/src/create_uptime_check.php
@@ -38,7 +38,7 @@
* @param string $hostName
* @param string $displayName
*/
-function create_uptime_check($projectId, $hostName = 'example.com', $displayName = 'New uptime check')
+function create_uptime_check($projectId, $hostName = 'example.com', $displayName = 'New uptime check'): void
{
$uptimeCheckClient = new UptimeCheckServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/delete_metric.php b/monitoring/src/delete_metric.php
index 9dd8acbe79..b49e7f003d 100644
--- a/monitoring/src/delete_metric.php
+++ b/monitoring/src/delete_metric.php
@@ -35,7 +35,7 @@
* @param string $projectId Your project ID
* @param string $metricId The ID of the Metric Descriptor to delete
*/
-function delete_metric($projectId, $metricId)
+function delete_metric($projectId, $metricId): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/delete_uptime_check.php b/monitoring/src/delete_uptime_check.php
index 077ea5b6ab..e076934821 100644
--- a/monitoring/src/delete_uptime_check.php
+++ b/monitoring/src/delete_uptime_check.php
@@ -35,7 +35,7 @@
* @param string $projectId Your project ID
* @param string $configName
*/
-function delete_uptime_check($projectId, $configName)
+function delete_uptime_check($projectId, $configName): void
{
$uptimeCheckClient = new UptimeCheckServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/get_descriptor.php b/monitoring/src/get_descriptor.php
index ccebd7e45c..79716618b9 100644
--- a/monitoring/src/get_descriptor.php
+++ b/monitoring/src/get_descriptor.php
@@ -35,7 +35,7 @@
* @param string $projectId Your project ID
* @param string $metricId The ID of the Metric Descriptor to get
*/
-function get_descriptor($projectId, $metricId)
+function get_descriptor($projectId, $metricId): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/get_resource.php b/monitoring/src/get_resource.php
index bee985f901..bebefc414c 100644
--- a/monitoring/src/get_resource.php
+++ b/monitoring/src/get_resource.php
@@ -35,7 +35,7 @@
* @param string $projectId Your project ID
* @param string $resourceType The resource type of the monitored resource.
*/
-function get_resource($projectId, $resourceType)
+function get_resource($projectId, $resourceType): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/get_uptime_check.php b/monitoring/src/get_uptime_check.php
index 6c3f8a0aa9..0f84b57b8a 100644
--- a/monitoring/src/get_uptime_check.php
+++ b/monitoring/src/get_uptime_check.php
@@ -35,7 +35,7 @@
* @param string $projectId Your project ID
* @param string $configName
*/
-function get_uptime_check($projectId, $configName)
+function get_uptime_check($projectId, $configName): void
{
$uptimeCheckClient = new UptimeCheckServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/list_descriptors.php b/monitoring/src/list_descriptors.php
index 075639344d..61338dbeda 100644
--- a/monitoring/src/list_descriptors.php
+++ b/monitoring/src/list_descriptors.php
@@ -34,7 +34,7 @@
*
* @param string $projectId Your project ID
*/
-function list_descriptors($projectId)
+function list_descriptors($projectId): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/list_resources.php b/monitoring/src/list_resources.php
index ef05535151..c86824471d 100644
--- a/monitoring/src/list_resources.php
+++ b/monitoring/src/list_resources.php
@@ -34,7 +34,7 @@
*
* @param string $projectId Your project ID
*/
-function list_resources($projectId)
+function list_resources($projectId): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/monitoring/src/list_uptime_check_ips.php b/monitoring/src/list_uptime_check_ips.php
index b8a74c0f0f..4a852beeb9 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 2c0e2e9f1b..cd78fac0fd 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 136878de6c..38454f7824 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 bfca73ea0d..c6fe057f85 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 66a9f76fae..0e77166ea9 100644
--- a/monitoring/src/read_timeseries_reduce.php
+++ b/monitoring/src/read_timeseries_reduce.php
@@ -41,7 +41,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 5427e7377f..e5aee9a98b 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 e69cc6206d..a981418deb 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/monitoring/src/write_timeseries.php b/monitoring/src/write_timeseries.php
index 3c0a854976..6631d3dd68 100644
--- a/monitoring/src/write_timeseries.php
+++ b/monitoring/src/write_timeseries.php
@@ -41,7 +41,7 @@
*
* @param string $projectId Your project ID
*/
-function write_timeseries($projectId)
+function write_timeseries($projectId): void
{
$metrics = new MetricServiceClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/create_avro_schema.php b/pubsub/api/src/create_avro_schema.php
index 2955e6513d..6388e238fc 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_proto_schema.php b/pubsub/api/src/create_proto_schema.php
index b907a7b0b8..cf77503549 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.
@@ -33,14 +32,14 @@
* @param string $schemaId
* @param string $protoFile
*/
-function create_proto_schema($projectId, $schemaId, $protoFile)
+function create_proto_schema($projectId, $schemaId, $protoFile): void
{
$pubsub = new PubSubClient([
'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_push_subscription.php b/pubsub/api/src/create_push_subscription.php
index 037d2bbae8..8034a890b1 100644
--- a/pubsub/api/src/create_push_subscription.php
+++ b/pubsub/api/src/create_push_subscription.php
@@ -34,7 +34,7 @@
* @param string $subscriptionName The Pub/Sub subscription name.
* @param string $endpoint The endpoint for the push subscription.
*/
-function create_push_subscription($projectId, $topicName, $subscriptionName, $endpoint)
+function create_push_subscription($projectId, $topicName, $subscriptionName, $endpoint): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/create_subscription.php b/pubsub/api/src/create_subscription.php
index 4bf8bb0df9..d107de2433 100644
--- a/pubsub/api/src/create_subscription.php
+++ b/pubsub/api/src/create_subscription.php
@@ -33,7 +33,7 @@
* @param string $topicName The Pub/Sub topic name.
* @param string $subscriptionName The Pub/Sub subscription name.
*/
-function create_subscription($projectId, $topicName, $subscriptionName)
+function create_subscription($projectId, $topicName, $subscriptionName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/create_subscription_with_filter.php b/pubsub/api/src/create_subscription_with_filter.php
index d59e6d2966..da7885d3c8 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/create_topic.php b/pubsub/api/src/create_topic.php
index adf5b24de0..ad9a392ee5 100644
--- a/pubsub/api/src/create_topic.php
+++ b/pubsub/api/src/create_topic.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $topicName The Pub/Sub topic name.
*/
-function create_topic($projectId, $topicName)
+function create_topic($projectId, $topicName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/create_topic_with_schema.php b/pubsub/api/src/create_topic_with_schema.php
index 482b7c7eae..998e591e0d 100644
--- a/pubsub/api/src/create_topic_with_schema.php
+++ b/pubsub/api/src/create_topic_with_schema.php
@@ -34,7 +34,7 @@
* @param string $schemaId
* @param string $encoding
*/
-function create_topic_with_schema($projectId, $topicId, $schemaId, $encoding)
+function create_topic_with_schema($projectId, $topicId, $schemaId, $encoding): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/dead_letter_create_subscription.php b/pubsub/api/src/dead_letter_create_subscription.php
index d18f2a4400..822bb7f315 100644
--- a/pubsub/api/src/dead_letter_create_subscription.php
+++ b/pubsub/api/src/dead_letter_create_subscription.php
@@ -34,7 +34,7 @@
* @param string $subscriptionName The Pub/Sub subscription name.
* @param string $deadLetterTopicName The Pub/Sub topic to use for dead letter policy.
*/
-function dead_letter_create_subscription($projectId, $topicName, $subscriptionName, $deadLetterTopicName)
+function dead_letter_create_subscription($projectId, $topicName, $subscriptionName, $deadLetterTopicName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/dead_letter_delivery_attempt.php b/pubsub/api/src/dead_letter_delivery_attempt.php
index b9adc7e071..eb0bb2b705 100644
--- a/pubsub/api/src/dead_letter_delivery_attempt.php
+++ b/pubsub/api/src/dead_letter_delivery_attempt.php
@@ -35,7 +35,7 @@
* @param string $subscriptionName The Pub/Sub subscription name.
* @param string $message The contents of a pubsub message data field.
*/
-function dead_letter_delivery_attempt($projectId, $topicName, $subscriptionName, $message)
+function dead_letter_delivery_attempt($projectId, $topicName, $subscriptionName, $message): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/dead_letter_remove.php b/pubsub/api/src/dead_letter_remove.php
index a947836950..caa6046313 100644
--- a/pubsub/api/src/dead_letter_remove.php
+++ b/pubsub/api/src/dead_letter_remove.php
@@ -33,7 +33,7 @@
* @param string $topicName The Pub/Sub topic name.
* @param string $subscriptionName The Pub/Sub subscription name.
*/
-function dead_letter_remove($projectId, $topicName, $subscriptionName)
+function dead_letter_remove($projectId, $topicName, $subscriptionName): 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 6293471a0f..dd8999ade5 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/delete_schema.php b/pubsub/api/src/delete_schema.php
index ea14d258c1..c8da1e22c0 100644
--- a/pubsub/api/src/delete_schema.php
+++ b/pubsub/api/src/delete_schema.php
@@ -31,7 +31,7 @@
* @param string $projectId
* @param string $schemaId
*/
-function delete_schema($projectId, $schemaId)
+function delete_schema($projectId, $schemaId): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/delete_subscription.php b/pubsub/api/src/delete_subscription.php
index 1bd1227a70..7985d8de1f 100644
--- a/pubsub/api/src/delete_subscription.php
+++ b/pubsub/api/src/delete_subscription.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $subscriptionName The Pub/Sub subscription name.
*/
-function delete_subscription($projectId, $subscriptionName)
+function delete_subscription($projectId, $subscriptionName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/delete_topic.php b/pubsub/api/src/delete_topic.php
index 3a0fff976a..75a8c26341 100644
--- a/pubsub/api/src/delete_topic.php
+++ b/pubsub/api/src/delete_topic.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $topicName The Pub/Sub topic name.
*/
-function delete_topic($projectId, $topicName)
+function delete_topic($projectId, $topicName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/detach_subscription.php b/pubsub/api/src/detach_subscription.php
index 2c6ac5d85f..37e568eb8e 100644
--- a/pubsub/api/src/detach_subscription.php
+++ b/pubsub/api/src/detach_subscription.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $subscriptionName The Pub/Sub subscription name.
*/
-function detach_subscription($projectId, $subscriptionName)
+function detach_subscription($projectId, $subscriptionName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/get_schema.php b/pubsub/api/src/get_schema.php
index 9adb1e15c9..956ecac034 100644
--- a/pubsub/api/src/get_schema.php
+++ b/pubsub/api/src/get_schema.php
@@ -31,7 +31,7 @@
* @param string $projectId
* @param string $schemaId
*/
-function get_schema($projectId, $schemaId)
+function get_schema($projectId, $schemaId): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/get_subscription_policy.php b/pubsub/api/src/get_subscription_policy.php
index 11730a75ee..fb77ab20cf 100644
--- a/pubsub/api/src/get_subscription_policy.php
+++ b/pubsub/api/src/get_subscription_policy.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $subscriptionName The Pub/Sub subscription name.
*/
-function get_subscription_policy($projectId, $subscriptionName)
+function get_subscription_policy($projectId, $subscriptionName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/get_topic_policy.php b/pubsub/api/src/get_topic_policy.php
index 186cd052a2..faa690dbf8 100644
--- a/pubsub/api/src/get_topic_policy.php
+++ b/pubsub/api/src/get_topic_policy.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $topicName The Pub/Sub topic name.
*/
-function get_topic_policy($projectId, $topicName)
+function get_topic_policy($projectId, $topicName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/list_schemas.php b/pubsub/api/src/list_schemas.php
index 061e572921..011dd30dff 100644
--- a/pubsub/api/src/list_schemas.php
+++ b/pubsub/api/src/list_schemas.php
@@ -30,7 +30,7 @@
*
* @param string $projectId
*/
-function list_schemas($projectId)
+function list_schemas($projectId): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/list_subscriptions.php b/pubsub/api/src/list_subscriptions.php
index 94ae8234a3..70824e4feb 100644
--- a/pubsub/api/src/list_subscriptions.php
+++ b/pubsub/api/src/list_subscriptions.php
@@ -31,7 +31,7 @@
*
* @param string $projectId The Google project ID.
*/
-function list_subscriptions($projectId)
+function list_subscriptions($projectId): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/list_topics.php b/pubsub/api/src/list_topics.php
index be679cb3ce..da49007f27 100644
--- a/pubsub/api/src/list_topics.php
+++ b/pubsub/api/src/list_topics.php
@@ -31,7 +31,7 @@
*
* @param string $projectId The Google project ID.
*/
-function list_topics($projectId)
+function list_topics($projectId): 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 5015453f9c..387f5544f7 100644
--- a/pubsub/api/src/publish_avro_records.php
+++ b/pubsub/api/src/publish_avro_records.php
@@ -39,15 +39,14 @@
* @param string $projectId
* @param string $topicId
* @param string $definitionFile
- * @return void
*/
-function publish_avro_records($projectId, $topicId, $definitionFile)
+function publish_avro_records($projectId, $topicId, $definitionFile): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
- $definition = file_get_contents($definitionFile);
+ $definition = (string) file_get_contents($definitionFile);
$messageData = [
'name' => 'Alaska',
diff --git a/pubsub/api/src/publish_message.php b/pubsub/api/src/publish_message.php
index 4eca7bb141..e748c62af7 100644
--- a/pubsub/api/src/publish_message.php
+++ b/pubsub/api/src/publish_message.php
@@ -35,7 +35,7 @@
* @param string $topicName The Pub/Sub topic name.
* @param string $message The message to publish.
*/
-function publish_message($projectId, $topicName, $message)
+function publish_message($projectId, $topicName, $message): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/publish_message_batch.php b/pubsub/api/src/publish_message_batch.php
index 946ff1e8fb..af5bc14b35 100644
--- a/pubsub/api/src/publish_message_batch.php
+++ b/pubsub/api/src/publish_message_batch.php
@@ -38,7 +38,7 @@
* @param string $topicName The Pub/Sub topic name.
* @param string $message The message to publish.
*/
-function publish_message_batch($projectId, $topicName, $message)
+function publish_message_batch($projectId, $topicName, $message): void
{
// Check if the batch daemon is running.
if (getenv('IS_BATCH_DAEMON_RUNNING') !== 'true') {
diff --git a/pubsub/api/src/publish_proto_messages.php b/pubsub/api/src/publish_proto_messages.php
index be53a6a1b1..65b8863d00 100644
--- a/pubsub/api/src/publish_proto_messages.php
+++ b/pubsub/api/src/publish_proto_messages.php
@@ -50,7 +50,7 @@
* @param string $topicId
* @return void
*/
-function publish_proto_messages($projectId, $topicId)
+function publish_proto_messages($projectId, $topicId): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/pubsub_client.php b/pubsub/api/src/pubsub_client.php
index 26e7c610d2..a3a869f801 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/pubsub/api/src/pull_messages.php b/pubsub/api/src/pull_messages.php
index 36abed9c55..5041cac6fd 100644
--- a/pubsub/api/src/pull_messages.php
+++ b/pubsub/api/src/pull_messages.php
@@ -33,7 +33,7 @@
* @param string $projectId The Google project ID.
* @param string $subscriptionName The Pub/Sub subscription name.
*/
-function pull_messages($projectId, $subscriptionName)
+function pull_messages($projectId, $subscriptionName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/set_subscription_policy.php b/pubsub/api/src/set_subscription_policy.php
index 7043145cfa..23a5d1f976 100644
--- a/pubsub/api/src/set_subscription_policy.php
+++ b/pubsub/api/src/set_subscription_policy.php
@@ -33,7 +33,7 @@
* @param string $subscriptionName The Pub/Sub subscription name.
* @param string $userEmail The user email to add to the policy.
*/
-function set_subscription_policy($projectId, $subscriptionName, $userEmail)
+function set_subscription_policy($projectId, $subscriptionName, $userEmail): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/set_topic_policy.php b/pubsub/api/src/set_topic_policy.php
index b8fe331d66..d27dfb17d3 100644
--- a/pubsub/api/src/set_topic_policy.php
+++ b/pubsub/api/src/set_topic_policy.php
@@ -33,7 +33,7 @@
* @param string $topicName The Pub/Sub topic name.
* @param string $userEmail The user email to add to the policy.
*/
-function set_topic_policy($projectId, $topicName, $userEmail)
+function set_topic_policy($projectId, $topicName, $userEmail): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/subscribe_avro_records.php b/pubsub/api/src/subscribe_avro_records.php
index e56def3cdf..44d266bdbd 100644
--- a/pubsub/api/src/subscribe_avro_records.php
+++ b/pubsub/api/src/subscribe_avro_records.php
@@ -31,7 +31,7 @@
* @param string $projectId
* @param string $subscriptionId
*/
-function subscribe_avro_records($projectId, $subscriptionId)
+function subscribe_avro_records($projectId, $subscriptionId): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/subscribe_proto_messages.php b/pubsub/api/src/subscribe_proto_messages.php
index d6e0aa701c..0615304f27 100644
--- a/pubsub/api/src/subscribe_proto_messages.php
+++ b/pubsub/api/src/subscribe_proto_messages.php
@@ -46,7 +46,7 @@
* @param string $projectId
* @param string $subscriptionId
*/
-function subscribe_proto_messages($projectId, $subscriptionId)
+function subscribe_proto_messages($projectId, $subscriptionId): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/test_subscription_permissions.php b/pubsub/api/src/test_subscription_permissions.php
index 6738f0c18d..9cec732e6b 100644
--- a/pubsub/api/src/test_subscription_permissions.php
+++ b/pubsub/api/src/test_subscription_permissions.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $subscriptionName The Pub/Sub subscription name.
*/
-function test_subscription_permissions($projectId, $subscriptionName)
+function test_subscription_permissions($projectId, $subscriptionName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/pubsub/api/src/test_topic_permissions.php b/pubsub/api/src/test_topic_permissions.php
index 5a5c1f21d0..53b6d44c73 100644
--- a/pubsub/api/src/test_topic_permissions.php
+++ b/pubsub/api/src/test_topic_permissions.php
@@ -32,7 +32,7 @@
* @param string $projectId The Google project ID.
* @param string $topicName The Pub/Sub topic name.
*/
-function test_topic_permissions($projectId, $topicName)
+function test_topic_permissions($projectId, $topicName): void
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
diff --git a/spanner/src/add_column.php b/spanner/src/add_column.php
index 2a3cf41422..3e80c7bf73 100644
--- a/spanner/src/add_column.php
+++ b/spanner/src/add_column.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function add_column($instanceId, $databaseId)
+function add_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/add_json_column.php b/spanner/src/add_json_column.php
index bd5b320fb3..d9b69a5ded 100644
--- a/spanner/src/add_json_column.php
+++ b/spanner/src/add_json_column.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function add_json_column($instanceId, $databaseId)
+function add_json_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/add_numeric_column.php b/spanner/src/add_numeric_column.php
index 0a9ca1e1b2..c632b27621 100644
--- a/spanner/src/add_numeric_column.php
+++ b/spanner/src/add_numeric_column.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function add_numeric_column($instanceId, $databaseId)
+function add_numeric_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/add_timestamp_column.php b/spanner/src/add_timestamp_column.php
index fa40a0f0e1..f6ce815c4f 100644
--- a/spanner/src/add_timestamp_column.php
+++ b/spanner/src/add_timestamp_column.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function add_timestamp_column($instanceId, $databaseId)
+function add_timestamp_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/batch_query_data.php b/spanner/src/batch_query_data.php
index 2ae8a1d69c..5d6a98e6ea 100644
--- a/spanner/src/batch_query_data.php
+++ b/spanner/src/batch_query_data.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function batch_query_data($instanceId, $databaseId)
+function batch_query_data($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$batch = $spanner->batch($instanceId, $databaseId);
diff --git a/spanner/src/cancel_backup.php b/spanner/src/cancel_backup.php
index 0173ee7219..24df9c8d01 100644
--- a/spanner/src/cancel_backup.php
+++ b/spanner/src/cancel_backup.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function cancel_backup($instanceId, $databaseId)
+function cancel_backup($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/copy_backup.php b/spanner/src/copy_backup.php
index 7e47a2f334..3047abeef1 100644
--- a/spanner/src/copy_backup.php
+++ b/spanner/src/copy_backup.php
@@ -39,8 +39,12 @@
* @param string $sourceInstanceId The Spanner instance ID of the source backup.
* @param string $sourceBackupId The Spanner backup ID of the source.
*/
-function copy_backup($destInstanceId, $destBackupId, $sourceInstanceId, $sourceBackupId)
-{
+function copy_backup(
+ string $destInstanceId,
+ string $destBackupId,
+ string $sourceInstanceId,
+ string $sourceBackupId
+): void {
$spanner = new SpannerClient();
$destInstance = $spanner->instance($destInstanceId);
diff --git a/spanner/src/create_backup.php b/spanner/src/create_backup.php
index 6386153b59..5e1c7dc85b 100644
--- a/spanner/src/create_backup.php
+++ b/spanner/src/create_backup.php
@@ -39,7 +39,7 @@
* @param string $backupId The Spanner backup ID.
* @param string $versionTime The version of the database to backup.
*/
-function create_backup($instanceId, $databaseId, $backupId, $versionTime)
+function create_backup($instanceId, $databaseId, $backupId, $versionTime): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/create_backup_with_encryption_key.php b/spanner/src/create_backup_with_encryption_key.php
index 000b34e859..0d1ad4adf4 100644
--- a/spanner/src/create_backup_with_encryption_key.php
+++ b/spanner/src/create_backup_with_encryption_key.php
@@ -40,7 +40,7 @@
* @param string $backupId The Spanner backup ID.
* @param string $kmsKeyName The KMS key used for encryption.
*/
-function create_backup_with_encryption_key($instanceId, $databaseId, $backupId, $kmsKeyName)
+function create_backup_with_encryption_key($instanceId, $databaseId, $backupId, $kmsKeyName): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/create_client_with_query_options.php b/spanner/src/create_client_with_query_options.php
index 448540348a..47ee96ff40 100644
--- a/spanner/src/create_client_with_query_options.php
+++ b/spanner/src/create_client_with_query_options.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function create_client_with_query_options($instanceId, $databaseId)
+function create_client_with_query_options($instanceId, $databaseId): void
{
$spanner = new SpannerClient([
'queryOptions' => [
diff --git a/spanner/src/create_database.php b/spanner/src/create_database.php
index d755e1f564..7bc2fdc935 100644
--- a/spanner/src/create_database.php
+++ b/spanner/src/create_database.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function create_database($instanceId, $databaseId)
+function create_database($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/create_database_with_default_leader.php b/spanner/src/create_database_with_default_leader.php
index b503a59e5f..63aa0ddfc2 100644
--- a/spanner/src/create_database_with_default_leader.php
+++ b/spanner/src/create_database_with_default_leader.php
@@ -37,7 +37,7 @@
* @param string $databaseId The Spanner database ID.
* @param string $defaultLeader The leader instance configuration used by default.
*/
-function create_database_with_default_leader($instanceId, $databaseId, $defaultLeader)
+function create_database_with_default_leader($instanceId, $databaseId, $defaultLeader): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/create_database_with_encryption_key.php b/spanner/src/create_database_with_encryption_key.php
index 9448630e31..a37386a3cd 100644
--- a/spanner/src/create_database_with_encryption_key.php
+++ b/spanner/src/create_database_with_encryption_key.php
@@ -37,7 +37,7 @@
* @param string $databaseId The Spanner database ID.
* @param string $kmsKeyName The KMS key used for encryption.
*/
-function create_database_with_encryption_key($instanceId, $databaseId, $kmsKeyName)
+function create_database_with_encryption_key($instanceId, $databaseId, $kmsKeyName): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/create_database_with_version_retention_period.php b/spanner/src/create_database_with_version_retention_period.php
index 06c89fc04d..a1209d8156 100644
--- a/spanner/src/create_database_with_version_retention_period.php
+++ b/spanner/src/create_database_with_version_retention_period.php
@@ -37,7 +37,7 @@
* @param string $databaseId The Spanner database ID.
* @param string $retentionPeriod The data retention period for the database.
*/
-function create_database_with_version_retention_period($instanceId, $databaseId, $retentionPeriod)
+function create_database_with_version_retention_period($instanceId, $databaseId, $retentionPeriod): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/create_index.php b/spanner/src/create_index.php
index 9fcbb50223..7c0b3139a8 100644
--- a/spanner/src/create_index.php
+++ b/spanner/src/create_index.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function create_index($instanceId, $databaseId)
+function create_index($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/create_instance.php b/spanner/src/create_instance.php
index 4ce8bd4550..887647b8f3 100644
--- a/spanner/src/create_instance.php
+++ b/spanner/src/create_instance.php
@@ -35,7 +35,7 @@
*
* @param string $instanceId The Spanner instance ID.
*/
-function create_instance($instanceId)
+function create_instance($instanceId): void
{
$spanner = new SpannerClient();
$instanceConfig = $spanner->instanceConfiguration(
diff --git a/spanner/src/create_storing_index.php b/spanner/src/create_storing_index.php
index 759f86232a..0058ffb853 100644
--- a/spanner/src/create_storing_index.php
+++ b/spanner/src/create_storing_index.php
@@ -47,7 +47,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function create_storing_index($instanceId, $databaseId)
+function create_storing_index($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/create_table_with_datatypes.php b/spanner/src/create_table_with_datatypes.php
index d78c831113..9f435bca7b 100644
--- a/spanner/src/create_table_with_datatypes.php
+++ b/spanner/src/create_table_with_datatypes.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function create_table_with_datatypes($instanceId, $databaseId)
+function create_table_with_datatypes($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/create_table_with_timestamp_column.php b/spanner/src/create_table_with_timestamp_column.php
index 6b44b98f41..b04c549bfe 100644
--- a/spanner/src/create_table_with_timestamp_column.php
+++ b/spanner/src/create_table_with_timestamp_column.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function create_table_with_timestamp_column($instanceId, $databaseId)
+function create_table_with_timestamp_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/delete_backup.php b/spanner/src/delete_backup.php
index b8a881e18d..fbfb7ebac2 100644
--- a/spanner/src/delete_backup.php
+++ b/spanner/src/delete_backup.php
@@ -35,7 +35,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $backupId The Spanner backup ID.
*/
-function delete_backup($instanceId, $backupId)
+function delete_backup($instanceId, $backupId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/delete_data.php b/spanner/src/delete_data.php
index d9ed65db44..2bcf2b4a14 100644
--- a/spanner/src/delete_data.php
+++ b/spanner/src/delete_data.php
@@ -35,7 +35,7 @@
* @param string $databaseId The Spanner database ID.
* @throws GoogleException
*/
-function delete_data($instanceId, $databaseId)
+function delete_data($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/delete_data_with_dml.php b/spanner/src/delete_data_with_dml.php
index 1862b8758f..752a28260a 100644
--- a/spanner/src/delete_data_with_dml.php
+++ b/spanner/src/delete_data_with_dml.php
@@ -33,13 +33,13 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function delete_data_with_dml($instanceId, $databaseId)
+function delete_data_with_dml($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$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/delete_data_with_partitioned_dml.php b/spanner/src/delete_data_with_partitioned_dml.php
index 075bd57cb5..36d26609b9 100644
--- a/spanner/src/delete_data_with_partitioned_dml.php
+++ b/spanner/src/delete_data_with_partitioned_dml.php
@@ -43,7 +43,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function delete_data_with_partitioned_dml($instanceId, $databaseId)
+function delete_data_with_partitioned_dml($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/get_commit_stats.php b/spanner/src/get_commit_stats.php
index e92e7fc636..d1799e3f8b 100644
--- a/spanner/src/get_commit_stats.php
+++ b/spanner/src/get_commit_stats.php
@@ -37,13 +37,13 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function get_commit_stats($instanceId, $databaseId)
+function get_commit_stats($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$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/get_database_ddl.php b/spanner/src/get_database_ddl.php
index 5645a44613..45de3063f2 100644
--- a/spanner/src/get_database_ddl.php
+++ b/spanner/src/get_database_ddl.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function get_database_ddl($instanceId, $databaseId)
+function get_database_ddl($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/get_instance_config.php b/spanner/src/get_instance_config.php
index 7ef49a78bc..da0b187bb9 100644
--- a/spanner/src/get_instance_config.php
+++ b/spanner/src/get_instance_config.php
@@ -31,7 +31,7 @@
*
* @param string $instanceConfig The name of the instance configuration.
*/
-function get_instance_config($instanceConfig)
+function get_instance_config($instanceConfig): void
{
$spanner = new SpannerClient();
$config = $spanner->instanceConfiguration($instanceConfig);
diff --git a/spanner/src/insert_data.php b/spanner/src/insert_data.php
index 7351d2f602..b4932ac7e6 100644
--- a/spanner/src/insert_data.php
+++ b/spanner/src/insert_data.php
@@ -39,7 +39,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function insert_data($instanceId, $databaseId)
+function insert_data($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/insert_data_with_datatypes.php b/spanner/src/insert_data_with_datatypes.php
index 1ad24845e5..bd16a26ce6 100644
--- a/spanner/src/insert_data_with_datatypes.php
+++ b/spanner/src/insert_data_with_datatypes.php
@@ -39,7 +39,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function insert_data_with_datatypes($instanceId, $databaseId)
+function insert_data_with_datatypes($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/insert_data_with_dml.php b/spanner/src/insert_data_with_dml.php
index fa4b0f5a88..2d7ecf47e4 100644
--- a/spanner/src/insert_data_with_dml.php
+++ b/spanner/src/insert_data_with_dml.php
@@ -40,13 +40,13 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function insert_data_with_dml($instanceId, $databaseId)
+function insert_data_with_dml(string $instanceId, string $databaseId): void
{
$spanner = new SpannerClient();
$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/insert_data_with_timestamp_column.php b/spanner/src/insert_data_with_timestamp_column.php
index 04be9e10c0..399ba615e7 100644
--- a/spanner/src/insert_data_with_timestamp_column.php
+++ b/spanner/src/insert_data_with_timestamp_column.php
@@ -39,7 +39,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function insert_data_with_timestamp_column($instanceId, $databaseId)
+function insert_data_with_timestamp_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/insert_struct_data.php b/spanner/src/insert_struct_data.php
index 30ad11c0d3..05f2ff9392 100644
--- a/spanner/src/insert_struct_data.php
+++ b/spanner/src/insert_struct_data.php
@@ -39,7 +39,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function insert_struct_data($instanceId, $databaseId)
+function insert_struct_data(string $instanceId, string $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/list_backups.php b/spanner/src/list_backups.php
index 6250b76405..2a3a42cc55 100644
--- a/spanner/src/list_backups.php
+++ b/spanner/src/list_backups.php
@@ -35,7 +35,7 @@
*
* @param string $instanceId The Spanner instance ID.
*/
-function list_backups($instanceId)
+function list_backups($instanceId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/list_database_operations.php b/spanner/src/list_database_operations.php
index 7d74bc2e24..e8dc845162 100644
--- a/spanner/src/list_database_operations.php
+++ b/spanner/src/list_database_operations.php
@@ -35,7 +35,7 @@
*
* @param string $instanceId The Spanner instance ID.
*/
-function list_database_operations($instanceId)
+function list_database_operations($instanceId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/list_databases.php b/spanner/src/list_databases.php
index 17dd57a144..abfe3abf2e 100644
--- a/spanner/src/list_databases.php
+++ b/spanner/src/list_databases.php
@@ -33,9 +33,9 @@
* list_databases($instanceId);
* ```
*
- * @param $instanceId The Spanner instance ID.
+ * @param string $instanceId The Spanner instance ID.
*/
-function list_databases($instanceId)
+function list_databases(string $instanceId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/list_instance_configs.php b/spanner/src/list_instance_configs.php
index e6ba90d0c0..8528f2bd05 100644
--- a/spanner/src/list_instance_configs.php
+++ b/spanner/src/list_instance_configs.php
@@ -33,7 +33,7 @@
* list_instance_configs();
* ```
*/
-function list_instance_configs()
+function list_instance_configs(): void
{
$spanner = new SpannerClient();
foreach ($spanner->instanceConfigurations() as $config) {
diff --git a/spanner/src/query_data.php b/spanner/src/query_data.php
index 5099d1a997..c525a4d2db 100644
--- a/spanner/src/query_data.php
+++ b/spanner/src/query_data.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data($instanceId, $databaseId)
+function query_data($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_array_of_struct.php b/spanner/src/query_data_with_array_of_struct.php
index abc6604dc7..34511c3a8a 100644
--- a/spanner/src/query_data_with_array_of_struct.php
+++ b/spanner/src/query_data_with_array_of_struct.php
@@ -39,7 +39,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_array_of_struct($instanceId, $databaseId)
+function query_data_with_array_of_struct($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_array_parameter.php b/spanner/src/query_data_with_array_parameter.php
index e4f36411c5..c0b40c47f6 100644
--- a/spanner/src/query_data_with_array_parameter.php
+++ b/spanner/src/query_data_with_array_parameter.php
@@ -38,7 +38,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_array_parameter($instanceId, $databaseId)
+function query_data_with_array_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_bool_parameter.php b/spanner/src/query_data_with_bool_parameter.php
index 2ecec63ae1..762206f5b9 100644
--- a/spanner/src/query_data_with_bool_parameter.php
+++ b/spanner/src/query_data_with_bool_parameter.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_bool_parameter($instanceId, $databaseId)
+function query_data_with_bool_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_bytes_parameter.php b/spanner/src/query_data_with_bytes_parameter.php
index 71704e186e..7e653ba17f 100644
--- a/spanner/src/query_data_with_bytes_parameter.php
+++ b/spanner/src/query_data_with_bytes_parameter.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_bytes_parameter($instanceId, $databaseId)
+function query_data_with_bytes_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_date_parameter.php b/spanner/src/query_data_with_date_parameter.php
index d0cd972caf..5ea857c5ec 100644
--- a/spanner/src/query_data_with_date_parameter.php
+++ b/spanner/src/query_data_with_date_parameter.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_date_parameter($instanceId, $databaseId)
+function query_data_with_date_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_float_parameter.php b/spanner/src/query_data_with_float_parameter.php
index 7c5d07cbbe..a6ae68666f 100644
--- a/spanner/src/query_data_with_float_parameter.php
+++ b/spanner/src/query_data_with_float_parameter.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_float_parameter($instanceId, $databaseId)
+function query_data_with_float_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_index.php b/spanner/src/query_data_with_index.php
index f3e3629134..cd0b933388 100644
--- a/spanner/src/query_data_with_index.php
+++ b/spanner/src/query_data_with_index.php
@@ -50,7 +50,7 @@ function query_data_with_index(
$databaseId,
$startTitle = 'Aardvark',
$endTitle = 'Goo'
-) {
+): void {
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
$database = $instance->database($databaseId);
diff --git a/spanner/src/query_data_with_int_parameter.php b/spanner/src/query_data_with_int_parameter.php
index b31111b6cc..412aa3980b 100644
--- a/spanner/src/query_data_with_int_parameter.php
+++ b/spanner/src/query_data_with_int_parameter.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_int_parameter($instanceId, $databaseId)
+function query_data_with_int_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_json_parameter.php b/spanner/src/query_data_with_json_parameter.php
index 369a538d07..7bc1d9a910 100644
--- a/spanner/src/query_data_with_json_parameter.php
+++ b/spanner/src/query_data_with_json_parameter.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_json_parameter($instanceId, $databaseId)
+function query_data_with_json_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_nested_struct_field.php b/spanner/src/query_data_with_nested_struct_field.php
index 839c6cc528..70e0a7268f 100644
--- a/spanner/src/query_data_with_nested_struct_field.php
+++ b/spanner/src/query_data_with_nested_struct_field.php
@@ -40,7 +40,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_nested_struct_field($instanceId, $databaseId)
+function query_data_with_nested_struct_field($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_new_column.php b/spanner/src/query_data_with_new_column.php
index 0cba7d6b0f..3e1ff1d7ec 100644
--- a/spanner/src/query_data_with_new_column.php
+++ b/spanner/src/query_data_with_new_column.php
@@ -42,7 +42,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_new_column($instanceId, $databaseId)
+function query_data_with_new_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_numeric_parameter.php b/spanner/src/query_data_with_numeric_parameter.php
index d195186054..d6ace286bf 100644
--- a/spanner/src/query_data_with_numeric_parameter.php
+++ b/spanner/src/query_data_with_numeric_parameter.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_numeric_parameter($instanceId, $databaseId)
+function query_data_with_numeric_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_parameter.php b/spanner/src/query_data_with_parameter.php
index 37a37ae253..4b020e71f2 100644
--- a/spanner/src/query_data_with_parameter.php
+++ b/spanner/src/query_data_with_parameter.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_parameter($instanceId, $databaseId)
+function query_data_with_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_query_options.php b/spanner/src/query_data_with_query_options.php
index 45ea9f1378..d167147586 100644
--- a/spanner/src/query_data_with_query_options.php
+++ b/spanner/src/query_data_with_query_options.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_query_options($instanceId, $databaseId)
+function query_data_with_query_options($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_string_parameter.php b/spanner/src/query_data_with_string_parameter.php
index 8cb9af2f8d..92fb073906 100644
--- a/spanner/src/query_data_with_string_parameter.php
+++ b/spanner/src/query_data_with_string_parameter.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_string_parameter($instanceId, $databaseId)
+function query_data_with_string_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_struct.php b/spanner/src/query_data_with_struct.php
index d1446ad1f6..912648433a 100644
--- a/spanner/src/query_data_with_struct.php
+++ b/spanner/src/query_data_with_struct.php
@@ -38,7 +38,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_struct($instanceId, $databaseId)
+function query_data_with_struct($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_struct_field.php b/spanner/src/query_data_with_struct_field.php
index 9950792df5..64d8d6389c 100644
--- a/spanner/src/query_data_with_struct_field.php
+++ b/spanner/src/query_data_with_struct_field.php
@@ -38,7 +38,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_struct_field($instanceId, $databaseId)
+function query_data_with_struct_field($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_timestamp_column.php b/spanner/src/query_data_with_timestamp_column.php
index ae4ea6091f..1930514a64 100644
--- a/spanner/src/query_data_with_timestamp_column.php
+++ b/spanner/src/query_data_with_timestamp_column.php
@@ -49,7 +49,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_timestamp_column($instanceId, $databaseId)
+function query_data_with_timestamp_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_data_with_timestamp_parameter.php b/spanner/src/query_data_with_timestamp_parameter.php
index 001779e3bb..07f08208f4 100644
--- a/spanner/src/query_data_with_timestamp_parameter.php
+++ b/spanner/src/query_data_with_timestamp_parameter.php
@@ -37,7 +37,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_data_with_timestamp_parameter($instanceId, $databaseId)
+function query_data_with_timestamp_parameter($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/query_information_schema_database_options.php b/spanner/src/query_information_schema_database_options.php
index 74d5fbbfdb..ad9df3facd 100644
--- a/spanner/src/query_information_schema_database_options.php
+++ b/spanner/src/query_information_schema_database_options.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function query_information_schema_database_options($instanceId, $databaseId)
+function query_information_schema_database_options($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/read_data.php b/spanner/src/read_data.php
index d5df827cd5..c24cff64ec 100644
--- a/spanner/src/read_data.php
+++ b/spanner/src/read_data.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function read_data($instanceId, $databaseId)
+function read_data($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/read_data_with_index.php b/spanner/src/read_data_with_index.php
index 0226829fb5..2c92bf549d 100644
--- a/spanner/src/read_data_with_index.php
+++ b/spanner/src/read_data_with_index.php
@@ -43,7 +43,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function read_data_with_index($instanceId, $databaseId)
+function read_data_with_index($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/read_data_with_storing_index.php b/spanner/src/read_data_with_storing_index.php
index 93c190cb77..3907b3f8d4 100644
--- a/spanner/src/read_data_with_storing_index.php
+++ b/spanner/src/read_data_with_storing_index.php
@@ -49,7 +49,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function read_data_with_storing_index($instanceId, $databaseId)
+function read_data_with_storing_index($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/read_only_transaction.php b/spanner/src/read_only_transaction.php
index bc04b0d003..fab0895a56 100644
--- a/spanner/src/read_only_transaction.php
+++ b/spanner/src/read_only_transaction.php
@@ -39,7 +39,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function read_only_transaction($instanceId, $databaseId)
+function read_only_transaction($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/read_stale_data.php b/spanner/src/read_stale_data.php
index f684b1eb95..b14f0706ff 100644
--- a/spanner/src/read_stale_data.php
+++ b/spanner/src/read_stale_data.php
@@ -39,7 +39,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function read_stale_data($instanceId, $databaseId)
+function read_stale_data($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/read_write_transaction.php b/spanner/src/read_write_transaction.php
index 775d81108a..b77283fe77 100644
--- a/spanner/src/read_write_transaction.php
+++ b/spanner/src/read_write_transaction.php
@@ -46,7 +46,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function read_write_transaction($instanceId, $databaseId)
+function read_write_transaction($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/restore_backup.php b/spanner/src/restore_backup.php
index 010c90a976..8427ebdec2 100644
--- a/spanner/src/restore_backup.php
+++ b/spanner/src/restore_backup.php
@@ -36,7 +36,7 @@
* @param string $databaseId The Spanner database ID.
* @param string $backupId The Spanner backup ID.
*/
-function restore_backup($instanceId, $databaseId, $backupId)
+function restore_backup($instanceId, $databaseId, $backupId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/restore_backup_with_encryption_key.php b/spanner/src/restore_backup_with_encryption_key.php
index f45c533187..9b3273197b 100644
--- a/spanner/src/restore_backup_with_encryption_key.php
+++ b/spanner/src/restore_backup_with_encryption_key.php
@@ -38,7 +38,7 @@
* @param string $backupId The Spanner backup ID.
* @param string $kmsKeyName The KMS key used for encryption.
*/
-function restore_backup_with_encryption_key($instanceId, $databaseId, $backupId, $kmsKeyName)
+function restore_backup_with_encryption_key($instanceId, $databaseId, $backupId, $kmsKeyName): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/set_transaction_tag.php b/spanner/src/set_transaction_tag.php
index e087bc7bfd..0f02585071 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_backup.php b/spanner/src/update_backup.php
index a63c647f9b..ad8ddaf61b 100644
--- a/spanner/src/update_backup.php
+++ b/spanner/src/update_backup.php
@@ -36,7 +36,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $backupId The Spanner backup ID.
*/
-function update_backup($instanceId, $backupId)
+function update_backup($instanceId, $backupId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/update_data.php b/spanner/src/update_data.php
index 6024cb1b4c..c239980fa4 100644
--- a/spanner/src/update_data.php
+++ b/spanner/src/update_data.php
@@ -43,7 +43,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function update_data($instanceId, $databaseId)
+function update_data($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/update_data_with_batch_dml.php b/spanner/src/update_data_with_batch_dml.php
index eba07e4308..efe006b8d4 100644
--- a/spanner/src/update_data_with_batch_dml.php
+++ b/spanner/src/update_data_with_batch_dml.php
@@ -44,7 +44,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function update_data_with_batch_dml($instanceId, $databaseId)
+function update_data_with_batch_dml($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/update_data_with_dml.php b/spanner/src/update_data_with_dml.php
index 14eac097f0..b38df63049 100644
--- a/spanner/src/update_data_with_dml.php
+++ b/spanner/src/update_data_with_dml.php
@@ -44,13 +44,13 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function update_data_with_dml($instanceId, $databaseId)
+function update_data_with_dml(string $instanceId, string $databaseId): void
{
$spanner = new SpannerClient();
$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 029765c19f..adb840940a 100644
--- a/spanner/src/update_data_with_dml_structs.php
+++ b/spanner/src/update_data_with_dml_structs.php
@@ -43,13 +43,13 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function update_data_with_dml_structs($instanceId, $databaseId)
+function update_data_with_dml_structs($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$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 8bb476ea23..b61c71ad26 100644
--- a/spanner/src/update_data_with_dml_timestamp.php
+++ b/spanner/src/update_data_with_dml_timestamp.php
@@ -40,13 +40,13 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function update_data_with_dml_timestamp($instanceId, $databaseId)
+function update_data_with_dml_timestamp($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$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/update_data_with_json_column.php b/spanner/src/update_data_with_json_column.php
index fa01681ba1..86e6d3bfb2 100644
--- a/spanner/src/update_data_with_json_column.php
+++ b/spanner/src/update_data_with_json_column.php
@@ -40,7 +40,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function update_data_with_json_column($instanceId, $databaseId)
+function update_data_with_json_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/update_data_with_numeric_column.php b/spanner/src/update_data_with_numeric_column.php
index 86e3d02fa9..1d25f77934 100644
--- a/spanner/src/update_data_with_numeric_column.php
+++ b/spanner/src/update_data_with_numeric_column.php
@@ -40,7 +40,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function update_data_with_numeric_column($instanceId, $databaseId)
+function update_data_with_numeric_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/update_data_with_partitioned_dml.php b/spanner/src/update_data_with_partitioned_dml.php
index d9cd608a7f..6d730092d6 100644
--- a/spanner/src/update_data_with_partitioned_dml.php
+++ b/spanner/src/update_data_with_partitioned_dml.php
@@ -43,7 +43,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function update_data_with_partitioned_dml($instanceId, $databaseId)
+function update_data_with_partitioned_dml($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/update_data_with_timestamp_column.php b/spanner/src/update_data_with_timestamp_column.php
index 6402160a33..c660dddc84 100644
--- a/spanner/src/update_data_with_timestamp_column.php
+++ b/spanner/src/update_data_with_timestamp_column.php
@@ -43,7 +43,7 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function update_data_with_timestamp_column($instanceId, $databaseId)
+function update_data_with_timestamp_column($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/update_database_with_default_leader.php b/spanner/src/update_database_with_default_leader.php
index f9ad762b76..fa4f357544 100644
--- a/spanner/src/update_database_with_default_leader.php
+++ b/spanner/src/update_database_with_default_leader.php
@@ -37,7 +37,7 @@
* @param string $databaseId The Spanner database ID.
* @param string $defaultLeader The leader instance configuration used by default.
*/
-function update_database_with_default_leader($instanceId, $databaseId, $defaultLeader)
+function update_database_with_default_leader($instanceId, $databaseId, $defaultLeader): void
{
$spanner = new SpannerClient();
$instance = $spanner->instance($instanceId);
diff --git a/spanner/src/write_data_with_dml.php b/spanner/src/write_data_with_dml.php
index 0d5abf75d9..7e2014eecb 100644
--- a/spanner/src/write_data_with_dml.php
+++ b/spanner/src/write_data_with_dml.php
@@ -40,13 +40,13 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function write_data_with_dml($instanceId, $databaseId)
+function write_data_with_dml($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$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 8fca2a39e7..ffe7c74183 100644
--- a/spanner/src/write_data_with_dml_transaction.php
+++ b/spanner/src/write_data_with_dml_transaction.php
@@ -45,13 +45,13 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function write_data_with_dml_transaction($instanceId, $databaseId)
+function write_data_with_dml_transaction($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$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 722d35f353..40770b8350 100644
--- a/spanner/src/write_read_with_dml.php
+++ b/spanner/src/write_read_with_dml.php
@@ -40,13 +40,13 @@
* @param string $instanceId The Spanner instance ID.
* @param string $databaseId The Spanner database ID.
*/
-function write_read_with_dml($instanceId, $databaseId)
+function write_read_with_dml($instanceId, $databaseId): void
{
$spanner = new SpannerClient();
$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/speech/src/base64_encode_audio.php b/speech/src/base64_encode_audio.php
index de6b4dc235..28976b58f5 100644
--- a/speech/src/base64_encode_audio.php
+++ b/speech/src/base64_encode_audio.php
@@ -30,7 +30,9 @@
/** Uncomment and populate these variables in your code */
// $audioFile = 'path to an audio file';
-$audioFileResource = fopen($audioFile, 'r');
-$base64Audio = base64_encode(stream_get_contents($audioFileResource));
+if (!$audioFileResource = fopen($audioFile, 'r')) {
+ throw new InvalidArgumentException('unable to open file for reading');
+}
+$base64Audio = base64_encode((string) stream_get_contents($audioFileResource));
print($base64Audio);
# [end base64_audio]
diff --git a/speech/src/profanity_filter.php b/speech/src/profanity_filter.php
index 5430b3a288..9015ec496e 100644
--- a/speech/src/profanity_filter.php
+++ b/speech/src/profanity_filter.php
@@ -37,7 +37,7 @@
$profanityFilter = true;
// get contents of a file into a string
-$content = file_get_contents($audioFile);
+$content = (string) file_get_contents($audioFile);
// set string as audio content
$audio = (new RecognitionAudio())
diff --git a/speech/src/streaming_recognize.php b/speech/src/streaming_recognize.php
index 5207b8218a..1aff410713 100644
--- a/speech/src/streaming_recognize.php
+++ b/speech/src/streaming_recognize.php
@@ -61,7 +61,7 @@
$strm->write($strmReq);
$strmReq = new StreamingRecognizeRequest();
- $content = file_get_contents($audioFile);
+ $content = (string) file_get_contents($audioFile);
$strmReq->setAudioContent($content);
$strm->write($strmReq);
diff --git a/speech/src/transcribe_async.php b/speech/src/transcribe_async.php
index 50b93cae83..0b2e6793f3 100644
--- a/speech/src/transcribe_async.php
+++ b/speech/src/transcribe_async.php
@@ -44,7 +44,7 @@
$languageCode = 'en-US';
// get contents of a file into a string
-$content = file_get_contents($audioFile);
+$content = (string) file_get_contents($audioFile);
// set string as audio content
$audio = (new RecognitionAudio())
diff --git a/speech/src/transcribe_async_words.php b/speech/src/transcribe_async_words.php
index 7ecb1e3dc1..5eb056b209 100644
--- a/speech/src/transcribe_async_words.php
+++ b/speech/src/transcribe_async_words.php
@@ -47,7 +47,7 @@
$enableWordTimeOffsets = true;
// get contents of a file into a string
-$content = file_get_contents($audioFile);
+$content = (string) file_get_contents($audioFile);
// set string as audio content
$audio = (new RecognitionAudio())
diff --git a/speech/src/transcribe_auto_punctuation.php b/speech/src/transcribe_auto_punctuation.php
index 058e801fa5..92081ae55c 100644
--- a/speech/src/transcribe_auto_punctuation.php
+++ b/speech/src/transcribe_auto_punctuation.php
@@ -44,7 +44,7 @@
$languageCode = 'en-US';
// get contents of a file into a string
-$content = file_get_contents($audioFile);
+$content = (string) file_get_contents($audioFile);
// set string as audio content
$audio = (new RecognitionAudio())
diff --git a/speech/src/transcribe_enhanced_model.php b/speech/src/transcribe_enhanced_model.php
index 5fdd6ee3e9..6c35368722 100644
--- a/speech/src/transcribe_enhanced_model.php
+++ b/speech/src/transcribe_enhanced_model.php
@@ -44,7 +44,7 @@
$languageCode = 'en-US';
// get contents of a file into a string
-$content = file_get_contents($audioFile);
+$content = (string) file_get_contents($audioFile);
// set string as audio content
$audio = (new RecognitionAudio())
diff --git a/speech/src/transcribe_model_selection.php b/speech/src/transcribe_model_selection.php
index 39d1401855..5134807e92 100644
--- a/speech/src/transcribe_model_selection.php
+++ b/speech/src/transcribe_model_selection.php
@@ -45,7 +45,7 @@
$languageCode = 'en-US';
// get contents of a file into a string
-$content = file_get_contents($audioFile);
+$content = (string) file_get_contents($audioFile);
// set string as audio content
$audio = (new RecognitionAudio())
diff --git a/speech/src/transcribe_sync.php b/speech/src/transcribe_sync.php
index 0e01cbbe00..273d99fe5e 100644
--- a/speech/src/transcribe_sync.php
+++ b/speech/src/transcribe_sync.php
@@ -44,7 +44,7 @@
$languageCode = 'en-US';
// get contents of a file into a string
-$content = file_get_contents($audioFile);
+$content = (string) file_get_contents($audioFile);
// set string as audio content
$audio = (new RecognitionAudio())
diff --git a/storage/src/activate_hmac_key.php b/storage/src/activate_hmac_key.php
index bd283f99bf..f122fe9e08 100644
--- a/storage/src/activate_hmac_key.php
+++ b/storage/src/activate_hmac_key.php
@@ -32,7 +32,7 @@
* @param string $projectId The ID of your Google Cloud Platform project.
* @param string $accessId Access ID for an inactive HMAC key.
*/
-function activate_hmac_key($projectId, $accessId)
+function activate_hmac_key($projectId, $accessId): void
{
// $projectId = 'my-project-id';
// $accessId = 'GOOG0234230X00';
diff --git a/storage/src/add_bucket_acl.php b/storage/src/add_bucket_acl.php
index 63555de5eb..f69eed139b 100644
--- a/storage/src/add_bucket_acl.php
+++ b/storage/src/add_bucket_acl.php
@@ -33,7 +33,7 @@
* @param string $entity The entity for which to update access controls.
* @param string $role The permissions to add for the specified entity.
*/
-function add_bucket_acl($bucketName, $entity, $role)
+function add_bucket_acl($bucketName, $entity, $role): void
{
// $bucketName = 'my-bucket';
// $entity = 'user-example@domain.com';
diff --git a/storage/src/add_bucket_conditional_iam_binding.php b/storage/src/add_bucket_conditional_iam_binding.php
index 41097f6e1f..c83e49f941 100644
--- a/storage/src/add_bucket_conditional_iam_binding.php
+++ b/storage/src/add_bucket_conditional_iam_binding.php
@@ -39,7 +39,7 @@
* To see how to express a condition in CEL, visit:
* @see https://cloud.google.com/storage/docs/access-control/iam#conditions.
*/
-function add_bucket_conditional_iam_binding($bucketName, $role, array $members, $title, $description, $expression)
+function add_bucket_conditional_iam_binding($bucketName, $role, array $members, $title, $description, $expression): void
{
// $bucketName = 'my-bucket';
// $role = 'roles/storage.objectViewer';
diff --git a/storage/src/add_bucket_default_acl.php b/storage/src/add_bucket_default_acl.php
index 51730d9a9c..b2dd0d0bcb 100644
--- a/storage/src/add_bucket_default_acl.php
+++ b/storage/src/add_bucket_default_acl.php
@@ -33,7 +33,7 @@
* @param string $entity The entity for which to update access controls.
* @param string $role The permissions to add for the specified entity.
*/
-function add_bucket_default_acl($bucketName, $entity, $role)
+function add_bucket_default_acl($bucketName, $entity, $role): void
{
// $bucketName = 'my-bucket';
// $entity = 'user-example@domain.com';
diff --git a/storage/src/add_bucket_iam_member.php b/storage/src/add_bucket_iam_member.php
index 5bd1217882..9734b160a0 100644
--- a/storage/src/add_bucket_iam_member.php
+++ b/storage/src/add_bucket_iam_member.php
@@ -33,7 +33,7 @@
* @param string $role The role to which the given member should be added.
* @param string[] $members The member(s) to be added to the role.
*/
-function add_bucket_iam_member($bucketName, $role, array $members)
+function add_bucket_iam_member($bucketName, $role, array $members): void
{
// $bucketName = 'my-bucket';
// $role = 'roles/storage.objectViewer';
diff --git a/storage/src/add_bucket_label.php b/storage/src/add_bucket_label.php
index 2e213df282..18a0ca9e4d 100644
--- a/storage/src/add_bucket_label.php
+++ b/storage/src/add_bucket_label.php
@@ -33,7 +33,7 @@
* @param string $labelName The name of the label to add.
* @param string $labelValue The value of the label to add.
*/
-function add_bucket_label($bucketName, $labelName, $labelValue)
+function add_bucket_label($bucketName, $labelName, $labelValue): void
{
// $bucketName = 'my-bucket';
// $labelName = 'label-key-to-add';
diff --git a/storage/src/add_object_acl.php b/storage/src/add_object_acl.php
index e13275db1a..e36fa22536 100644
--- a/storage/src/add_object_acl.php
+++ b/storage/src/add_object_acl.php
@@ -34,7 +34,7 @@
* @param string $entity The entity for which to update access controls.
* @param string $role The permissions to add for the specified entity.
*/
-function add_object_acl($bucketName, $objectName, $entity, $role)
+function add_object_acl($bucketName, $objectName, $entity, $role): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/bucket_delete_default_kms_key.php b/storage/src/bucket_delete_default_kms_key.php
index 7c9a7203d0..af21abdba4 100644
--- a/storage/src/bucket_delete_default_kms_key.php
+++ b/storage/src/bucket_delete_default_kms_key.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function bucket_delete_default_kms_key($bucketName)
+function bucket_delete_default_kms_key($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/change_default_storage_class.php b/storage/src/change_default_storage_class.php
index 97f64cec1a..c31d1d2eca 100644
--- a/storage/src/change_default_storage_class.php
+++ b/storage/src/change_default_storage_class.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function change_default_storage_class($bucketName)
+function change_default_storage_class($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/change_file_storage_class.php b/storage/src/change_file_storage_class.php
index 6a62096757..ef99e7d84c 100644
--- a/storage/src/change_file_storage_class.php
+++ b/storage/src/change_file_storage_class.php
@@ -33,7 +33,7 @@
* @param string $objectName The name of your Cloud Storage object.
* @param string $storageClass The storage class of the new object.
*/
-function change_file_storage_class($bucketName, $objectName, $storageClass)
+function change_file_storage_class($bucketName, $objectName, $storageClass): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/compose_file.php b/storage/src/compose_file.php
index 180cf4a46b..f78166a227 100644
--- a/storage/src/compose_file.php
+++ b/storage/src/compose_file.php
@@ -34,7 +34,7 @@
* @param string $secondObjectName The name of the second GCS object to compose.
* @param string $targetObjectName The name of the object to be created.
*/
-function compose_file($bucketName, $firstObjectName, $secondObjectName, $targetObjectName)
+function compose_file($bucketName, $firstObjectName, $secondObjectName, $targetObjectName): void
{
// $bucketName = 'my-bucket';
// $firstObjectName = 'my-object-1';
diff --git a/storage/src/copy_file_archived_generation.php b/storage/src/copy_file_archived_generation.php
index 0551d0db4b..7152972484 100644
--- a/storage/src/copy_file_archived_generation.php
+++ b/storage/src/copy_file_archived_generation.php
@@ -34,7 +34,7 @@
* @param string $generationToCopy The generation of the object to copy.
* @param string $newObjectName The name of the target object.
*/
-function copy_file_archived_generation($bucketName, $objectToCopy, $generationToCopy, $newObjectName)
+function copy_file_archived_generation($bucketName, $objectToCopy, $generationToCopy, $newObjectName): void
{
// $bucketName = 'my-bucket';
// $objectToCopy = 'my-object';
diff --git a/storage/src/copy_object.php b/storage/src/copy_object.php
index eb58a44a9d..79e5250acd 100644
--- a/storage/src/copy_object.php
+++ b/storage/src/copy_object.php
@@ -34,7 +34,7 @@
* @param string $newBucketName The destination bucket name.
* @param string $newObjectName The destination object name.
*/
-function copy_object($bucketName, $objectName, $newBucketName, $newObjectName)
+function copy_object($bucketName, $objectName, $newBucketName, $newObjectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/cors_configuration.php b/storage/src/cors_configuration.php
index 6c66754051..b89c11e3b0 100644
--- a/storage/src/cors_configuration.php
+++ b/storage/src/cors_configuration.php
@@ -36,7 +36,7 @@
* @param int $maxAgeSeconds The maximum amount of time the browser can make
* requests before it must repeat preflighted requests.
*/
-function cors_configuration($bucketName, $method, $origin, $responseHeader, $maxAgeSeconds)
+function cors_configuration($bucketName, $method, $origin, $responseHeader, $maxAgeSeconds): void
{
// $bucketName = 'my-bucket';
// $method = 'GET';
diff --git a/storage/src/create_bucket.php b/storage/src/create_bucket.php
index 234162b3c3..612adfcf13 100644
--- a/storage/src/create_bucket.php
+++ b/storage/src/create_bucket.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function create_bucket($bucketName)
+function create_bucket($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/create_bucket_class_location.php b/storage/src/create_bucket_class_location.php
index 46eebfe9f4..34315096e1 100644
--- a/storage/src/create_bucket_class_location.php
+++ b/storage/src/create_bucket_class_location.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function create_bucket_class_location($bucketName)
+function create_bucket_class_location($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/create_bucket_turbo_replication.php b/storage/src/create_bucket_turbo_replication.php
index dcfb72ba06..3b7a10da54 100644
--- a/storage/src/create_bucket_turbo_replication.php
+++ b/storage/src/create_bucket_turbo_replication.php
@@ -33,7 +33,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $location The Dual Region location where you want your bucket to reside. (Read more at https://cloud.google.com/storage/docs/locations#location-dr)
*/
-function create_bucket_turbo_replication($bucketName, $location = 'nam4')
+function create_bucket_turbo_replication($bucketName, $location = 'nam4'): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/create_hmac_key.php b/storage/src/create_hmac_key.php
index 15c7b406dd..64aafbaaf3 100644
--- a/storage/src/create_hmac_key.php
+++ b/storage/src/create_hmac_key.php
@@ -32,7 +32,7 @@
* @param string $projectId The ID of your Google Cloud Platform project.
* @param string $serviceAccountEmail Service account email to associate with the new HMAC key.
*/
-function create_hmac_key($projectId, $serviceAccountEmail)
+function create_hmac_key($projectId, $serviceAccountEmail): void
{
// $projectId = 'my-project-id';
// $serviceAccountEmail = 'service-account@iam.gserviceaccount.com';
diff --git a/storage/src/deactivate_hmac_key.php b/storage/src/deactivate_hmac_key.php
index 1c875216b3..be388c0d94 100644
--- a/storage/src/deactivate_hmac_key.php
+++ b/storage/src/deactivate_hmac_key.php
@@ -32,7 +32,7 @@
* @param string $projectId The ID of your Google Cloud Platform project.
* @param string $accessId Access ID for an inactive HMAC key.
*/
-function deactivate_hmac_key($projectId, $accessId)
+function deactivate_hmac_key($projectId, $accessId): void
{
// $projectId = 'my-project-id';
// $accessId = 'GOOG0234230X00';
diff --git a/storage/src/define_bucket_website_configuration.php b/storage/src/define_bucket_website_configuration.php
index 95a399af70..0375f5299c 100644
--- a/storage/src/define_bucket_website_configuration.php
+++ b/storage/src/define_bucket_website_configuration.php
@@ -35,7 +35,7 @@
* @param string $notFoundPageObject the name of an object in the bucket to use
* as the 404 Not Found page.
*/
-function define_bucket_website_configuration($bucketName, $indexPageObject, $notFoundPageObject)
+function define_bucket_website_configuration($bucketName, $indexPageObject, $notFoundPageObject): void
{
// $bucketName = 'my-bucket';
// $indexPageObject = 'index.html';
diff --git a/storage/src/delete_bucket.php b/storage/src/delete_bucket.php
index c54a84e8db..a12bbf48fd 100644
--- a/storage/src/delete_bucket.php
+++ b/storage/src/delete_bucket.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function delete_bucket($bucketName)
+function delete_bucket($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/delete_bucket_acl.php b/storage/src/delete_bucket_acl.php
index cffe59ebfa..af073100ab 100644
--- a/storage/src/delete_bucket_acl.php
+++ b/storage/src/delete_bucket_acl.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $entity The entity for which to update access controls.
*/
-function delete_bucket_acl($bucketName, $entity)
+function delete_bucket_acl($bucketName, $entity): void
{
// $bucketName = 'my-bucket';
// $entity = 'user-example@domain.com';
diff --git a/storage/src/delete_bucket_default_acl.php b/storage/src/delete_bucket_default_acl.php
index 223e49dc44..cab9bc2b5e 100644
--- a/storage/src/delete_bucket_default_acl.php
+++ b/storage/src/delete_bucket_default_acl.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $entity The entity for which to update access controls.
*/
-function delete_bucket_default_acl($bucketName, $entity)
+function delete_bucket_default_acl($bucketName, $entity): void
{
// $bucketName = 'my-bucket';
// $entity = 'user-example@domain.com';
diff --git a/storage/src/delete_file_archived_generation.php b/storage/src/delete_file_archived_generation.php
index 3460de08e6..236e9e681e 100644
--- a/storage/src/delete_file_archived_generation.php
+++ b/storage/src/delete_file_archived_generation.php
@@ -33,7 +33,7 @@
* @param string $objectName The name of your Cloud Storage object.
* @param string $generationToDelete the generation of the object to delete.
*/
-function delete_file_archived_generation($bucketName, $objectName, $generationToDelete)
+function delete_file_archived_generation($bucketName, $objectName, $generationToDelete): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/delete_hmac_key.php b/storage/src/delete_hmac_key.php
index 4ac5cb6e0e..f5871d0360 100644
--- a/storage/src/delete_hmac_key.php
+++ b/storage/src/delete_hmac_key.php
@@ -32,7 +32,7 @@
* @param string $projectId The ID of your Google Cloud Platform project.
* @param string $accessId Access ID for an HMAC key.
*/
-function delete_hmac_key($projectId, $accessId)
+function delete_hmac_key($projectId, $accessId): void
{
// $projectId = 'my-project-id';
// $accessId = 'GOOG0234230X00';
diff --git a/storage/src/delete_object.php b/storage/src/delete_object.php
index fb277a0517..5d07441914 100644
--- a/storage/src/delete_object.php
+++ b/storage/src/delete_object.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function delete_object($bucketName, $objectName)
+function delete_object($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/delete_object_acl.php b/storage/src/delete_object_acl.php
index 3c13a15ac0..87a2077eea 100644
--- a/storage/src/delete_object_acl.php
+++ b/storage/src/delete_object_acl.php
@@ -33,7 +33,7 @@
* @param string $objectName The name of your Cloud Storage object.
* @param string $entity The entity for which to update access controls.
*/
-function delete_object_acl($bucketName, $objectName, $entity)
+function delete_object_acl($bucketName, $objectName, $entity): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/disable_bucket_lifecycle_management.php b/storage/src/disable_bucket_lifecycle_management.php
index 2711aba819..166e534cc5 100644
--- a/storage/src/disable_bucket_lifecycle_management.php
+++ b/storage/src/disable_bucket_lifecycle_management.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function disable_bucket_lifecycle_management($bucketName)
+function disable_bucket_lifecycle_management($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/disable_default_event_based_hold.php b/storage/src/disable_default_event_based_hold.php
index 989e30b63f..3fd46e82df 100644
--- a/storage/src/disable_default_event_based_hold.php
+++ b/storage/src/disable_default_event_based_hold.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function disable_default_event_based_hold($bucketName)
+function disable_default_event_based_hold($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/disable_requester_pays.php b/storage/src/disable_requester_pays.php
index a7938b3259..71abb4425f 100644
--- a/storage/src/disable_requester_pays.php
+++ b/storage/src/disable_requester_pays.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function disable_requester_pays($bucketName)
+function disable_requester_pays($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/disable_uniform_bucket_level_access.php b/storage/src/disable_uniform_bucket_level_access.php
index d7b497f608..7782d04bae 100644
--- a/storage/src/disable_uniform_bucket_level_access.php
+++ b/storage/src/disable_uniform_bucket_level_access.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function disable_uniform_bucket_level_access($bucketName)
+function disable_uniform_bucket_level_access($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/disable_versioning.php b/storage/src/disable_versioning.php
index 66c0f175cc..144db545ca 100644
--- a/storage/src/disable_versioning.php
+++ b/storage/src/disable_versioning.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function disable_versioning($bucketName)
+function disable_versioning($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/download_encrypted_object.php b/storage/src/download_encrypted_object.php
index a77b628c93..68b81db248 100644
--- a/storage/src/download_encrypted_object.php
+++ b/storage/src/download_encrypted_object.php
@@ -35,7 +35,7 @@
* @param string $base64EncryptionKey The base64 encoded encryption key. Should
* be the same key originally used to encrypt the object.
*/
-function download_encrypted_object($bucketName, $objectName, $destination, $base64EncryptionKey)
+function download_encrypted_object($bucketName, $objectName, $destination, $base64EncryptionKey): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/download_file_requester_pays.php b/storage/src/download_file_requester_pays.php
index 670b7da18a..c05b06a6ef 100644
--- a/storage/src/download_file_requester_pays.php
+++ b/storage/src/download_file_requester_pays.php
@@ -34,7 +34,7 @@
* @param string $objectName The name of your Cloud Storage object.
* @param string $destination The local destination to save the object.
*/
-function download_file_requester_pays($projectId, $bucketName, $objectName, $destination)
+function download_file_requester_pays($projectId, $bucketName, $objectName, $destination): void
{
// $projectId = 'my-project-id';
// $bucketName = 'my-bucket';
diff --git a/storage/src/download_object.php b/storage/src/download_object.php
index 0d7f4b43a8..673ae90257 100644
--- a/storage/src/download_object.php
+++ b/storage/src/download_object.php
@@ -34,7 +34,7 @@
* @param string $objectName The name of your Cloud Storage object.
* @param string $destination The local destination to save the object.
*/
-function download_object($bucketName, $objectName, $destination)
+function download_object($bucketName, $objectName, $destination): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/download_public_file.php b/storage/src/download_public_file.php
index 543b219ea6..ac1b58eb66 100644
--- a/storage/src/download_public_file.php
+++ b/storage/src/download_public_file.php
@@ -33,7 +33,7 @@
* @param string $objectName The name of your Cloud Storage object.
* @param string $destination The local destination to save the object.
*/
-function download_public_file($bucketName, $objectName, $destination)
+function download_public_file($bucketName, $objectName, $destination): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/enable_bucket_lifecycle_management.php b/storage/src/enable_bucket_lifecycle_management.php
index f5d1f26055..783f791393 100644
--- a/storage/src/enable_bucket_lifecycle_management.php
+++ b/storage/src/enable_bucket_lifecycle_management.php
@@ -32,7 +32,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function enable_bucket_lifecycle_management($bucketName)
+function enable_bucket_lifecycle_management($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/enable_default_event_based_hold.php b/storage/src/enable_default_event_based_hold.php
index 2d4a8d70b9..ab6d7da449 100644
--- a/storage/src/enable_default_event_based_hold.php
+++ b/storage/src/enable_default_event_based_hold.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function enable_default_event_based_hold($bucketName)
+function enable_default_event_based_hold($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/enable_default_kms_key.php b/storage/src/enable_default_kms_key.php
index cff7f7ff05..e4ecaad87a 100644
--- a/storage/src/enable_default_kms_key.php
+++ b/storage/src/enable_default_kms_key.php
@@ -34,7 +34,7 @@
* Key names are provided in the following format:
* `projects//locations//keyRings//cryptoKeys/`.
*/
-function enable_default_kms_key($bucketName, $kmsKeyName)
+function enable_default_kms_key($bucketName, $kmsKeyName): void
{
// $bucketName = 'my-bucket';
// $kmsKeyName = "";
diff --git a/storage/src/enable_requester_pays.php b/storage/src/enable_requester_pays.php
index 086d83154a..454c847c86 100644
--- a/storage/src/enable_requester_pays.php
+++ b/storage/src/enable_requester_pays.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function enable_requester_pays($bucketName)
+function enable_requester_pays($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/enable_uniform_bucket_level_access.php b/storage/src/enable_uniform_bucket_level_access.php
index 95a6e9ca62..8b7397719d 100644
--- a/storage/src/enable_uniform_bucket_level_access.php
+++ b/storage/src/enable_uniform_bucket_level_access.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function enable_uniform_bucket_level_access($bucketName)
+function enable_uniform_bucket_level_access($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/enable_versioning.php b/storage/src/enable_versioning.php
index de64a7afc3..966864ea2a 100644
--- a/storage/src/enable_versioning.php
+++ b/storage/src/enable_versioning.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function enable_versioning($bucketName)
+function enable_versioning($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/generate_encryption_key.php b/storage/src/generate_encryption_key.php
index 61dea81f07..6aca52a93f 100644
--- a/storage/src/generate_encryption_key.php
+++ b/storage/src/generate_encryption_key.php
@@ -28,7 +28,7 @@
/**
* Generate a base64 encoded encryption key for Google Cloud Storage.
*/
-function generate_encryption_key()
+function generate_encryption_key(): void
{
$key = random_bytes(32);
$encodedKey = base64_encode($key);
diff --git a/storage/src/generate_signed_post_policy_v4.php b/storage/src/generate_signed_post_policy_v4.php
index a59bd3e5b5..4757de8a3f 100644
--- a/storage/src/generate_signed_post_policy_v4.php
+++ b/storage/src/generate_signed_post_policy_v4.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function generate_signed_post_policy_v4($bucketName, $objectName)
+function generate_signed_post_policy_v4($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/generate_v4_post_policy.php b/storage/src/generate_v4_post_policy.php
index ea85e732cd..24a5678c4d 100644
--- a/storage/src/generate_v4_post_policy.php
+++ b/storage/src/generate_v4_post_policy.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function generate_v4_post_policy($bucketName, $objectName)
+function generate_v4_post_policy($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/get_bucket_acl.php b/storage/src/get_bucket_acl.php
index 9ce11e2bdb..a80e16037e 100644
--- a/storage/src/get_bucket_acl.php
+++ b/storage/src/get_bucket_acl.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function get_bucket_acl($bucketName)
+function get_bucket_acl($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/get_bucket_acl_for_entity.php b/storage/src/get_bucket_acl_for_entity.php
index 346fb216ec..01e76c5573 100644
--- a/storage/src/get_bucket_acl_for_entity.php
+++ b/storage/src/get_bucket_acl_for_entity.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $entity The entity for which to update access controls.
*/
-function get_bucket_acl_for_entity($bucketName, $entity)
+function get_bucket_acl_for_entity($bucketName, $entity): void
{
// $bucketName = 'my-bucket';
// $entity = 'user-example@domain.com';
diff --git a/storage/src/get_bucket_default_acl.php b/storage/src/get_bucket_default_acl.php
index 01ef1ed1b6..83620d0f2f 100644
--- a/storage/src/get_bucket_default_acl.php
+++ b/storage/src/get_bucket_default_acl.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function get_bucket_default_acl($bucketName)
+function get_bucket_default_acl($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/get_bucket_default_acl_for_entity.php b/storage/src/get_bucket_default_acl_for_entity.php
index caa6aecf0e..2dc1ec2854 100644
--- a/storage/src/get_bucket_default_acl_for_entity.php
+++ b/storage/src/get_bucket_default_acl_for_entity.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $entity The entity for which to update access controls.
*/
-function get_bucket_default_acl_for_entity($bucketName, $entity)
+function get_bucket_default_acl_for_entity($bucketName, $entity): void
{
// $bucketName = 'my-bucket';
// $entity = 'user-example@domain.com';
diff --git a/storage/src/get_bucket_labels.php b/storage/src/get_bucket_labels.php
index 0592525dab..f02f35bb30 100644
--- a/storage/src/get_bucket_labels.php
+++ b/storage/src/get_bucket_labels.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function get_bucket_labels($bucketName)
+function get_bucket_labels($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/get_bucket_metadata.php b/storage/src/get_bucket_metadata.php
index 0d8d3daba7..657730c5e6 100644
--- a/storage/src/get_bucket_metadata.php
+++ b/storage/src/get_bucket_metadata.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function get_bucket_metadata($bucketName)
+function get_bucket_metadata($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/get_default_event_based_hold.php b/storage/src/get_default_event_based_hold.php
index 4b41a06192..86fc95b43c 100644
--- a/storage/src/get_default_event_based_hold.php
+++ b/storage/src/get_default_event_based_hold.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function get_default_event_based_hold($bucketName)
+function get_default_event_based_hold($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/get_hmac_key.php b/storage/src/get_hmac_key.php
index ffa6e40bd9..01a9640cf2 100644
--- a/storage/src/get_hmac_key.php
+++ b/storage/src/get_hmac_key.php
@@ -32,7 +32,7 @@
* @param string $projectId The ID of your Google Cloud Platform project.
* @param string $accessId Access ID for an HMAC key.
*/
-function get_hmac_key($projectId, $accessId)
+function get_hmac_key($projectId, $accessId): void
{
// $projectId = 'my-project-id';
// $accessId = 'GOOG0234230X00';
diff --git a/storage/src/get_object_acl.php b/storage/src/get_object_acl.php
index f03477b711..459b39c003 100644
--- a/storage/src/get_object_acl.php
+++ b/storage/src/get_object_acl.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function get_object_acl($bucketName, $objectName)
+function get_object_acl($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/get_object_acl_for_entity.php b/storage/src/get_object_acl_for_entity.php
index c198ac4502..3b27a1906c 100644
--- a/storage/src/get_object_acl_for_entity.php
+++ b/storage/src/get_object_acl_for_entity.php
@@ -33,7 +33,7 @@
* @param string $objectName The name of your Cloud Storage object.
* @param string $entity The entity for which to update access controls.
*/
-function get_object_acl_for_entity($bucketName, $objectName, $entity)
+function get_object_acl_for_entity($bucketName, $objectName, $entity): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/get_object_v2_signed_url.php b/storage/src/get_object_v2_signed_url.php
index e96cb75654..9c6c8300ce 100644
--- a/storage/src/get_object_v2_signed_url.php
+++ b/storage/src/get_object_v2_signed_url.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function get_object_v2_signed_url(http://github.com/$bucketName,%20$objectName)
+function get_object_v2_signed_url(http://github.com/$bucketName,%20$objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/get_object_v4_signed_url.php b/storage/src/get_object_v4_signed_url.php
index 70e9a44fd9..329ddb079a 100644
--- a/storage/src/get_object_v4_signed_url.php
+++ b/storage/src/get_object_v4_signed_url.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function get_object_v4_signed_url(http://github.com/$bucketName,%20$objectName)
+function get_object_v4_signed_url(http://github.com/$bucketName,%20$objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/get_public_access_prevention.php b/storage/src/get_public_access_prevention.php
index 0b56935bdd..89a423facf 100644
--- a/storage/src/get_public_access_prevention.php
+++ b/storage/src/get_public_access_prevention.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName the name of your Cloud Storage bucket.
*/
-function get_public_access_prevention($bucketName)
+function get_public_access_prevention($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/get_requester_pays_status.php b/storage/src/get_requester_pays_status.php
index 4613a8cbaf..34d5e04363 100644
--- a/storage/src/get_requester_pays_status.php
+++ b/storage/src/get_requester_pays_status.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function get_requester_pays_status($bucketName)
+function get_requester_pays_status($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/get_retention_policy.php b/storage/src/get_retention_policy.php
index e03a3dda0e..32118bdff3 100644
--- a/storage/src/get_retention_policy.php
+++ b/storage/src/get_retention_policy.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function get_retention_policy($bucketName)
+function get_retention_policy($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/get_service_account.php b/storage/src/get_service_account.php
index 9b3f00969d..3102f1070a 100644
--- a/storage/src/get_service_account.php
+++ b/storage/src/get_service_account.php
@@ -31,7 +31,7 @@
*
* @param string $projectId The ID of your Google Cloud Platform project.
*/
-function get_service_account($projectId)
+function get_service_account($projectId): void
{
// $projectId = 'my-project-id';
diff --git a/storage/src/get_turbo_replication_status.php b/storage/src/get_turbo_replication_status.php
index 269cb676af..ba93337c82 100644
--- a/storage/src/get_turbo_replication_status.php
+++ b/storage/src/get_turbo_replication_status.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName the name of your Cloud Storage bucket.
*/
-function get_turbo_replication_status($bucketName)
+function get_turbo_replication_status($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/get_uniform_bucket_level_access.php b/storage/src/get_uniform_bucket_level_access.php
index 474f40abea..4a5241bee3 100644
--- a/storage/src/get_uniform_bucket_level_access.php
+++ b/storage/src/get_uniform_bucket_level_access.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function get_uniform_bucket_level_access($bucketName)
+function get_uniform_bucket_level_access($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/list_buckets.php b/storage/src/list_buckets.php
index 9f6bb7c74c..78448a5696 100644
--- a/storage/src/list_buckets.php
+++ b/storage/src/list_buckets.php
@@ -29,7 +29,7 @@
/**
* List all Cloud Storage buckets for the current project.
*/
-function list_buckets()
+function list_buckets(): void
{
$storage = new StorageClient();
foreach ($storage->buckets() as $bucket) {
diff --git a/storage/src/list_file_archived_generations.php b/storage/src/list_file_archived_generations.php
index 19de55cf17..b774d5598a 100644
--- a/storage/src/list_file_archived_generations.php
+++ b/storage/src/list_file_archived_generations.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function list_file_archived_generations($bucketName)
+function list_file_archived_generations($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/list_hmac_keys.php b/storage/src/list_hmac_keys.php
index b6d0aa71df..4a5a033ac1 100644
--- a/storage/src/list_hmac_keys.php
+++ b/storage/src/list_hmac_keys.php
@@ -31,7 +31,7 @@
*
* @param string $projectId The ID of your Google Cloud Platform project.
*/
-function list_hmac_keys($projectId)
+function list_hmac_keys($projectId): void
{
// $projectId = 'my-project-id';
diff --git a/storage/src/list_objects.php b/storage/src/list_objects.php
index 8eb1a2a5ed..a66a98e51a 100644
--- a/storage/src/list_objects.php
+++ b/storage/src/list_objects.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function list_objects($bucketName)
+function list_objects($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/list_objects_with_prefix.php b/storage/src/list_objects_with_prefix.php
index 6c2d0a432e..0e134cffb5 100644
--- a/storage/src/list_objects_with_prefix.php
+++ b/storage/src/list_objects_with_prefix.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $directoryPrefix the prefix to use in the list objects API call.
*/
-function list_objects_with_prefix($bucketName, $directoryPrefix)
+function list_objects_with_prefix($bucketName, $directoryPrefix): void
{
// $bucketName = 'my-bucket';
// $directoryPrefix = 'myDirectory/';
diff --git a/storage/src/lock_retention_policy.php b/storage/src/lock_retention_policy.php
index 32f6d19afc..70dc8f37eb 100644
--- a/storage/src/lock_retention_policy.php
+++ b/storage/src/lock_retention_policy.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function lock_retention_policy($bucketName)
+function lock_retention_policy($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/make_public.php b/storage/src/make_public.php
index c6c5130fe9..ce62a301bf 100644
--- a/storage/src/make_public.php
+++ b/storage/src/make_public.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function make_public($bucketName, $objectName)
+function make_public($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/move_object.php b/storage/src/move_object.php
index fde4271bc5..d4f7b0b722 100644
--- a/storage/src/move_object.php
+++ b/storage/src/move_object.php
@@ -34,7 +34,7 @@
* @param string $newBucketName the destination bucket name.
* @param string $newObjectName the destination object name.
*/
-function move_object($bucketName, $objectName, $newBucketName, $newObjectName)
+function move_object($bucketName, $objectName, $newBucketName, $newObjectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/object_csek_to_cmek.php b/storage/src/object_csek_to_cmek.php
index fb6d9aa6ed..997134961f 100644
--- a/storage/src/object_csek_to_cmek.php
+++ b/storage/src/object_csek_to_cmek.php
@@ -38,7 +38,7 @@
* Key names are provided in the following format:
* `projects//locations//keyRings//cryptoKeys/`.
*/
-function object_csek_to_cmek($bucketName, $objectName, $decryptionKey, $kmsKeyName)
+function object_csek_to_cmek($bucketName, $objectName, $decryptionKey, $kmsKeyName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/object_metadata.php b/storage/src/object_metadata.php
index 8bc2cf53ed..a0a4f2d457 100644
--- a/storage/src/object_metadata.php
+++ b/storage/src/object_metadata.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function object_metadata($bucketName, $objectName)
+function object_metadata($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/release_event_based_hold.php b/storage/src/release_event_based_hold.php
index fad14a1f22..45373db542 100644
--- a/storage/src/release_event_based_hold.php
+++ b/storage/src/release_event_based_hold.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function release_event_based_hold($bucketName, $objectName)
+function release_event_based_hold($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/release_temporary_hold.php b/storage/src/release_temporary_hold.php
index 6ec57af64c..ae3ebe5a1b 100644
--- a/storage/src/release_temporary_hold.php
+++ b/storage/src/release_temporary_hold.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function release_temporary_hold($bucketName, $objectName)
+function release_temporary_hold($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/remove_bucket_conditional_iam_binding.php b/storage/src/remove_bucket_conditional_iam_binding.php
index fa531a3533..8cdd6cb8c5 100644
--- a/storage/src/remove_bucket_conditional_iam_binding.php
+++ b/storage/src/remove_bucket_conditional_iam_binding.php
@@ -38,7 +38,7 @@
* @param string $description The description of the condition.
* @param string $expression Te condition specified in CEL expression language.
*/
-function remove_bucket_conditional_iam_binding($bucketName, $role, $title, $description, $expression)
+function remove_bucket_conditional_iam_binding($bucketName, $role, $title, $description, $expression): void
{
// $bucketName = 'my-bucket';
// $role = 'roles/storage.objectViewer';
diff --git a/storage/src/remove_bucket_iam_member.php b/storage/src/remove_bucket_iam_member.php
index 5c451bd574..04b94f425e 100644
--- a/storage/src/remove_bucket_iam_member.php
+++ b/storage/src/remove_bucket_iam_member.php
@@ -33,7 +33,7 @@
* @param string $role The role from which the specified member should be removed.
* @param string $member The member to be removed from the specified role.
*/
-function remove_bucket_iam_member($bucketName, $role, $member)
+function remove_bucket_iam_member($bucketName, $role, $member): void
{
// $bucketName = 'my-bucket';
// $role = 'roles/storage.objectViewer';
diff --git a/storage/src/remove_bucket_label.php b/storage/src/remove_bucket_label.php
index 436d50f02e..1b626a60c7 100644
--- a/storage/src/remove_bucket_label.php
+++ b/storage/src/remove_bucket_label.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $labelName The name of the label to remove.
*/
-function remove_bucket_label($bucketName, $labelName)
+function remove_bucket_label($bucketName, $labelName): void
{
// $bucketName = 'my-bucket';
// $labelName = 'label-key-to-remove';
diff --git a/storage/src/remove_cors_configuration.php b/storage/src/remove_cors_configuration.php
index 6e4d8edfd8..11392246af 100644
--- a/storage/src/remove_cors_configuration.php
+++ b/storage/src/remove_cors_configuration.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function remove_cors_configuration($bucketName)
+function remove_cors_configuration($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/remove_retention_policy.php b/storage/src/remove_retention_policy.php
index 621f2dd507..c6d3a1e3ab 100644
--- a/storage/src/remove_retention_policy.php
+++ b/storage/src/remove_retention_policy.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function remove_retention_policy($bucketName)
+function remove_retention_policy($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/rotate_encryption_key.php b/storage/src/rotate_encryption_key.php
index cee8d0b825..94310fec49 100644
--- a/storage/src/rotate_encryption_key.php
+++ b/storage/src/rotate_encryption_key.php
@@ -38,11 +38,11 @@
* @param string $newBase64EncryptionKey The new base64 encoded encryption key.
*/
function rotate_encryption_key(
- $bucketName,
- $objectName,
- $oldBase64EncryptionKey,
- $newBase64EncryptionKey
-) {
+ string $bucketName,
+ string $objectName,
+ string $oldBase64EncryptionKey,
+ string $newBase64EncryptionKey
+): void {
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
// $oldbase64EncryptionKey = 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=';
diff --git a/storage/src/set_bucket_public_iam.php b/storage/src/set_bucket_public_iam.php
index d2336a63b8..cf88a3e82a 100644
--- a/storage/src/set_bucket_public_iam.php
+++ b/storage/src/set_bucket_public_iam.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function set_bucket_public_iam($bucketName)
+function set_bucket_public_iam($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/set_event_based_hold.php b/storage/src/set_event_based_hold.php
index b6a7657208..a80c822aa4 100644
--- a/storage/src/set_event_based_hold.php
+++ b/storage/src/set_event_based_hold.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function set_event_based_hold($bucketName, $objectName)
+function set_event_based_hold($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/set_metadata.php b/storage/src/set_metadata.php
index 5c04005b83..791dcf6814 100644
--- a/storage/src/set_metadata.php
+++ b/storage/src/set_metadata.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function set_metadata($bucketName, $objectName)
+function set_metadata($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/set_public_access_prevention_enforced.php b/storage/src/set_public_access_prevention_enforced.php
index 7ee50da30f..d7c914f162 100644
--- a/storage/src/set_public_access_prevention_enforced.php
+++ b/storage/src/set_public_access_prevention_enforced.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName the name of your Cloud Storage bucket.
*/
-function set_public_access_prevention_enforced($bucketName)
+function set_public_access_prevention_enforced($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/set_public_access_prevention_inherited.php b/storage/src/set_public_access_prevention_inherited.php
index 35caa5c5a5..d31bdfc8e9 100644
--- a/storage/src/set_public_access_prevention_inherited.php
+++ b/storage/src/set_public_access_prevention_inherited.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName the name of your Cloud Storage bucket.
*/
-function set_public_access_prevention_inherited($bucketName)
+function set_public_access_prevention_inherited($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/set_public_access_prevention_unspecified.php b/storage/src/set_public_access_prevention_unspecified.php
index de8779c739..963db68fc7 100644
--- a/storage/src/set_public_access_prevention_unspecified.php
+++ b/storage/src/set_public_access_prevention_unspecified.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName the name of your Cloud Storage bucket.
*/
-function set_public_access_prevention_unspecified($bucketName)
+function set_public_access_prevention_unspecified($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/set_retention_policy.php b/storage/src/set_retention_policy.php
index 34e39b447f..dace532cde 100644
--- a/storage/src/set_retention_policy.php
+++ b/storage/src/set_retention_policy.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param int $retentionPeriod The retention period for objects in bucket, in seconds.
*/
-function set_retention_policy($bucketName, $retentionPeriod)
+function set_retention_policy($bucketName, $retentionPeriod): void
{
// $bucketName = 'my-bucket';
// $retentionPeriod = 3600;
diff --git a/storage/src/set_temporary_hold.php b/storage/src/set_temporary_hold.php
index 4fc057751a..af3edbbb82 100644
--- a/storage/src/set_temporary_hold.php
+++ b/storage/src/set_temporary_hold.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function set_temporary_hold($bucketName, $objectName)
+function set_temporary_hold($bucketName, $objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/set_turbo_replication_async_turbo.php b/storage/src/set_turbo_replication_async_turbo.php
index 49e110c77c..6bc3dfc8dd 100644
--- a/storage/src/set_turbo_replication_async_turbo.php
+++ b/storage/src/set_turbo_replication_async_turbo.php
@@ -32,7 +32,7 @@
*
* @param string $bucketName the name of your Cloud Storage bucket.
*/
-function set_turbo_replication_async_turbo($bucketName)
+function set_turbo_replication_async_turbo($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/set_turbo_replication_default.php b/storage/src/set_turbo_replication_default.php
index e5f5cae8fa..29bb738d03 100644
--- a/storage/src/set_turbo_replication_default.php
+++ b/storage/src/set_turbo_replication_default.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName the name of your Cloud Storage bucket.
*/
-function set_turbo_replication_default($bucketName)
+function set_turbo_replication_default($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storage/src/upload_encrypted_object.php b/storage/src/upload_encrypted_object.php
index 344892a550..a5404b73cf 100644
--- a/storage/src/upload_encrypted_object.php
+++ b/storage/src/upload_encrypted_object.php
@@ -34,15 +34,21 @@
* @param string $source The path to the file to upload.
* @param string $base64EncryptionKey The base64 encoded encryption key.
*/
-function upload_encrypted_object($bucketName, $objectName, $source, $base64EncryptionKey)
-{
+function upload_encrypted_object(
+ string $bucketName,
+ string $objectName,
+ string $source,
+ string $base64EncryptionKey
+): void {
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
// $source = '/path/to/your/file';
// $base64EncryptionKey = 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=';
$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.php b/storage/src/upload_object.php
index 84d1a9abec..3cb176fadb 100644
--- a/storage/src/upload_object.php
+++ b/storage/src/upload_object.php
@@ -34,14 +34,16 @@
* @param string $objectName The name of your Cloud Storage object.
* @param string $source The path to the file to upload.
*/
-function upload_object($bucketName, $objectName, $source)
+function upload_object($bucketName, $objectName, $source): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
// $source = '/path/to/your/file';
$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 b9d5953647..d9a52cb4d0 100644
--- a/storage/src/upload_object_from_memory.php
+++ b/storage/src/upload_object_from_memory.php
@@ -43,7 +43,9 @@ function upload_object_from_memory(
// $contents = 'these are my contents';
$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_object_v4_signed_url.php b/storage/src/upload_object_v4_signed_url.php
index 14c967e17f..a24d0b7c70 100644
--- a/storage/src/upload_object_v4_signed_url.php
+++ b/storage/src/upload_object_v4_signed_url.php
@@ -32,7 +32,7 @@
* @param string $bucketName The name of your Cloud Storage bucket.
* @param string $objectName The name of your Cloud Storage object.
*/
-function upload_object_v4_signed_url(http://github.com/$bucketName,%20$objectName)
+function upload_object_v4_signed_url(http://github.com/$bucketName,%20$objectName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
diff --git a/storage/src/upload_with_kms_key.php b/storage/src/upload_with_kms_key.php
index f24d6d9141..53d9cfee31 100644
--- a/storage/src/upload_with_kms_key.php
+++ b/storage/src/upload_with_kms_key.php
@@ -36,7 +36,7 @@
* Key names are provided in the following format:
* `projects//locations//keyRings//cryptoKeys/`.
*/
-function upload_with_kms_key($bucketName, $objectName, $source, $kmsKeyName)
+function upload_with_kms_key($bucketName, $objectName, $source, $kmsKeyName): void
{
// $bucketName = 'my-bucket';
// $objectName = 'my-object';
@@ -44,7 +44,9 @@ function upload_with_kms_key($bucketName, $objectName, $source, $kmsKeyName)
// $kmsKeyName = "";
$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/view_bucket_iam_members.php b/storage/src/view_bucket_iam_members.php
index 00e902fc73..58a83035a2 100644
--- a/storage/src/view_bucket_iam_members.php
+++ b/storage/src/view_bucket_iam_members.php
@@ -31,7 +31,7 @@
*
* @param string $bucketName The name of your Cloud Storage bucket.
*/
-function view_bucket_iam_members($bucketName)
+function view_bucket_iam_members($bucketName): void
{
// $bucketName = 'my-bucket';
diff --git a/storagetransfer/src/quickstart.php b/storagetransfer/src/quickstart.php
index 2fcee93d38..f7c398d322 100644
--- a/storagetransfer/src/quickstart.php
+++ b/storagetransfer/src/quickstart.php
@@ -31,7 +31,7 @@
* @param string $sourceGcsBucketName The name of the GCS bucket to transfer objects from.
* @param string $sinkGcsBucketName The name of the GCS bucket to transfer objects to.
*/
-function quickstart($projectId, $sourceGcsBucketName, $sinkGcsBucketName)
+function quickstart($projectId, $sourceGcsBucketName, $sinkGcsBucketName): void
{
// $project = 'my-project-id';
// $sourceGcsBucketName = 'my-source-bucket';
diff --git a/testing/composer.json b/testing/composer.json
index 1495dc65d2..447b067180 100755
--- a/testing/composer.json
+++ b/testing/composer.json
@@ -8,6 +8,7 @@
"google/cloud-tools": "dev-main",
"guzzlehttp/guzzle": "^7.0",
"phpunit/phpunit": "^7|^8",
+ "phpstan/phpstan": "^1.5.4",
"friendsofphp/php-cs-fixer": "^3.0",
"composer/semver": "^3.2"
}
diff --git a/testing/phpstan/bigtable.neon.dist b/testing/phpstan/bigtable.neon.dist
new file mode 100644
index 0000000000..2e9a38b049
--- /dev/null
+++ b/testing/phpstan/bigtable.neon.dist
@@ -0,0 +1,6 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+ - '#dev-label#'
diff --git a/testing/phpstan/compute/cloud-client/firewall.neon.dist b/testing/phpstan/compute/cloud-client/firewall.neon.dist
new file mode 100644
index 0000000000..0d733bd06e
--- /dev/null
+++ b/testing/phpstan/compute/cloud-client/firewall.neon.dist
@@ -0,0 +1,5 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
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..329cd7a786
--- /dev/null
+++ b/testing/phpstan/compute/cloud-client/instances.neon.dist
@@ -0,0 +1,6 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+ - '#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..53b8e895e9
--- /dev/null
+++ b/testing/phpstan/default.neon.dist
@@ -0,0 +1,3 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
diff --git a/testing/phpstan/dlp.neon.dist b/testing/phpstan/dlp.neon.dist
new file mode 100644
index 0000000000..c455072167
--- /dev/null
+++ b/testing/phpstan/dlp.neon.dist
@@ -0,0 +1,6 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+
diff --git a/testing/phpstan/kms.neon.dist b/testing/phpstan/kms.neon.dist
new file mode 100644
index 0000000000..3dacf92209
--- /dev/null
+++ b/testing/phpstan/kms.neon.dist
@@ -0,0 +1,7 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+ - '#Cannot assign new offset to Google\\Protobuf\\Internal\\RepeatedField#'
+
diff --git a/testing/phpstan/media/transcoder.neon.dist b/testing/phpstan/media/transcoder.neon.dist
new file mode 100644
index 0000000000..c455072167
--- /dev/null
+++ b/testing/phpstan/media/transcoder.neon.dist
@@ -0,0 +1,6 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+
diff --git a/testing/phpstan/monitoring.neon.dist b/testing/phpstan/monitoring.neon.dist
new file mode 100644
index 0000000000..c4de013597
--- /dev/null
+++ b/testing/phpstan/monitoring.neon.dist
@@ -0,0 +1,8 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+ - '#Google\\Protobuf\\Internal\\RepeatedField does not accept string#'
+ - '#Cannot assign new offset to Google\\Protobuf\\Internal\\RepeatedField#'
+
diff --git a/testing/phpstan/pubsub/api.neon.dist b/testing/phpstan/pubsub/api.neon.dist
new file mode 100644
index 0000000000..a35469abb8
--- /dev/null
+++ b/testing/phpstan/pubsub/api.neon.dist
@@ -0,0 +1,8 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ excludePaths:
+ - ../../../pubsub/api/src/data
+ ignoreErrors:
+ - '#Utilities\\StateProto#'
+
diff --git a/testing/phpstan/recaptcha.neon.dist b/testing/phpstan/recaptcha.neon.dist
new file mode 100644
index 0000000000..c455072167
--- /dev/null
+++ b/testing/phpstan/recaptcha.neon.dist
@@ -0,0 +1,6 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+
diff --git a/testing/phpstan/secretmanager.neon.dist b/testing/phpstan/secretmanager.neon.dist
new file mode 100644
index 0000000000..3dacf92209
--- /dev/null
+++ b/testing/phpstan/secretmanager.neon.dist
@@ -0,0 +1,7 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+ - '#Cannot assign new offset to Google\\Protobuf\\Internal\\RepeatedField#'
+
diff --git a/testing/phpstan/securitycenter.neon.dist b/testing/phpstan/securitycenter.neon.dist
new file mode 100644
index 0000000000..c455072167
--- /dev/null
+++ b/testing/phpstan/securitycenter.neon.dist
@@ -0,0 +1,6 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+
diff --git a/testing/phpstan/texttospeech.neon.dist b/testing/phpstan/texttospeech.neon.dist
new file mode 100644
index 0000000000..c455072167
--- /dev/null
+++ b/testing/phpstan/texttospeech.neon.dist
@@ -0,0 +1,6 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+
diff --git a/testing/phpstan/translate.neon.dist b/testing/phpstan/translate.neon.dist
new file mode 100644
index 0000000000..c455072167
--- /dev/null
+++ b/testing/phpstan/translate.neon.dist
@@ -0,0 +1,6 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+
diff --git a/testing/phpstan/vision.neon.dist b/testing/phpstan/vision.neon.dist
new file mode 100644
index 0000000000..c455072167
--- /dev/null
+++ b/testing/phpstan/vision.neon.dist
@@ -0,0 +1,6 @@
+parameters:
+ level: 7
+ treatPhpDocTypesAsCertain: false
+ ignoreErrors:
+ - '#expects Google\\Protobuf\\Internal\\RepeatedField'
+
diff --git a/testing/run_staticanalysis_check.sh b/testing/run_staticanalysis_check.sh
new file mode 100644
index 0000000000..f4f9f3e8a1
--- /dev/null
+++ b/testing/run_staticanalysis_check.sh
@@ -0,0 +1,71 @@
+#!/bin/bash
+# Copyright 2022 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=(
+ appengine
+ dialogflow
+ iot
+)
+
+TMP_REPORT_DIR=$(mktemp -d)
+SUCCEEDED_FILE=${TMP_REPORT_DIR}/succeeded
+FAILED_FILE=${TMP_REPORT_DIR}/failed
+
+for dir in $(find $TEST_DIRECTORIES -type d -name src -not -path '/*' -not -path 'appengine/*' -not -path '*/vendor/*' -exec dirname {} \;);
+do
+ if [[ " ${SKIP_DIRS[@]} " =~ " ${dir} " ]]; then
+ echo "Skipping $dir (explicitly flagged to be skipped)"
+ 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 "${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 8d76a848bd..bc6bfdaf45 100644
--- a/testing/sample_helpers.php
+++ b/testing/sample_helpers.php
@@ -4,7 +4,7 @@
use ReflectionFunction;
-function execute_sample(string $file, string $namespace, ?array $argv)
+function execute_sample(string $file, string $namespace, ?array $argv): void
{
// Return if sample file is not being executed via CLI
if (is_null($argv)) {
@@ -42,14 +42,15 @@ function execute_sample(string $file, string $namespace, ?array $argv)
require_once $autoloadFile;
// If any parameters are typehinted as "array", explode user input on ","
+ $validArrayTypes = ['array', 'array', 'string[]'];
$parameterReflections = $functionReflection->getParameters();
foreach (array_values($argv) as $i => $val) {
$parameterReflection = $parameterReflections[$i];
- if (
- $parameterReflection->hasType()
- && 'array' === $parameterReflection->getType()->getName()
- ) {
- $argv[$i] = explode(',', $argv[$i]);
+ if ($parameterReflection->hasType()) {
+ $parameterType = $parameterReflection->getType()->getName();
+ if (in_array($parameterType, $validArrayTypes)) {
+ $argv[$i] = explode(',', $argv[$i]);
+ }
}
}
@@ -57,7 +58,7 @@ function execute_sample(string $file, string $namespace, ?array $argv)
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/texttospeech/src/synthesize_ssml_file.php b/texttospeech/src/synthesize_ssml_file.php
index 58adf7eb72..9727ebd138 100644
--- a/texttospeech/src/synthesize_ssml_file.php
+++ b/texttospeech/src/synthesize_ssml_file.php
@@ -44,7 +44,7 @@
$client = new TextToSpeechClient();
// get ssml from file
-$ssml = file_get_contents($path);
+$ssml = (string) file_get_contents($path);
$input_text = (new SynthesisInput())
->setSsml($ssml);
diff --git a/texttospeech/src/synthesize_text_effects_profile_file.php b/texttospeech/src/synthesize_text_effects_profile_file.php
index a980be63d6..d5312c0c92 100644
--- a/texttospeech/src/synthesize_text_effects_profile_file.php
+++ b/texttospeech/src/synthesize_text_effects_profile_file.php
@@ -45,7 +45,7 @@
$client = new TextToSpeechClient();
// get text from file
-$text = file_get_contents($path);
+$text = (string) file_get_contents($path);
$inputText = (new SynthesisInput())
->setText($text);
diff --git a/texttospeech/src/synthesize_text_file.php b/texttospeech/src/synthesize_text_file.php
index ea901e4e58..b8c82be873 100644
--- a/texttospeech/src/synthesize_text_file.php
+++ b/texttospeech/src/synthesize_text_file.php
@@ -44,7 +44,7 @@
$client = new TextToSpeechClient();
// get text from file
-$text = file_get_contents($path);
+$text = (string) file_get_contents($path);
$input_text = (new SynthesisInput())
->setText($text);
diff --git a/trace/trace-sample.php b/trace/trace-sample.php
index 1fab0b9b9f..d559ed8f89 100644
--- a/trace/trace-sample.php
+++ b/trace/trace-sample.php
@@ -44,7 +44,7 @@
Tracer::start($exporter);
# [END trace_setup_php_tracer_start]
-function trace_callable()
+function trace_callable(): void
{
# [START trace_setup_php_span_with_closure]
Tracer::inSpan(
diff --git a/vision/src/detect_document_text.php b/vision/src/detect_document_text.php
index 5049f46609..48c5e740f7 100644
--- a/vision/src/detect_document_text.php
+++ b/vision/src/detect_document_text.php
@@ -22,12 +22,12 @@
// $path = 'path/to/your/image.jpg'
-function detect_document_text($path)
+function detect_document_text(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->documentTextDetection($image);
$annotation = $response->getFullTextAnnotation();
diff --git a/vision/src/detect_document_text_gcs.php b/vision/src/detect_document_text_gcs.php
index 5a2d106ef4..f5014966f3 100644
--- a/vision/src/detect_document_text_gcs.php
+++ b/vision/src/detect_document_text_gcs.php
@@ -22,7 +22,7 @@
// $path = 'gs://path/to/your/image.jpg'
-function detect_document_text_gcs($path)
+function detect_document_text_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
diff --git a/vision/src/detect_face.php b/vision/src/detect_face.php
index 46efa4e48b..79228a46bc 100644
--- a/vision/src/detect_face.php
+++ b/vision/src/detect_face.php
@@ -22,7 +22,7 @@
// [END vision_face_detection_tutorial_imports]
-function detect_face($path, $outFile = null)
+function detect_face(string $path, string $outFile = null): void
{
// [START vision_face_detection_tutorial_client]
$imageAnnotator = new ImageAnnotatorClient();
@@ -31,7 +31,7 @@ function detect_face($path, $outFile = null)
// [START vision_face_detection_tutorial_send_request]
# annotate the image
// $path = 'path/to/your/image.jpg'
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->faceDetection($image);
$faces = $response->getFaceAnnotations();
// [END vision_face_detection_tutorial_send_request]
@@ -64,7 +64,7 @@ function detect_face($path, $outFile = null)
# [START vision_face_detection_tutorial_process_response]
# draw box around faces
- if ($faces && $outFile) {
+ if (count($faces) && $outFile) {
$imageCreateFunc = [
'png' => 'imagecreatefrompng',
'gd' => 'imagecreatefromgd',
diff --git a/vision/src/detect_face_gcs.php b/vision/src/detect_face_gcs.php
index 57ed042af8..4db7fc7cd3 100644
--- a/vision/src/detect_face_gcs.php
+++ b/vision/src/detect_face_gcs.php
@@ -22,7 +22,7 @@
// $path = 'gs://path/to/your/image.jpg'
-function detect_face_gcs($path)
+function detect_face_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
diff --git a/vision/src/detect_image_property.php b/vision/src/detect_image_property.php
index e6132d12b1..6c25b5f237 100644
--- a/vision/src/detect_image_property.php
+++ b/vision/src/detect_image_property.php
@@ -22,12 +22,12 @@
// $path = 'path/to/your/image.jpg'
-function detect_image_property($path)
+function detect_image_property(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->imagePropertiesDetection($image);
$props = $response->getImagePropertiesAnnotation();
diff --git a/vision/src/detect_image_property_gcs.php b/vision/src/detect_image_property_gcs.php
index 03fae62ad3..5bb85c4251 100644
--- a/vision/src/detect_image_property_gcs.php
+++ b/vision/src/detect_image_property_gcs.php
@@ -22,7 +22,7 @@
// $path = 'gs://path/to/your/image.jpg'
-function detect_image_property_gcs($path)
+function detect_image_property_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
diff --git a/vision/src/detect_label.php b/vision/src/detect_label.php
index 910a2bd8af..06281f2a46 100644
--- a/vision/src/detect_label.php
+++ b/vision/src/detect_label.php
@@ -22,16 +22,16 @@
// $path = 'path/to/your/image.jpg'
-function detect_label($path)
+function detect_label(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->labelDetection($image);
$labels = $response->getLabelAnnotations();
- if ($labels) {
+ if (count($labels)) {
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 cb752daef1..434d87002e 100644
--- a/vision/src/detect_label_gcs.php
+++ b/vision/src/detect_label_gcs.php
@@ -22,7 +22,7 @@
// $path = 'gs://path/to/your/image.jpg'
-function detect_label_gcs($path)
+function detect_label_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
@@ -30,7 +30,7 @@ function detect_label_gcs($path)
$response = $imageAnnotator->labelDetection($path);
$labels = $response->getLabelAnnotations();
- if ($labels) {
+ if (count($labels)) {
print('Labels:' . PHP_EOL);
foreach ($labels as $label) {
print($label->getDescription() . PHP_EOL);
diff --git a/vision/src/detect_landmark.php b/vision/src/detect_landmark.php
index c8e1bdd517..c5c57db3e9 100644
--- a/vision/src/detect_landmark.php
+++ b/vision/src/detect_landmark.php
@@ -22,12 +22,12 @@
// $path = 'path/to/your/image.jpg1'
-function detect_landmark($path)
+function detect_landmark(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->landmarkDetection($image);
$landmarks = $response->getLandmarkAnnotations();
diff --git a/vision/src/detect_landmark_gcs.php b/vision/src/detect_landmark_gcs.php
index 26fbdc5911..a66ce1485d 100644
--- a/vision/src/detect_landmark_gcs.php
+++ b/vision/src/detect_landmark_gcs.php
@@ -22,7 +22,7 @@
// $path = 'gs://path/to/your/image.jpg'
-function detect_landmark_gcs($path)
+function detect_landmark_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
diff --git a/vision/src/detect_logo.php b/vision/src/detect_logo.php
index 51b5838c3c..cd19c9a3f3 100644
--- a/vision/src/detect_logo.php
+++ b/vision/src/detect_logo.php
@@ -22,12 +22,12 @@
// $path = 'path/to/your/image.jpg'
-function detect_logo($path)
+function detect_logo(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->logoDetection($image);
$logos = $response->getLogoAnnotations();
diff --git a/vision/src/detect_logo_gcs.php b/vision/src/detect_logo_gcs.php
index d3fb773d89..083fd9878d 100644
--- a/vision/src/detect_logo_gcs.php
+++ b/vision/src/detect_logo_gcs.php
@@ -20,9 +20,10 @@
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
-// $path = 'gs://path/to/your/image.jpg'
-
-function detect_logo_gcs($path)
+/**
+ * @param string $path (example: 'gs://path/to/your/image.jpg')
+ */
+function detect_logo_gcs(string$path): void
{
$imageAnnotator = new ImageAnnotatorClient();
diff --git a/vision/src/detect_object.php b/vision/src/detect_object.php
index 0bf784d435..c5823c1528 100644
--- a/vision/src/detect_object.php
+++ b/vision/src/detect_object.php
@@ -20,14 +20,15 @@
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
-// $path = 'path/to/your/image.jpg'
-
-function detect_object($path)
+/**
+ * @param string $path (example: 'path/to/your/image.jpg')
+ */
+function detect_object(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->objectLocalization($image);
$objects = $response->getLocalizedObjectAnnotations();
diff --git a/vision/src/detect_object_gcs.php b/vision/src/detect_object_gcs.php
index 9d1b2345b6..d664300c58 100644
--- a/vision/src/detect_object_gcs.php
+++ b/vision/src/detect_object_gcs.php
@@ -20,9 +20,10 @@
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
-// $path = 'gs://path/to/your/image.jpg'
-
-function detect_object_gcs($path)
+/**
+ * @param string $path (example: 'gs://path/to/your/image.jpg')
+ */
+function detect_object_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
diff --git a/vision/src/detect_pdf_gcs.php b/vision/src/detect_pdf_gcs.php
index eae77d3e5e..05c24aef3b 100644
--- a/vision/src/detect_pdf_gcs.php
+++ b/vision/src/detect_pdf_gcs.php
@@ -29,10 +29,11 @@
use Google\Cloud\Vision\V1\InputConfig;
use Google\Cloud\Vision\V1\OutputConfig;
-// $path = 'gs://path/to/your/document.pdf'
-// $output = 'gs://path/to/store/results/'
-
-function detect_pdf_gcs($path, $output)
+/**
+ * @param string $path (example: 'gs://path/to/your/document.pdf')
+ * @param string $output (example: 'gs://path/to/store/results/')
+ */
+function detect_pdf_gcs(string $path, string $output): void
{
# select ocr feature
$feature = (new Feature())
diff --git a/vision/src/detect_safe_search.php b/vision/src/detect_safe_search.php
index f01a014c37..3404b68a0e 100644
--- a/vision/src/detect_safe_search.php
+++ b/vision/src/detect_safe_search.php
@@ -22,12 +22,12 @@
// $path = 'path/to/your/image.jpg'
-function detect_safe_search($path)
+function detect_safe_search(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->safeSearchDetection($image);
$safe = $response->getSafeSearchAnnotation();
diff --git a/vision/src/detect_safe_search_gcs.php b/vision/src/detect_safe_search_gcs.php
index d81c13c7d4..7ba494ff33 100644
--- a/vision/src/detect_safe_search_gcs.php
+++ b/vision/src/detect_safe_search_gcs.php
@@ -22,7 +22,7 @@
// $path = 'gs://path/to/your/image.jpg'
-function detect_safe_search_gcs($path)
+function detect_safe_search_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
diff --git a/vision/src/detect_text.php b/vision/src/detect_text.php
index d07bf62b76..8ff1c0d3f3 100644
--- a/vision/src/detect_text.php
+++ b/vision/src/detect_text.php
@@ -20,14 +20,12 @@
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
-// $path = 'path/to/your/image.jpg';
-
-function detect_text($path)
+function detect_text(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->textDetection($image);
$texts = $response->getTextAnnotations();
diff --git a/vision/src/detect_text_gcs.php b/vision/src/detect_text_gcs.php
index 93f594af8d..1ff07f87c9 100644
--- a/vision/src/detect_text_gcs.php
+++ b/vision/src/detect_text_gcs.php
@@ -20,9 +20,7 @@
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
-// $path = 'gs://path/to/your/image.jpg'
-
-function detect_text_gcs($path)
+function detect_text_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
diff --git a/vision/src/detect_web.php b/vision/src/detect_web.php
index 3f58298633..d066891ec5 100644
--- a/vision/src/detect_web.php
+++ b/vision/src/detect_web.php
@@ -20,14 +20,15 @@
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
-// $path = 'path/to/your/image.jpg'
-
-function detect_web($path)
+/**
+ * @param string $path Path to your image (e.g. 'path/to/your/image.jpg')
+ */
+function detect_web(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->webDetection($image);
$web = $response->getWebDetection();
diff --git a/vision/src/detect_web_gcs.php b/vision/src/detect_web_gcs.php
index 13fbe44031..358572d5f7 100644
--- a/vision/src/detect_web_gcs.php
+++ b/vision/src/detect_web_gcs.php
@@ -20,9 +20,10 @@
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
-// $path = 'gs://path/to/your/image.jpg'
-
-function detect_web_gcs($path)
+/**
+ * @param string $path Path to your image (e.g. 'gs://path/to/your/image.jpg')
+ */
+function detect_web_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
diff --git a/vision/src/detect_web_with_geo_metadata.php b/vision/src/detect_web_with_geo_metadata.php
index 8bc28d061d..cf0b4def10 100644
--- a/vision/src/detect_web_with_geo_metadata.php
+++ b/vision/src/detect_web_with_geo_metadata.php
@@ -22,13 +22,13 @@
use Google\Cloud\Vision\V1\ImageContext;
use Google\Cloud\Vision\V1\WebDetectionParams;
-// $path = 'path/to/your/image.jpg'
-
/**
* Detect web entities on an image and include the image's geo metadata
* to improve the quality of the detection.
+ *
+ * @param string $path Path to your image (e.g. 'path/to/your/image.jpg')
*/
-function detect_web_with_geo_metadata($path)
+function detect_web_with_geo_metadata(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();
@@ -39,11 +39,11 @@ function detect_web_with_geo_metadata($path)
$imageContext-> setWebDetectionParams($params);
# annotate the image
- $image = file_get_contents($path);
+ $image = (string) file_get_contents($path);
$response = $imageAnnotator->webDetection($image, ['imageContext' => $imageContext]);
$web = $response->getWebDetection();
- if ($web && $web->getWebEntities()) {
+ if ($web) {
printf('%d web entities found:' . PHP_EOL,
count($web->getWebEntities()));
foreach ($web->getWebEntities() as $entity) {
diff --git a/vision/src/detect_web_with_geo_metadata_gcs.php b/vision/src/detect_web_with_geo_metadata_gcs.php
index b5b80fa79d..9fc63671e4 100644
--- a/vision/src/detect_web_with_geo_metadata_gcs.php
+++ b/vision/src/detect_web_with_geo_metadata_gcs.php
@@ -22,13 +22,13 @@
use Google\Cloud\Vision\V1\ImageContext;
use Google\Cloud\Vision\V1\WebDetectionParams;
-// $path = 'gs://path/to/your/image.jpg'
-
/**
* Detect web entities on an image and include the image's geo metadata
* to improve the quality of the detection.
+ *
+ * @param string $path Path to your image (e.g. 'gs://path/to/your/image.jpg')
*/
-function detect_web_with_geo_metadata_gcs($path)
+function detect_web_with_geo_metadata_gcs(string $path): void
{
$imageAnnotator = new ImageAnnotatorClient();