PHP code example of blashbrook / papiclient

1. Go to this page and download the library: Download blashbrook/papiclient 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/ */

    

blashbrook / papiclient example snippets


class YourComponent extends Component
{
    public $deliveryOptionIDChanged;
    
    public function mount()
    {
        $this->deliveryOptionIDChanged = session('DeliveryOptionID', 8);
    }
    
    public function updatedDeliveryOptionIDChanged($value)
    {
        session(['DeliveryOptionID' => $value]);
    }
}

private $availableDeliveryOptions = [
    'Mailing Address' => 'Mail',           // Database value => Display name
    'Email Address' => 'Email',            // Database value => Display name
    'Phone 1' => 'Phone',                  // Database value => Display name
    'TXT Messaging' => 'Text Messaging'    // Database value => Display name
];

class YourParentComponent extends Component
{
    public $deliveryOptionIDChanged;
    
    public function mount()
    {
        // Set from session (recommended)
        $this->deliveryOptionIDChanged = session('DeliveryOptionID', 8);
        
        // OR set from user preference
        // $this->deliveryOptionIDChanged = auth()->user()->preferred_delivery_option ?? 8;
        
        // OR set hardcoded default
        // $this->deliveryOptionIDChanged = 8;
    }
    
    // Optional: Update session when value changes
    public function updatedDeliveryOptionIDChanged($value)
    {
        session(['DeliveryOptionID' => $value]);
    }
}

// Migration examples
Schema::create('delivery_options', function (Blueprint $table) {
    $table->id();
    $table->integer('DeliveryOptionID')->unique();
    $table->string('DeliveryOption');
    $table->timestamps();
});

// Seeder examples
DeliveryOption::create(['DeliveryOptionID' => 1, 'DeliveryOption' => 'Mailing Address']);
DeliveryOption::create(['DeliveryOptionID' => 2, 'DeliveryOption' => 'Email Address']);
DeliveryOption::create(['DeliveryOptionID' => 3, 'DeliveryOption' => 'Phone 1']);
DeliveryOption::create(['DeliveryOptionID' => 8, 'DeliveryOption' => 'TXT Messaging']);

   private $availableDeliveryOptions = [
       'Mailing Address' => 'Mail',
       'Email Address' => 'Email',
       'Phone 1' => 'Phone',
       'TXT Messaging' => 'Text Messaging',
       'Push Notification' => 'Push Alerts',  // New option
   ];
   

private $availableDeliveryOptions = [
    'Mailing Address' => 'Postal Mail',     // Changed from 'Mail'
    'Email Address' => 'Electronic Mail',   // Changed from 'Email'
    'Phone 1' => 'Voice Call',              // Changed from 'Phone'
    'TXT Messaging' => 'SMS',               // Changed from 'Text Messaging'
];

class YourComponent extends Component
{
    public $selectedSchool;
    
    public function mount()
    {
        $this->selectedSchool = session('PatronUDF_School', '');
    }
    
    #[On('patronUdfUpdated')]
    public function handleUdfUpdate($data)
    {
        if ($data['label'] === 'School') {
            $this->selectedSchool = $data['value'];
            // Handle school selection logic here
        }
    }
}

class AddressComponent extends Component
{
    public $selectedPostalCode;
    public $userCity;
    public $userState;
    
    public function mount()
    {
        $this->selectedPostalCode = session('PostalCodeID', null);
    }
    
    #[On('postalCodeUpdated')]
    public function handlePostalCodeUpdate($data)
    {
        $this->userCity = $data['city'];
        $this->userState = $data['state'];
        // Auto-populate address fields
        $this->updateAddressFromPostalCode($data);
    }
    
    private function updateAddressFromPostalCode($postalData)
    {
        // Handle postal code selection logic
        $this->dispatch('addressUpdated', $postalData);
    }
}

// When user selects a new postal code:
// 1. updatedSelectedPostalCodeChanged() fires automatically
// 2. Session is updated: session(['PostalCodeID' => $newValue])
// 3. Event is dispatched: postalCodeUpdated with full location data
// 4. Parent component receives event and can update other fields

// Tests automatically create test data
PatronUdf::create([
    'PatronUdfID' => 1,
    'Label' => 'School',
    'Display' => true,
    'Values' => 'Elementary School,Middle School,High School,College',
    'Required' => true
]);

PostalCode::create([
    'PostalCodeID' => 1,
    'PostalCode' => '80202',
    'City' => 'Denver',
    'State' => 'CO',
    'County' => 'Denver County',
    'CountryID' => 1
]);

