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

Smarty Streets Bundle Laravel Package

blackknight467/smarty-streets-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require blackknight467/smarty-streets-bundle:^1.0
    

    Add to app/AppKernel.php:

    new blackknight467\SmartyStreetsBundle\SmartyStreetsBundle(),
    
  2. Configuration: Add to config/packages/smarty_streets.yaml (Symfony 4+) or app/config/config.yml (Symfony 2):

    smarty_streets:
        auth_id: '%env(SMARTY_STREETS_AUTH_ID)%'
        auth_token: '%env(SMARTY_STREETS_AUTH_TOKEN)%'
    
  3. First Use Case: Verify an address via controller:

    $result = $this->get('blackknight467.smarty_streets')->verifyUSStreetAddressText(
        '1600 Pennsylvania Ave NW, Washington, DC 20500'
    );
    

Where to Look First

  • Service Container: The bundle exposes blackknight467.smarty_streets as a service.
  • Interfaces: Check SimpleSmartyStreetsUSAddressInterface for entity integration.
  • Documentation: The README covers basic usage, but refer to SmartyStreets API docs for advanced features.

Implementation Patterns

Core Workflows

  1. Text-Based Verification:

    // Controller
    $response = $this->get('blackknight467.smarty_streets')
        ->verifyUSStreetAddressText($rawAddressString);
    
  2. Entity Integration:

    // Entity (e.g., UserAddress.php)
    class UserAddress implements SimpleSmartyStreetsUSAddressInterface
    {
        private $street1;
        private $street2;
        private $city;
        private $state;
        private $zipcode;
    
        // Getters for each field (required by interface)
    }
    
    // Controller
    $address = new UserAddress();
    $address->setStreet1('1600 Pennsylvania Ave NW');
    $address->setCity('Washington');
    // ... set other fields
    $response = $this->get('blackknight467.smarty_streets')->verifyUSStreetAddress($address);
    
  3. Batch Processing: Use the verifyUSStreetAddressBatchText() or verifyUSStreetAddressBatch() methods for bulk validation:

    $addresses = ['addr1', 'addr2', 'addr3'];
    $results = $this->get('blackknight467.smarty_streets')->verifyUSStreetAddressBatchText($addresses);
    
  4. Autocomplete:

    $suggestions = $this->get('blackknight467.smarty_streets')
        ->autocompleteUSStreetAddressText('1600 Pennsylvania', 'DC');
    

Integration Tips

  • Form Handling: Use the bundle in form validation (e.g., Symfony’s Validator):

    $validator = $this->get('validator');
    $errors = $validator->validate($addressEntity);
    
  • Event Listeners: Trigger validation on entity creation/update:

    // src/EventListener/AddressValidationListener.php
    public function onAddressCreate(AddressEvent $event)
    {
        $service = $this->container->get('blackknight467.smarty_streets');
        $service->verifyUSStreetAddress($event->getAddress());
    }
    
  • Caching Responses: Cache API responses to avoid rate limits (e.g., using Symfony’s cache component):

    $cache = $this->get('cache.app');
    $cacheKey = md5($addressString);
    if (!$cached = $cache->get($cacheKey)) {
        $cached = $this->get('blackknight467.smarty_streets')->verifyUSStreetAddressText($addressString);
        $cache->set($cacheKey, $cached, 3600); // Cache for 1 hour
    }
    
  • Error Handling: Wrap API calls in try-catch blocks to handle SmartyStreetsException:

    try {
        $result = $service->verifyUSStreetAddressText($address);
    } catch (SmartyStreetsException $e) {
        $this->addFlash('error', 'Address validation failed: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication:

    • Issue: Hardcoding auth_id/auth_token in config.yml exposes credentials.
    • Fix: Use environment variables (Symfony 4+) or parameter bags (Symfony 2):
      # config/packages/smarty_streets.yaml
      smarty_streets:
          auth_id: '%env(SMARTY_STREETS_AUTH_ID)%'
          auth_token: '%env(SMARTY_STREETS_AUTH_TOKEN)%'
      
      Or in Symfony 2:
      parameters:
          smarty_streets.auth_id: %SMARTY_STREETS_AUTH_ID%
          smarty_streets.auth_token: %SMARTY_STREETS_AUTH_TOKEN%
      
  2. Rate Limits:

    • Issue: SmartyStreets enforces rate limits. Batch operations or rapid calls may hit limits.
    • Fix:
      • Implement exponential backoff for retries.
      • Cache responses aggressively (see Integration Tips above).
      • Use the SmartyStreets Queue API for high-volume processing.
  3. Entity Interface Requirements:

    • Issue: The SimpleSmartyStreetsUSAddressInterface requires all fields (street1, city, state, zipcode, etc.), even if unused. Missing getters will throw errors.
    • Fix: Implement all required methods, even if they return null or defaults:
      public function getStreet2() { return null; }
      
  4. Deprecated Symfony 2:

    • Issue: The bundle is designed for Symfony 2 and may not work out-of-the-box with Symfony 4/5/6.
    • Fix:
      • Use make:bundle to create a Symfony 4+ compatible version.
      • Replace appKernel.php with config/bundles.php.
      • Update service wiring (e.g., services.yaml).
  5. Response Parsing:

    • Issue: Raw API responses may not match expected formats (e.g., nested arrays vs. objects).
    • Fix: Inspect the response structure:
      $response = $service->verifyUSStreetAddressText($address);
      dd($response); // Debug the structure
      
      Adjust your code to handle variations (e.g., $response['result']['metadata']['record_count']).

Debugging

  1. Enable API Debugging: Add debug: true to config to log raw API responses:

    smarty_streets:
        auth_id: '%env(SMARTY_STREETS_AUTH_ID)%'
        auth_token: '%env(SMARTY_STREETS_AUTH_TOKEN)%'
        debug: true  # Logs raw API calls/responses
    
  2. Common Errors:

    • InvalidAuthId/InvalidAuthToken: Verify credentials in SmartyStreets dashboard.
    • InvalidAddress: Check for typos or unsupported address formats (e.g., PO boxes, military addresses).
    • NetworkError: Ensure your server can reach https://api.smartystreets.com.
  3. Logging: Use Symfony’s logger to track issues:

    $logger = $this->get('logger');
    try {
        $result = $service->verifyUSStreetAddressText($address);
    } catch (Exception $e) {
        $logger->error('SmartyStreets error', ['exception' => $e]);
    }
    

Extension Points

  1. Custom Services: Extend the bundle by creating a custom service that wraps the core functionality:

    // src/Service/CustomSmartyStreets.php
    class CustomSmartyStreets
    {
        private $service;
    
        public function __construct(SmartyStreetsService $service)
        {
            $this->service = $service;
        }
    
        public function validateAndFormat($address)
        {
            $result = $this->service->verifyUSStreetAddressText($address);
            return $this->formatResponse($result);
        }
    
        private function formatResponse($result) { /* ... */ }
    }
    
  2. Event Dispatching: Dispatch events for pre/post-validation hooks:

    // src/Event/SmartyStreetsEvent.php
    class SmartyStreetsEvent extends Event
    {
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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