Weave 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

Hub Sdk Laravel Package

datacore/hub-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require datacore/hub-sdk
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Datacore\HubSdk\HubSdkServiceProvider"
    
  2. Configuration Locate the config file at config/hub-sdk.php and set:

    'client_id' => env('HUB_CLIENT_ID'),
    'client_secret' => env('HUB_CLIENT_SECRET'),
    'jwks_url' => env('HUB_JWKS_URL'),
    'api_url' => env('HUB_API_URL'),
    
  3. First Use Case: JWT Validation Validate a JWT token in a controller/middleware:

    use Datacore\HubSdk\JwtValidator;
    
    $validator = new JwtValidator();
    $isValid = $validator->validate($jwtToken); // Returns bool
    
  4. First Use Case: API Call Fetch an OAuth token and call the Hub API:

    use Datacore\HubSdk\HubClient;
    
    $client = new HubClient();
    $response = $client->get('/endpoint'); // Automatically handles OAuth
    

Implementation Patterns

Workflow: OAuth Token Management

  1. Lazy Token Fetching The SDK caches tokens by default (configurable via cache_seconds in hub-sdk.php).

    $client = new HubClient(['cache_seconds' => 300]); // 5-minute cache
    
  2. Manual Token Refresh Force a new token if needed:

    $client->refreshToken();
    

Workflow: JWT Validation in Middleware

Extend Laravel’s middleware to validate incoming JWTs:

namespace App\Http\Middleware;

use Datacore\HubSdk\JwtValidator;
use Closure;

class ValidateHubJwt
{
    public function handle($request, Closure $next)
    {
        $validator = new JwtValidator();
        if (!$validator->validate($request->bearerToken())) {
            return response()->json(['error' => 'Invalid JWT'], 401);
        }
        return $next($request);
    }
}

Integration Tips

  • Symfony Bundle Compatibility If using Symfony, register the bundle in config/bundles.php:

    return [
        // ...
        Datacore\HubSdkBundle\HubSdkBundle::class => ['all' => true],
    ];
    
  • Custom Headers/Requests Pass additional headers or query params:

    $response = $client->get('/endpoint', [
        'headers' => ['X-Custom-Header' => 'value'],
        'query' => ['param' => 'value']
    ]);
    
  • Error Handling Catch HubSdkException for API errors:

    try {
        $response = $client->post('/endpoint', ['data' => 'payload']);
    } catch (HubSdkException $e) {
        \Log::error('Hub API Error: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Token Cache Stale Data If cache_seconds is too high, you may hit rate limits or miss revoked tokens. Fix: Set a lower cache duration (e.g., 180 seconds) or disable caching (cache_seconds => 0).

  2. JWKS Fetch Failures If the JWKS URL is unreachable, JWT validation will fail silently. Fix: Add retry logic or log errors:

    $validator = new JwtValidator();
    $validator->setJwksFallback(true); // Graceful fallback (returns false)
    
  3. OAuth Scope Mismatches The SDK does not validate scopes by default. Ensure your client_id has the required scopes configured in the Hub admin panel.

  4. Symfony vs. Laravel Quirks

    • In Symfony, use dependency injection:
      # config/services.yaml
      services:
          Datacore\HubSdk\HubClient: ~
      
    • In Laravel, manually instantiate or bind the client in the service container:
      $this->app->bind(HubClient::class, function () {
          return new HubClient();
      });
      

Debugging Tips

  • Enable Verbose Logging Set debug to true in hub-sdk.php to log OAuth flows and JWT validation:

    'debug' => env('APP_DEBUG', false),
    
  • Inspect Raw Responses Access the underlying Guzzle client for debugging:

    $client->getGuzzleClient()->getConfig(); // Inspect config
    $client->getGuzzleClient()->getHandlerStack(); // Inspect middleware
    

Extension Points

  1. Custom JWT Validation Extend JwtValidator to add logic:

    class CustomJwtValidator extends JwtValidator
    {
        protected function validateClaims(array $decoded): bool
        {
            // Add custom claims validation
            return parent::validateClaims($decoded) && $decoded['custom_claim'] === 'value';
        }
    }
    
  2. Intercept API Requests Use Guzzle middleware to log or modify requests:

    $client = new HubClient();
    $stack = $client->getGuzzleClient()->getHandlerStack();
    $stack->push(Middleware::tap(function (RequestInterface $request) {
        \Log::debug('Hub API Request:', $request->getBody());
    }));
    
  3. Mocking for Tests Replace the HubClient with a mock in tests:

    $mockClient = Mockery::mock(HubClient::class);
    $mockClient->shouldReceive('get')->andReturn(['data' => 'mocked']);
    $this->app->instance(HubClient::class, $mockClient);
    
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.
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names