// Examples from tests - verifying event dispatch
$component->set('selectedPatronUDFChanged', 'College');

$component->assertDispatched('patronUdfUpdated', [
    'label' => 'School',
    'value' => 'College', 
    'displayName' => 'College'
]);

// Verify session persistence
$component->set('selectedPostalCodeChanged', 1);
$this->assertEquals(1, Session::get('PostalCodeID'));

// Verify session loading on component mount
Session::put('PatronUDF_School', 'High School');
$component = Livewire::test(PatronUDFSelectFlux::class, [
    'patronUdfLabel' => 'School'
]);
$this->assertEquals('High School', $component->get('selectedPatronUDFChanged'));

// Test dynamic option loading
$options = $component->get('options');
$this->assertCount(4, $options);

// Test filtering functionality
$component->call('filterOptions', 'Denver');
$filteredOptions = $component->get('filteredOptions');
$this->assertCount(1, $filteredOptions);

class YourComponent extends Component
{
    public $selectedSchool;
    
    public function mount()
    {
        $this->selectedSchool = session('PatronUDF_School', '');
    }
    
    #[On('patronUdfUpdated')]
    public function handleUdfUpdate($data)
    {
        if ($data['label'] === 'School') {
            $this->selectedSchool = $data['value'];
            // Handle school selection logic here
        }
    }
}

// Migration examples
Schema::create('patron_udfs', function (Blueprint $table) {
    $table->id();
    $table->integer('PatronUdfID')->unique();
    $table->string('Label');           // e.g., 'School', 'Department', 'Grade'
    $table->boolean('Display')->default(true);
    $table->text('Values')->nullable(); // Comma-separated values
    $table->boolean('Required')->default(false);
    $table->string('DefaultValue')->nullable();
    $table->timestamps();
});

// Seeder examples
PatronUdf::create([
    'PatronUdfID' => 1,
    'Label' => 'School',
    'Display' => true,
    'Values' => 'Elementary School,Middle School,High School,College,Adult Education',
    'Required' => true
]);

PatronUdf::create([
    'PatronUdfID' => 2,
    'Label' => 'Department',
    'Display' => true,
    'Values' => 'Math,Science,English,History,Art,Music',
    'Required' => false
]);

// In your component
public function mount()
{
    $this->selectedGrade = session('PatronUDF_Grade', '');
}

public function updatedSelectedGrade($value)
{
    session(['PatronUDF_Grade' => $value]);
}

#[On('patronUdfUpdated')]
public function handlePatronUdfUpdate($data)
{
    // $data contains:
    // - 'label': The UDF label (e.g., 'School')
    // - 'value': Selected value (e.g., 'High School')
    // - 'displayName': Display name (customizable)
    
    match($data['label']) {
        'School' => $this->updateSchoolPreferences($data['value']),
        'Department' => $this->updateDepartmentSettings($data['value']),
        default => null
    };
}

// Create a custom component extending PatronUDFSelectFlux
class CustomSchoolSelectFlux extends PatronUDFSelectFlux
{
    protected function getCustomDisplayName(string $value): string
    {
        return match($value) {
            'Elementary School' => '🏫 Elementary (K-5)',
            'Middle School' => '🏛️ Middle School (6-8)',
            'High School' => '🎓 High School (9-12)',
            'College' => '🏛️ College/University',
            default => $value
        };
    }
}

class AddressComponent extends Component
{
    public $selectedPostalCode;
    public $userCity;
    public $userState;
    
    public function mount()
    {
        $this->selectedPostalCode = session('PostalCodeID', null);
    }
    
    #[On('postalCodeUpdated')]
    public function handlePostalCodeUpdate($data)
    {
        $this->userCity = $data['city'];
        $this->userState = $data['state'];
        // Auto-populate address fields
        $this->updateAddressFromPostalCode($data);
    }
    
    private function updateAddressFromPostalCode($postalData)
    {
        // Handle postal code selection logic
        $this->dispatch('addressUpdated', $postalData);
    }
}

// Migration examples
Schema::create('postal_codes', function (Blueprint $table) {
    $table->id();
    $table->integer('PostalCodeID')->unique();
    $table->string('PostalCode', 10);      // e.g., '80202', '80202-1234'
    $table->string('City', 100);
    $table->string('State', 2);            // State abbreviation
    $table->string('County', 100)->nullable();
    $table->integer('CountryID')->default(1);
    $table->timestamps();
    
    $table->index(['State', 'City']);
    $table->index('PostalCode');
});

