PHP code example of azaharizaman / nexus-sanctions

1. Go to this page and download the library: Download azaharizaman/nexus-sanctions 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-sanctions example snippets


use Nexus\Sanctions\Services\SanctionsScreener;
use Nexus\Sanctions\Enums\SanctionsList;

// Create screener with your repository implementation
$screener = new SanctionsScreener($sanctionsRepository);

// Screen a party against multiple sanctions lists
$result = $screener->screen(
    party: $party,
    lists: [SanctionsList::OFAC, SanctionsList::UN, SanctionsList::EU],
    options: ['similarity_threshold' => 0.85]
);

// Check results
if ($result->

use Nexus\Sanctions\Services\SanctionsScreener;
use Nexus\Sanctions\Enums\SanctionsList;

$screener = new SanctionsScreener($repository, $logger);

// Screen against all major lists
$result = $screener->screen(
    party: $party,
    lists: [
        SanctionsList::OFAC,
        SanctionsList::UN,
        SanctionsList::EU,
        SanctionsList::UK_HMT,
    ],
    options: [
        'similarity_threshold' => 0.85,
        'phonetic_matching' => true,
        'token_based' => true,
        'include_aliases' => true,
    ]
);

// Analyze results
echo "Matches found: " . $result->getMatchesCount() . "\n";
echo "Risk level: " . $result->overallRiskLevel . "\n";
echo "Processing time: " . $result->processingTimeMs . "ms\n";

if ($result->

// Screen multiple parties efficiently
$results = $screener->screenMultiple(
    parties: [$party1, $party2, $party3],
    lists: [SanctionsList::OFAC, SanctionsList::UN],
    options: ['similarity_threshold' => 0.80]
);

foreach ($results as $partyId => $result) {
    if ($result->hasMatches) {
        $this->notifyCompliance($partyId, $result);
    }
}

// Screen a single name against specific list
$matches = $screener->screenName(
    name: 'John Smith',
    list: SanctionsList::OFAC,
    options: ['threshold' => 0.85]
);

foreach ($matches as $match) {
    echo "Match: {$match->matchedName}\n";
    echo "Score: {$match->similarityScore}%\n";
    echo "List: {$match->list->getName()}\n";
    echo "Action: {$match->matchStrength->getRecommendedAction()}\n";
}

// Calculate similarity between two names
$similarity = $screener->calculateSimilarity(
    name1: 'Mohammed Ali',
    name2: 'Muhammad Ali'
);

echo "Similarity: " . ($similarity * 100) . "%\n"; // ~92%

use Nexus\Sanctions\Services\PepScreener;
use Nexus\Sanctions\Enums\PepLevel;

$pepScreener = new PepScreener($repository, $logger);

// Screen for PEP status
$pepProfiles = $pepScreener->screenForPep(
    party: $party,
    options: [
        '"Country: {$profile->country}\n";
    echo "Level: {$profile->level->value}\n";
    echo "Active: " . ($profile->isActive() ? 'Yes' : 'No') . "\n";
    echo "Risk Score: {$profile->getRiskScore()}\n";
}

// Determine overall PEP risk level
$riskLevel = $pepScreener->assessRiskLevel($party, $pepProfiles);

echo "Risk Level: {$riskLevel->value}\n";

// Get EDD 

// Check if Enhanced Due Diligence is  $pepProfiles)) {
    $this->initiateEddWorkflow($party, [
        'source_of_wealth' => true,
        'source_of_funds' => true,
        'ongoing_monitoring' => 'monthly',
    ]);
}

// Find family members and close associates
$relatedProfiles = $pepScreener->checkRelatedPersons($party);

foreach ($relatedProfiles as $related) {
    echo "Related PEP: {$related->name}\n";
    echo "Relationship: " . ($related->additionalInfo['relationship'] ?? 'Unknown') . "\n";
}

use Nexus\Sanctions\Services\PeriodicScreeningManager;
use Nexus\Sanctions\Enums\ScreeningFrequency;

$manager = new PeriodicScreeningManager($screener, $logger);

// Schedule based on risk level
$schedule = $manager->scheduleScreening(
    partyId: 'party-123',
    frequency: ScreeningFrequency::MONTHLY,
    options: [
        'lists' => [SanctionsList::OFAC, SanctionsList::UN],
        'start_date' => new DateTimeImmutable(),
        'metadata' => ['risk_tier' => 'medium'],
    ]
);

echo "Next screening: " . $schedule['next_screening_date']->format('Y-m-d') . "\n";

// Execute all due screenings
$summary = $manager->executeScheduledScreenings(
    asOfDate: new DateTimeImmutable(),
    options: [
        'batch_size' => 100,
        'continue_on_error' => true,
    ]
);

echo "Executed: {$summary['total_executed']}\n";
echo "Successful: {$summary['successful']}\n";
echo "Failed: {$summary['failed']}\n";
echo "Matches found: {$summary['total_matches']}\n";

// Increase frequency for higher risk party
$manager->updateScreeningFrequency(
    partyId: 'party-123',
    newFrequency: ScreeningFrequency::WEEKLY
);

// Cancel screening when relationship ends
$manager->cancelScheduledScreening('party-123');

interface SanctionsScreenerInterface
{
    public function screen(
        PartyInterface $party,
        array $lists,
        array $options = []
    ): ScreeningResult;
    
    public function screenMultiple(
        array $parties,
        array $lists,
        array $options = []
    ): array;
    
    public function screenName(
        string $name,
        SanctionsList $list,
        array $options = []
    ): array;
    
    public function calculateSimilarity(string $name1, string $name2): float;
}

interface PepScreenerInterface
{
    public function screenForPep(
        PartyInterface $party,
        array $options = []
    ): array;
    
    public function checkRelatedPersons(PartyInterface $party): array;
    
    public function assessRiskLevel(
        PartyInterface $party,
        array $pepProfiles
    ): PepLevel;
    
    public function 

interface PeriodicScreeningManagerInterface
{
    public function scheduleScreening(
        string $partyId,
        ScreeningFrequency $frequency,
        array $options = []
    ): array;
    
    public function executeScheduledScreenings(
        DateTimeImmutable $asOfDate,
        array $options = []
    ): array;
    
    public function updateScreeningFrequency(
        string $partyId,
        ScreeningFrequency $newFrequency
    ): void;
    
    public function cancelScheduledScreening(string $partyId): void;
}

interface SanctionsRepositoryInterface
{
    public function findByName(
        string $name,
        SanctionsList $list,
        float $similarityThreshold = 0.85
    ): array;
    
    public function findById(string $entryId, SanctionsList $list): ?array;
    
    public function findPepByName(
        string $name,
        float $similarityThreshold = 0.85
    ): array;
    
    public function findPepById(string $pepId): ?array;
    
    public function getRelatedPersons(string $pepId): array;
    
    public function isListAvailable(SanctionsList $list): bool;
}

interface PartyInterface
{
    public function getId(): string;
    public function getName(): string;
    public function getType(): string; // 'INDIVIDUAL' or 'ORGANIZATION'
    public function getDateOfBirth(): ?DateTimeImmutable;
    public function getNationality(): ?string;
    public function getCountryOfIncorporation(): ?string;
    public function getAliases(): array;
    public function getIdentificationDocuments(): array;
}

enum SanctionsList: string
{
    case OFAC = 'ofac';          // US Treasury
    case UN = 'un';              // United Nations
    case EU = 'eu';              // European Union
    case UK_HMT = 'uk_hmt';      // UK Treasury
    case AU_DFAT = 'au_dfat';    // Australia
    case CA_OSFI = 'ca_osfi';    // Canada
    case JP_METI = 'jp_meti';    // Japan
    case CH_SECO = 'ch_seco';    // Switzerland
    
    public function getName(): string;
    public function getAuthority(): string;
}

enum MatchStrength: string
{
    case EXACT = 'exact';    // 100% match
    case HIGH = 'high';      // 85-99% match
    case MEDIUM = 'medium';  // 70-84% match
    case LOW = 'low';        // 50-69% match
    case NONE = 'none';      // <50% match
    
    public function getSimilarityRange(): array;
    public function getRecommendedAction(): string;
    public function 

enum PepLevel: string
{
    case HIGH = 'high';      // Senior officials, heads of state
    case MEDIUM = 'medium';  // Mid-level officials
    case LOW = 'low';        // Former PEPs, honorary positions
    case NONE = 'none';      // Not a PEP
    
    public function getEddRequirements(): array;
    public function getRiskScore(): int;
    public function 

enum ScreeningFrequency: string
{
    case REAL_TIME = 'real_time';     // Every transaction
    case DAILY = 'daily';              // Every day
    case WEEKLY = 'weekly';            // Every 7 days
    case MONTHLY = 'monthly';          // Every 30 days
    case QUARTERLY = 'quarterly';      // Every 90 days
    case SEMI_ANNUAL = 'semi_annual';  // Every 180 days
    case ANNUAL = 'annual';            // Every 365 days
    
    public function getDays(): int;
    public function getHours(): int;
    public function calculateNextScreeningDate(DateTimeImmutable $from): DateTimeImmutable;
}

final class ScreeningResult
{
    public readonly string $screeningId;
    public readonly string $partyId;
    public readonly string $partyName;
    public readonly string $partyType;
    public readonly bool $hasMatches;
    public readonly array $matches;          // SanctionsMatch[]
    public readonly array $pepProfiles;      // PepProfile[]
    public readonly bool $blic function isClean(): bool;
    public function hasPepMatches(): bool;
    public function getHighestMatchStrength(): ?string;
    
    public static function clean(...): self;  // Factory for clean results
}

final class SanctionsMatch
{
    public readonly string $listEntryId;
    public readonly SanctionsList $list;
    public readonly string $matchedName;
    public readonly MatchStrength $matchStrength;
    public readonly float $similarityScore;  // 0-100
    public readonly array $additionalInfo;
    public readonly DateTimeImmutable $matchedAt;
    
    // Accessors for additional info
    public function getAliases(): array;
    public function getDateOfBirth(): ?DateTimeImmutable;
    public function getNationality(): ?string;
    public function getPassportNumber(): ?string;
    public function getNationalId(): ?string;
    public function getAddress(): ?string;
    public function getProgram(): ?string;
    public function getRemarks(): ?string;
    
    public function 

final class PepProfile
{
    public readonly string $pepId;
    public readonly string $name;
    public readonly PepLevel $level;
    public readonly string $position;
    public readonly string $country;
    public readonly ?string $organization;
    public readonly ?DateTimeImmutable $startDate;
    public readonly ?DateTimeImmutable $endDate;
    public readonly array $relatedPersons;
    public readonly array $additionalInfo;
    public readonly DateTimeImmutable $identifiedAt;
    
    public function isActive(): bool;
    public function isFormer(): bool;  // Left position >12 months ago
    public function 

use Nexus\Sanctions\Exceptions\InvalidPartyException;

try {
    $screener->screen($party, $lists);
} catch (InvalidPartyException $e) {
    $errors = $e->getValidationErrors();
    $

use Nexus\Sanctions\Exceptions\ScreeningFailedException;

try {
    $screener->screen($party, $lists);
} catch (ScreeningFailedException $e) {
    $this->logger->error('Screening failed', [
        'message' => $e->getMessage(),
        'code' => $e->getCode(),
    ]);
}

use Nexus\Sanctions\Exceptions\SanctionsListUnavailableException;

try {
    $screener->screen($party, [SanctionsList::OFAC]);
} catch (SanctionsListUnavailableException $e) {
    $list = $e->getSanctionsList();
    $this->alertOperations("List {$list->value} unavailable");
}

namespace App\Repositories;

use Nexus\Sanctions\Contracts\SanctionsRepositoryInterface;
use Nexus\Sanctions\Enums\SanctionsList;

final readonly class EloquentSanctionsRepository implements SanctionsRepositoryInterface
{
    public function findByName(
        string $name,
        SanctionsList $list,
        float $similarityThreshold = 0.85
    ): array {
        // Query your database or external API
        return SanctionsEntry::query()
            ->where('list', $list->value)
            ->whereRaw('SIMILARITY(name, ?) > ?', [$name, $similarityThreshold])
            ->get()
            ->toArray();
    }
    
    public function findPepByName(
        string $name,
        float $similarityThreshold = 0.85
    ): array {
        // Query PEP database
        return PepEntry::query()
            ->whereRaw('SIMILARITY(name, ?) > ?', [$name, $similarityThreshold])
            ->get()
            ->toArray();
    }
    
    public function isListAvailable(SanctionsList $list): bool
    {
        return Cache::remember(
            "sanctions_list_{$list->value}_available",
            3600,
            fn() => $this->checkListAvailability($list)
        );
    }
    
    // ... implement other methods
}

namespace App\Adapters;

use Nexus\Sanctions\Contracts\PartyInterface;
use App\Models\Customer;

final readonly class CustomerPartyAdapter implements PartyInterface
{
    public function __construct(
        private Customer $customer
    ) {}
    
    public function getId(): string
    {
        return $this->customer->id;
    }
    
    public function getName(): string
    {
        return $this->customer->legal_name ?? $this->customer->name;
    }
    
    public function getType(): string
    {
        return $this->customer->is_company ? 'ORGANIZATION' : 'INDIVIDUAL';
    }
    
    public function getDateOfBirth(): ?\DateTimeImmutable
    {
        return $this->customer->date_of_birth 
            ? new \DateTimeImmutable($this->customer->date_of_birth) 
            : null;
    }
    
    public function getNationality(): ?string
    {
        return $this->customer->nationality;
    }
    
    public function getAliases(): array
    {
        return $this->customer->aliases ?? [];
    }
    
    // ... implement other methods
}

// AppServiceProvider.php
use Nexus\Sanctions\Contracts\SanctionsRepositoryInterface;
use Nexus\Sanctions\Contracts\SanctionsScreenerInterface;
use Nexus\Sanctions\Contracts\PepScreenerInterface;
use Nexus\Sanctions\Services\SanctionsScreener;
use Nexus\Sanctions\Services\PepScreener;

public function register(): void
{
    $this->app->singleton(
        SanctionsRepositoryInterface::class,
        EloquentSanctionsRepository::class
    );
    
    $this->app->singleton(SanctionsScreenerInterface::class, function ($app) {
        return new SanctionsScreener(
            $app->make(SanctionsRepositoryInterface::class),
            $app->make(LoggerInterface::class)
        );
    });
    
    $this->app->singleton(PepScreenerInterface::class, function ($app) {
        return new PepScreener(
            $app->make(SanctionsRepositoryInterface::class),
            $app->make(LoggerInterface::class)
        );
    });
}

namespace App\Services;

use Nexus\Sanctions\Contracts\SanctionsScreenerInterface;
use Nexus\Sanctions\Contracts\PepScreenerInterface;
use Nexus\Sanctions\Enums\SanctionsList;

final readonly class CustomerOnboardingService
{
    public function __construct(
        private SanctionsScreenerInterface $sanctionsScreener,
        private PepScreenerInterface $pepScreener,
    ) {}
    
    public function screenCustomer(Customer $customer): OnboardingResult
    {
        $party = new CustomerPartyAdapter($customer);
        
        // Screen against sanctions lists
        $sanctionsResult = $this->sanctionsScreener->screen(
            party: $party,
            lists: [SanctionsList::OFAC, SanctionsList::UN, SanctionsList::EU],
        );
        
        if ($sanctionsResult->

packages/Sanctions/
├── src/
│   ├── Contracts/
│   │   ├── PartyInterface.php
│   │   ├── PepScreenerInterface.php
│   │   ├── PeriodicScreeningManagerInterface.php
│   │   ├── SanctionsRepositoryInterface.php
│   │   └── SanctionsScreenerInterface.php
│   ├── Enums/
│   │   ├── MatchStrength.php
│   │   ├── PepLevel.php
│   │   ├── SanctionsList.php
│   │   └── ScreeningFrequency.php
│   ├── Exceptions/
│   │   ├── InvalidPartyException.php
│   │   ├── SanctionsException.php
│   │   ├── SanctionsListUnavailableException.php
│   │   └── ScreeningFailedException.php
│   ├── Services/
│   │   ├── PepScreener.php
│   │   ├── PeriodicScreeningManager.php
│   │   └── SanctionsScreener.php
│   └── ValueObjects/
│       ├── PepProfile.php
│       ├── SanctionsMatch.php
│       └── ScreeningResult.php
├── tests/
├── composer.json
└── README.md