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

Navitiaio Api Component Laravel Package

canaltp/navitiaio-api-component

PHP client for the Navitia.io API. Provides a NavitiaIoApiService to perform authenticated HTTP requests (via cURL/Guzzle), with simple methods like getUsers() and support for injecting a mocked Guzzle client for testing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require canaltp/navitiaio-api-component:^1.6
    
  2. Basic Instantiation (in a Laravel service or controller):
    use CanalTP\NavitiaIoApiComponent\NavitiaIoApiService;
    
    $navitia = new NavitiaIoApiService(
        config('services.navitia.url'),
        config('services.navitia.user'),
        config('services.navitia.password')
    );
    
  3. First Use Case: Fetch all users with pagination:
    $users = $navitia->getUsers();
    foreach ($users->users as $user) {
        // Process user data
    }
    

Where to Look First

  • API Methods: Check NavitiaIoApiService for available endpoints (e.g., getUsers(), getUser($id), patchUser()).
  • Configuration: Store credentials in .env (e.g., NAVITIA_URL, NAVITIA_USER, NAVITIA_PASSWORD).
  • Testing: Use Guzzle mocks (see README) for unit tests.

Implementation Patterns

Dependency Injection (Laravel-Specific)

Register the service in config/services.php:

'navitia' => [
    'url' => env('NAVITIA_URL', 'http://navitia.local/'),
    'user' => env('NAVITIA_USER'),
    'password' => env('NAVITIA_PASSWORD'),
],

Bind the service in AppServiceProvider:

$this->app->singleton(NavitiaIoApiService::class, function ($app) {
    return new NavitiaIoApiService(
        $app['config']['services.navitia.url'],
        $app['config']['services.navitia.user'],
        $app['config']['services.navitia.password']
    );
});

Inject via constructor:

public function __construct(private NavitiaIoApiService $navitia) {}

Workflows

  1. Pagination Handling: Loop through paginated responses:

    $page = 1;
    do {
        $response = $navitia->getUsers(['page' => $page]);
        foreach ($response->users as $user) {
            // Process
        }
        $page = $response->nextPage ?? null;
    } while ($page);
    
  2. Error Handling: Wrap API calls in try-catch:

    try {
        $user = $navitia->getUser(123);
    } catch (\Exception $e) {
        Log::error("Navitia API error: " . $e->getMessage());
        // Fallback logic
    }
    
  3. Data Transformation: Use Laravel collections to shape responses:

    $users = collect($navitia->getUsers()->users)
        ->map(fn ($user) => [
            'id' => $user->id,
            'name' => $user->name,
        ]);
    

Integration Tips

  • Caching: Cache responses for read-heavy endpoints:
    $users = Cache::remember("navitia_users", now()->addHours(1), function () {
        return $navitia->getUsers();
    });
    
  • Rate Limiting: Use Laravel’s throttle middleware for API routes calling Navitia.
  • Logging: Log API requests/responses for debugging:
    $navitia->setClient($client->withMiddleware(new \GuzzleHttp\Middleware::tap(
        fn ($request, $options) => Log::debug("Navitia Request: " . $request->getUri()),
        fn ($response, $options) => Log
            ->debug("Navitia Response: " . $response->getBody())
    )));
    

Gotchas and Tips

Pitfalls

  1. Self-Signed Certificates: The package ignores self-signed cert checks (since v1.6.2), but ensure your Laravel app trusts the Navitia server’s certs if using HTTPS in production. Fix: Manually configure Guzzle to verify certs if needed:

    $client = new \GuzzleHttp\Client(['verify' => true]);
    $navitia->setClient($client);
    
  2. Deprecated Guzzle Package: Version 1.6.1 changed the Guzzle package name. If upgrading, ensure your composer.json uses:

    "guzzlehttp/guzzle": "^7.0"
    
  3. Pagination Quirks: The getUsers() method’s paginator was fixed in v1.5.0, but older versions may return incomplete data. Always check $response->nextPage for pagination.

  4. No Retry Logic: The package lacks built-in retry logic for failed requests. Implement middleware or decorate the client:

    $client->getHandler()->setHandler(
        new \GuzzleHttp\HandlerStack(
            \GuzzleHttp\HandlerStack::create()
        )
    );
    

Debugging

  • Enable Guzzle Debug:

    $navitia->setClient(new \GuzzleHttp\Client([
        'debug' => true,
    ]));
    

    Check Laravel’s storage logs for raw requests/responses.

  • Mocking for Tests: Use Guzzle’s MockHandler to simulate API responses:

    $mock = new \GuzzleHttp\Psr7\Response(200, [], json_encode(['users' => []]));
    $handler = \GuzzleHttp\HandlerStack::create(new \GuzzleHttp\Handler\MockHandler([$mock]));
    $navitia->setClient(new \GuzzleHttp\Client(['handler' => $handler]));
    

Extension Points

  1. Custom Headers: Override default headers (e.g., for API keys):

    $client = new \GuzzleHttp\Client([
        'headers' => ['X-API-Key' => config('services.navitia.api_key')],
    ]);
    $navitia->setClient($client);
    
  2. Response Decoding: Extend the service to decode responses into Laravel collections:

    class ExtendedNavitiaService extends NavitiaIoApiService {
        public function getUsersAsCollection() {
            return collect($this->getUsers()->users);
        }
    }
    
  3. Event Dispatching: Trigger events on API responses (e.g., NavitiaUsersFetched):

    $users = $navitia->getUsers();
    event(new NavitiaUsersFetched($users));
    
  4. Configuration Overrides: Dynamically set URL/credentials per request:

    $navitia->setUrl('https://staging.navitia.local/');
    $navitia->setCredentials('temp_user', 'temp_pass');
    
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme