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

Larachileancongress Laravel Package

unforgivencl/larachileancongress

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require unforgivencl/larachileancongress:dev-master
    

    Update config/app.php to include:

    'providers' => [
        Unforgivencl\LaraChileanCongress\LaraChileanCongressServiceProvider::class,
    ],
    'aliases' => [
        'ChileanCongress' => Unforgivencl\LaraChileanCongress\Facades\LaraChileanCongress::class,
    ],
    
  2. First Use Case Fetch all senators (default endpoint):

    $senators = ChileanCongress::senators()->getSenators()->fetch();
    

    Output: JSON array of senator data (e.g., id, name, party).


Where to Look First

  • Facade Methods: Check src/Facades/LaraChileanCongress.php for available endpoints (senators, delegates, votation, lawproject).
  • Response Handling: All responses are auto-converted from XML to JSON. Inspect src/Traits/ResponseHandler.php for parsing logic.
  • Endpoint Switching: Use setDelegates() or setSenators() to toggle between delegate/senator endpoints (default: senators).

Implementation Patterns

Core Workflows

  1. Fetching Legislators

    // Senators (default)
    $senators = ChileanCongress::senators()->getSenators()->fetch();
    
    // Delegates (requires explicit switch)
    $delegates = ChileanCongress::delegate()->setDelegates()->getDelegates()->fetch();
    

    Use case: Populate a dropdown or list view with legislator names/IDs.

  2. Votation Data

    // Senators' votation by number
    $votation = ChileanCongress::votation()
        ->number('8575') // Replace with actual votation ID
        ->getSenatorsVotation()
        ->fetch();
    

    Use case: Display votation results in a legislative tracker.

  3. Law Projects

    // Law project details
    $lawProject = ChileanCongress::lawproject()
        ->number('1') // Replace with actual law project ID
        ->getLawProject()
        ->fetch();
    

    Use case: Show law project status (e.g., "In Committee") in a legislative dashboard.


Integration Tips

  • Caching Responses Cache frequent queries (e.g., all senators) to reduce API calls:

    $senators = Cache::remember('senators_list', now()->addHours(1), function () {
        return ChileanCongress::senators()->getSenators()->fetch();
    });
    
  • Error Handling Wrap API calls in a try-catch to handle XML/JSON parsing errors:

    try {
        $data = ChileanCongress::lawproject()->number('1')->getLawProject()->fetch();
    } catch (\Exception $e) {
        Log::error("API Error: " . $e->getMessage());
        return response()->json(['error' => 'Failed to fetch data'], 500);
    }
    
  • Dynamic Endpoints Extend the facade for custom endpoints (e.g., committees):

    // In a service class
    public function getCommittees() {
        return ChileanCongress::custom()
            ->setEndpoint('committees') // Hypothetical; check package for extensibility
            ->getData()
            ->fetch();
    }
    

Gotchas and Tips

Pitfalls

  1. Endpoint Defaults

    • The package defaults to senators. Forgetting setDelegates() for delegate endpoints returns empty data.
    • Fix: Always verify the active endpoint with ChileanCongress::delegate()->setDelegates() before fetching.
  2. XML-to-JSON Quirks

    • The API’s XML structure may produce unexpected array keys (e.g., Senator[0] instead of Senator).
    • Workaround: Normalize responses post-fetch:
      $normalized = collect($rawData)->map(function ($item) {
          return array_values($item)[0]; // Flatten single-item arrays
      })->values();
      
  3. Rate Limiting

    • opendata.congreso.cl may throttle requests. Add delays between calls:
      sleep(1); // 1-second delay between API calls
      
  4. Deprecated Methods

    • The package is in early development (dev-master). Assume breaking changes in future updates.
    • Tip: Fork the repo to add missing endpoints (e.g., committees, amendments).

Debugging

  1. Raw XML Inspection To debug parsing issues, log the raw XML response:

    $rawXml = ChileanCongress::senators()->getSenators()->getRawResponse();
    Log::debug($rawXml);
    
  2. Facade Method Chaining Ensure method chaining is correct. Example of a broken call:

    // ❌ Wrong: Missing `setDelegates()`
    $delegates = ChileanCongress::delegate()->getDelegates()->fetch(); // Returns empty
    

    Fix: Always set the endpoint first.

  3. Endpoint URLs Hardcoded URLs may change. Override them in the service provider:

    // In `AppServiceProvider@boot`
    $this->app->singleton('chileancongress', function () {
        $client = new \Unforgivencl\LaraChileanCongress\ChileanCongressClient();
        $client->setBaseUrl('https://custom-api-url.cl'); // Override if needed
        return $client;
    });
    

Extension Points

  1. Add New Endpoints Extend the ChileanCongressClient class to support unsupported endpoints (e.g., committees):

    // In a custom service class
    public function getCommittees() {
        $response = Http::get('https://opendata.congreso.cl/committees');
        return json_decode($response->body(), true);
    }
    
  2. Custom Response Handling Override the ResponseHandler trait to modify JSON structure:

    // In a custom handler
    public function parseXmlToJson($xml) {
        $data = simplexml_load_string($xml);
        // Custom logic to restructure data
        return json_decode(json_encode($data), true);
    }
    
  3. Testing Mock the HTTP client for unit tests:

    $mock = Mockery::mock(\Unforgivencl\LaraChileanCongress\ChileanCongressClient::class);
    $mock->shouldReceive('getSenators')->andReturn(['data' => 'mocked']);
    $this->app->instance('chileancongress', $mock);
    
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