PHP code example of azaharizaman / nexus-data-privacy

1. Go to this page and download the library: Download azaharizaman/nexus-data-privacy library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

azaharizaman / nexus-data-privacy example snippets


use Nexus\DataPrivacy\Contracts\ConsentManagerInterface;
use Nexus\DataPrivacy\Enums\ConsentPurpose;
use Nexus\DataPrivacy\Enums\LawfulBasisType;
use Nexus\DataPrivacy\ValueObjects\DataSubjectId;

public function __construct(
    private readonly ConsentManagerInterface $consentManager
) {}

// Grant consent
$consent = $this->consentManager->grantConsent(
    subjectId: DataSubjectId::fromPartyId('party-12345'),
    purpose: ConsentPurpose::MARKETING_EMAIL,
    lawfulBasis: LawfulBasisType::CONSENT,
    expiresAt: new \DateTimeImmutable('+1 year'),
    metadata: ['ip_address' => '192.168.1.1', 'source' => 'web_form']
);

// Check if consent is active
$hasConsent = $this->consentManager->hasActiveConsent(
    subjectId: DataSubjectId::fromPartyId('party-12345'),
    purpose: ConsentPurpose::MARKETING_EMAIL
); // Returns: bool

// Withdraw consent
$this->consentManager->withdrawConsent(
    consentId: $consent->getId(),
    reason: 'User requested via preference center'
);

// Renew consent before expiry
$renewed = $this->consentManager->renewConsent(
    consentId: $consent->getId(),
    newExpiresAt: new \DateTimeImmutable('+2 years')
);

use Nexus\DataPrivacy\Contracts\DataSubjectRequestManagerInterface;
use Nexus\DataPrivacy\Enums\RequestType;
use Nexus\DataPrivacy\ValueObjects\DataSubjectId;

public function __construct(
    private readonly DataSubjectRequestManagerInterface $dsrManager
) {}

// Create an access request
$request = $this->dsrManager->createRequest(
    subjectId: DataSubjectId::fromEmail('[email protected]'),
    type: RequestType::ACCESS,
    metadata: ['verification_method' => 'email_otp']
);

// Verify the request
$this->dsrManager->verifyRequest($request->getId());

// Process the request (moves to IN_PROGRESS)
$this->dsrManager->startProcessing($request->getId());

// Execute the request through handler
$result = $this->dsrManager->executeRequest(
    requestId: $request->getId(),
    handlerResult: ['export_url' => 'https://...', 'expires_at' => '...']
);

// Complete the request
$this->dsrManager->completeRequest(
    requestId: $request->getId(),
    result: $result
);

// Get overdue requests for monitoring
$overdue = $this->dsrManager->getOverdueRequests();

use Nexus\DataPrivacy\Contracts\RetentionPolicyManagerInterface;
use Nexus\DataPrivacy\Enums\DataCategory;
use Nexus\DataPrivacy\Enums\RetentionCategory;

public function __construct(
    private readonly RetentionPolicyManagerInterface $retentionManager
) {}

// Create a retention policy
$policy = $this->retentionManager->createPolicy(
    name: 'Customer Invoice Retention',
    dataCategory: DataCategory::FINANCIAL,
    retentionMonths: 84, // 7 years
    autoDelete: false,   // Require manual review
    description: 'Retain invoices for tax compliance'
);

// Find applicable policies for a data category
$policies = $this->retentionManager->findPoliciesForCategory(DataCategory::FINANCIAL);

// Get items due for deletion
$dueItems = $this->retentionManager->getItemsDueForDeletion();

// Execute retention (delete expired data)
$this->retentionManager->executeRetention(
    policyId: $policy->getId(),
    dryRun: true // Preview what would be deleted
);

use Nexus\DataPrivacy\Contracts\BreachRecordManagerInterface;
use Nexus\DataPrivacy\Enums\BreachSeverity;
use Nexus\DataPrivacy\Enums\DataCategory;

public function __construct(
    private readonly BreachRecordManagerInterface $breachManager
) {}

// Report a data breach
$breach = $this->breachManager->reportBreach(
    title: 'Unauthorized Database Access',
    description: 'External actor gained access to customer table',
    discoveredAt: new \DateTimeImmutable(),
    affectedSubjectCount: 1500,
    affectedCategories: [DataCategory::CONTACT, DataCategory::FINANCIAL],
    severity: BreachSeverity::HIGH
);

// Notify regulatory authority (within 72 hours for GDPR)
$this->breachManager->notifyRegulator(
    breachId: $breach->getId(),
    authorityName: 'ICO',
    notifiedAt: new \DateTimeImmutable(),
    referenceNumber: 'ICO-2024-12345'
);

// Record containment actions
$this->breachManager->recordContainmentAction(
    breachId: $breach->getId(),
    action: 'Revoked compromised API keys',
    performedBy: 'security-team',
    performedAt: new \DateTimeImmutable()
);

// Resolve the breach
$this->breachManager->resolveBreach(
    breachId: $breach->getId(),
    resolution: 'All affected users notified, credentials reset, security audit completed',
    resolvedAt: new \DateTimeImmutable()
);

use Nexus\DataPrivacy\Contracts\ProcessingActivityManagerInterface;
use Nexus\DataPrivacy\Enums\DataCategory;
use Nexus\DataPrivacy\Enums\LawfulBasisType;

public function __construct(
    private readonly ProcessingActivityManagerInterface $ropaManager
) {}

// Register a processing activity
$activity = $this->ropaManager->registerActivity(
    name: 'Customer Order Processing',
    purpose: 'Process and fulfill customer orders',
    lawfulBasis: LawfulBasisType::CONTRACT,
    dataCategories: [DataCategory::CONTACT, DataCategory::FINANCIAL, DataCategory::TRANSACTION],
    dataSubjectCategories: ['customers', 'shipping_recipients'],
    recipients: ['payment_processor', 'shipping_provider'],
    retentionPeriod: '7 years',
    technicalMeasures: ['encryption_at_rest', 'tls_1_3', 'access_controls'],
    organizationalMeasures: ['staff_training', 'data_minimization', 'access_reviews']
);

// Check if DPIA is 

use Nexus\DataPrivacy\Contracts\External\PartyProviderInterface;

final readonly class PartyAdapter implements PartyProviderInterface
{
    public function __construct(
        private PartyManagerInterface $partyManager
    ) {}
    
    public function partyExists(string $partyId): bool
    {
        return $this->partyManager->exists($partyId);
    }
    
    public function getPersonalData(string $partyId): array
    {
        $party = $this->partyManager->findById($partyId);
        return [
            'name' => $party->getName(),
            'email' => $party->getEmail(),
            'phone' => $party->getPhone(),
            // ... other personal data fields
        ];
    }
    
    public function deletePersonalData(string $partyId): void
    {
        $this->partyManager->anonymize($partyId);
    }
    
    // ... implement other methods
}

use Nexus\DataPrivacy\Contracts\External\AuditLoggerInterface;

final readonly class AuditLoggerAdapter implements AuditLoggerInterface
{
    public function __construct(
        private AuditLogManagerInterface $auditLogger
    ) {}
    
    public function log(string $action, string $entityType, string $entityId, array $metadata = []): void
    {
        $this->auditLogger->log(
            entityId: $entityId,
            action: $action,
            description: "Privacy action: {$action} on {$entityType}",
            metadata: $metadata
        );
    }
    
    // ... implement other methods
}

// AppServiceProvider.php
public function register(): void
{
    $this->app->singleton(
        PartyProviderInterface::class,
        PartyAdapter::class
    );
    
    $this->app->singleton(
        AuditLoggerInterface::class,
        AuditLoggerAdapter::class
    );
    
    $this->app->singleton(
        ConsentQueryInterface::class,
        EloquentConsentRepository::class
    );
    
    $this->app->singleton(
        ConsentPersistInterface::class,
        EloquentConsentRepository::class
    );
    
    // ... bind other interfaces
}

// Enforces GDPR-specific rules:
// - 30-day response deadline for DSARs
// - 72-hour breach notification to regulators
// - Data Protection Impact Assessments (DPIA)
// - Mandatory DPO appointment checks

// Enforces PDPA-specific rules:
// - 21-day response deadline for DSARs
// - Sector-specific