// Seeder examples
PostalCode::create([
    'PostalCodeID' => 1,
    'PostalCode' => '80202',
    'City' => 'Denver',
    'State' => 'CO',
    'County' => 'Denver County',
    'CountryID' => 1
]);

PostalCode::create([
    'PostalCodeID' => 2,
    'PostalCode' => '80203',
    'City' => 'Denver',
    'State' => 'CO',
    'County' => 'Denver County',
    'CountryID' => 1
]);

public $selectedState = 'CO';
public $availablePostalCodes = [];

public function updatedSelectedState($state)
{
    // Re-render postal code component with new filter
    $this->dispatch('updatePostalCodeFilter', ['State' => $state]);
}

class AddressFormComponent extends Component
{
    public $selectedPostalCode;
    public $address = [
        'city' => '',
        'state' => '',
        'postal_code' => '',
        'county' => ''
    ];
    
    #[On('postalCodeUpdated')]
    public function handlePostalCodeSelection($data)
    {
        $this->address = [
            'city' => $data['city'],
            'state' => $data['state'], 
            'postal_code' => $data['postalCode'],
            'county' => $data['county']
        ];
        
        // Auto-populate form fields
        $this->dispatch('addressFieldsUpdated', $this->address);
    }
}

#[On('postalCodeUpdated')]
public function handlePostalCodeUpdate($data)
{
    // $data contains:
    // - 'id': Database ID
    // - 'postalCodeId': PostalCodeID field
    // - 'city': City name
    // - 'state': State abbreviation
    // - 'postalCode': Postal code
    // - 'county': County name
    // - 'countryId': Country ID
    // - 'displayText': Formatted display string
    
    $this->updateLocationPreferences($data);
    $this->loadNearbyServices($data['postalCode']);
    $this->calculateShippingCosts($data);
}

// Manual session management
public function mount()
{
    $this->selectedPostalCode = session('PostalCodeID', null);
}

public function updatedSelectedPostalCode($value)
{
    session(['PostalCodeID' => $value]);
}

class CustomPostalCodeSelectFlux extends PostalCodeSelectFlux
{
    protected function customFormatDisplay(PostalCode $postalCode): string
    {
        return "{$postalCode->City} ({$postalCode->PostalCode}) - {$postalCode->County}";
    }
}

public function searchPostalCodes($searchTerm)
{
    $this->filterOptions($searchTerm);
    $this->render(); // Re-render with filtered options
}

// In a custom extended component
protected function loadPostalCodes(): void
{
    $this->options = PostalCode::select(/* fields */)
        ->limit(500) // Limit initial load
        ->get();
}
`
  use Blashbrook\PAPIClient\PAPIClient;

  protected PAPIClient $papiclient;

  public function __construct(PAPIClient $papiclient) {
        $this->papiclient = $papiclient;
  }

  use Blashbrook\PAPIClient\PAPIClient;

  protected PAPIClient $papiclient;

  public function boot(PAPIClient $papiclient) {
    $this->papiclient = $papiclient;
  }
`
// Validate PAPI Access Key
$response = $this->papiclient->method('GET')->uri('apikeyvalidate')->execRequest();
bash
php artisan test --filter=DeliveryOptionSelectFluxTest

Tests/
├── Unit/
│   ├── PatronUDFSelectFluxTest.php      # Unit tests for PatronUDF component
│   ├── PostalCodeSelectFluxTest.php     # Unit tests for PostalCode component
│   └── PAPIClientTest.php               # Unit tests for API client
├── Feature/
│   ├── LivewireComponentsTest.php       # Feature tests for all components
│   └── PAPIClientTest.php               # Feature tests for API client
└── Integration/
    └── PAPIClientIntegrationTest.php     # Integration tests with real API
bash
# PatronUDFSelectFlux tests
vendor/bin/phpunit Tests/Unit/PatronUDFSelectFluxTest.php
vendor/bin/phpunit --filter PatronUDFSelectFlux

# PostalCodeSelectFlux tests
vendor/bin/phpunit Tests/Unit/PostalCodeSelectFluxTest.php
vendor/bin/phpunit --filter PostalCodeSelectFlux

# All Livewire component feature tests
vendor/bin/phpunit Tests/Feature/LivewireComponentsTest.php
bash
composer dump-autoload
bash
# Clear Laravel caches
php artisan cache:clear
php artisan view:clear
php artisan config:clear

# Ensure Database migrations are up to date
php artisan migrate:refresh --env=testing