Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cloud Dlp Laravel Package

google/cloud-dlp

Idiomatic PHP client for Google Cloud Data Loss Prevention (DLP). Inspect, classify, and manage sensitive data using REST or gRPC. Install via Composer and authenticate with Google Cloud credentials to start calling the DLP API.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require google/cloud-dlp
    

    Ensure your composer.json includes the package under require.

  2. Authentication: Configure Google Cloud credentials via:

    • Environment variable (GOOGLE_APPLICATION_CREDENTIALS pointing to a service account JSON key file).
    • Default application credentials (if running in a GCP environment like Cloud Functions or Compute Engine).
  3. First Use Case: Scan a text content for sensitive data (e.g., credit card numbers):

    use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
    use Google\Cloud\Dlp\V2\InspectContentRequest;
    use Google\Cloud\Dlp\V2\InfoType;
    
    $dlp = new DlpServiceClient();
    $request = (new InspectContentRequest())
        ->setItem(new \Google\Cloud\Dlp\V2\ContentItem())
            ->setData(new \Google\Cloud\Dlp\V2\ContentItem\Data())
                ->setBytes('Your sensitive text here')
        ->setInfoTypes([new InfoType()->setName('CREDIT_CARD')]);
    
    $response = $dlp->inspectContent($request);
    print_r($response->getFindings());
    

Key Entry Points

  • Client Initialization: DlpServiceClient is the primary class for all operations.
  • Core Methods:
    • inspectContent(): Scan text, images, or files for sensitive data.
    • redactContent(): Redact sensitive data from text.
    • createInspectJob(): Asynchronous scanning for large datasets (e.g., BigQuery tables).
    • getDataProfile(): Retrieve insights about data (e.g., column statistics, sensitive data distribution).

Documentation


Implementation Patterns

Common Workflows

1. Sensitive Data Detection in Text

$dlp = new DlpServiceClient();
$request = (new InspectContentRequest())
    ->setItem(new \Google\Cloud\Dlp\V2\ContentItem())
        ->setData(new \Google\Cloud\Dlp\V2\ContentItem\Data())
            ->setBytes('SSN: 123-45-6789')
    ->setInfoTypes([new InfoType()->setName('US_SOCIAL_SECURITY_NUMBER')]);

$response = $dlp->inspectContent($request);
foreach ($response->getFindings() as $finding) {
    echo "Found: " . $finding->getInfoType()->getName() . "\n";
}

2. Redacting Sensitive Data

$request = (new RedactContentRequest())
    ->setItem(new \Google\Cloud\Dlp\V2\ContentItem())
        ->setData(new \Google\Cloud\Dlp\V2\ContentItem\Data())
            ->setBytes('Email: user@example.com')
    ->setInfoTypes([new InfoType()->setName('EMAIL_ADDRESS')]);

$response = $dlp->redactContent($request);
echo "Redacted: " . $response->getResult()->getData()->getBytes() . "\n";

3. Asynchronous Scanning (BigQuery Tables)

$job = (new CreateInspectJobRequest())
    ->setParent('projects/YOUR_PROJECT_ID/locations/us')
    ->setInspectJob(new \Google\Cloud\Dlp\V2\InspectJob())
        ->setBigQueryTable(new \Google\Cloud\Dlp\V2\BigQueryTable())
            ->setProjectId('YOUR_PROJECT_ID')
            ->setDatasetId('YOUR_DATASET')
            ->setTableId('YOUR_TABLE')
        ->setInfoTypes([new InfoType()->setName('CREDIT_CARD')]);

$operation = $dlp->createInspectJob($job);
$jobName = $operation->getName();
// Poll for completion (see `getInspectJob`).

4. Data Profiling (Column Statistics)

$profileRequest = (new GetColumnDataProfileRequest())
    ->setName('projects/YOUR_PROJECT_ID/locations/us/dataProfiles/YOUR_PROFILE_ID');

$profile = $dlp->getColumnDataProfile($profileRequest);
print_r($profile->getColumnStatistics());

5. Handling Files (e.g., CSV, JSON)

$fileItem = new \Google\Cloud\Dlp\V2\ContentItem\File();
$fileItem->setBytes(file_get_contents('data.csv'));
$fileItem->setMimeType('text/csv');

$request = (new InspectContentRequest())
    ->setItem(new \Google\Cloud\Dlp\V2\ContentItem())
        ->setFile($fileItem)
    ->setInfoTypes([new InfoType()->setName('PHONE_NUMBER')]);

$response = $dlp->inspectContent($request);

Integration Tips

Laravel Service Provider

Register the DLP client in AppServiceProvider:

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;

public function register()
{
    $this->app->singleton(DlpServiceClient::class, function () {
        return new DlpServiceClient();
    });
}

Dependency Injection

Inject the client into controllers/services:

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;

class DataScannerService {
    public function __construct(private DlpServiceClient $dlp) {}

    public function scanText(string $text): array {
        // Use $this->dlp->inspectContent(...)
    }
}

Batch Processing

For large datasets, use asynchronous jobs (InspectJob) to avoid timeouts:

$job = $dlp->createInspectJob($request);
while (!$dlp->getInspectJob($job->getName())->getState()->getValue() === 'DONE') {
    sleep(5); // Poll every 5 seconds
}

Custom InfoTypes

Extend detection rules by combining multiple InfoType objects:

$infoTypes = [
    new InfoType()->setName('US_SOCIAL_SECURITY_NUMBER'),
    new InfoType()->setName('CREDIT_CARD'),
    new InfoType()->setName('EMAIL_ADDRESS'),
];

Error Handling

Wrap API calls in try-catch blocks:

try {
    $response = $dlp->inspectContent($request);
} catch (\Google\ApiCore\ApiException $e) {
    \Log::error("DLP Error: " . $e->getMessage());
    throw new \RuntimeException("Failed to scan data", 0, $e);
}

Logging

Enable debug logging for troubleshooting:

$dlp = new DlpServiceClient([
    'logger' => new \Monolog\Logger('dlp', [
        new \Monolog\Handler\StreamHandler('php://stderr', \Monolog\Logger::DEBUG),
    ]),
]);

Gotchas and Tips

Pitfalls

1. Authentication Issues

  • Symptom: Google\Auth\Exception\GoogleAuthException with "Could not load credentials".
  • Fix:
    • Ensure GOOGLE_APPLICATION_CREDENTIALS points to a valid service account JSON key.
    • For local development, use:
      export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account.json"
      
    • Avoid hardcoding credentials in code (use environment variables or Laravel's .env).

2. Quota Exceeded Errors

  • Symptom: RESOURCE_EXHAUSTED or QUOTA_EXCEEDED.
  • Fix:
    • Check DLP Quotas and request increases if needed.
    • Use asynchronous jobs (InspectJob) for large datasets to avoid timeouts.
    • Implement exponential backoff for retries:
      use Google\ApiCore\Retry\RetrySettings;
      
      $retrySettings = new RetrySettings()
          ->setMaxAttempts(3)
          ->setInitialBackoff(1.0)
          ->setMaxBackoff(60.0);
      
      $dlp = new DlpServiceClient(['retrySettings' => $retrySettings]);
      

3. Large Payloads

  • Symptom: INVALID_ARGUMENT for large files (>10MB).
  • Fix:
    • Use asynchronous jobs for files >10MB.
    • For text, split into chunks and process sequentially.

4. Deprecated Features

  • Symptom: Warnings about deprecated DataCatalog actions.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope