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

Grand Id Bundle Laravel Package

bsadnu/grand-id-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bsadnu/grand-id-bundle
    

    Ensure GrandIDBundle is enabled in config/bundles.php:

    return [
        // ...
        GrandID\Bundle\GrandIDBundle::class => ['all' => true],
    ];
    
  2. Configuration Add your Grand ID credentials to config/packages/grand_id.yaml:

    grand_id:
        client_id: '%env(GRAND_ID_CLIENT_ID)%'
        client_secret: '%env(GRAND_ID_CLIENT_SECRET)%'
        api_url: 'https://api.grandid.com'
    
  3. First Use Case: Authentication Inject the GrandIDService into a controller and initiate a login:

    use GrandID\Bundle\GrandIDBundle\Service\GrandIDService;
    
    class AuthController extends Controller
    {
        public function login(GrandIDService $grandID): Response
        {
            $authUrl = $grandID->getAuthUrl('http://your-callback-url.com');
            return redirect($authUrl);
        }
    }
    
  4. Database Migration Run migrations to create the required grand_id_sessions table:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

Implementation Patterns

Core Workflows

1. OAuth Flow Integration

  • Callback Handling: Use the handleCallback() method to process Grand ID responses:
    public function callback(GrandIDService $grandID, Request $request): Response
    {
        $session = $grandID->handleCallback($request);
        // Store session data in your user system
        return $this->redirectToRoute('home');
    }
    
  • Token Management: Refresh tokens automatically using refreshToken():
    $grandID->refreshToken($sessionId);
    

2. Session Management

  • Create Mock Sessions (Testing):
    $mockSession = $grandID->createMockSession([
        'user_id' => 'test123',
        'email' => 'user@example.com',
    ]);
    
  • Retrieve Stored Sessions:
    $session = $grandID->getSessionById($sessionId);
    

3. User Data Fetching

  • Fetch User Profile:
    $userData = $grandID->getUserData($accessToken);
    

4. Event Listeners

  • Subscribe to Grand ID events (e.g., grand_id.session.created) in config/services.yaml:
    services:
        App\EventListener\GrandIDListener:
            tags:
                - { name: 'kernel.event_listener', event: 'grand_id.session.created', method: 'onSessionCreated' }
    

Integration Tips

Laravel-Specific Adaptations

  1. Service Container Binding Bind the Symfony service to Laravel’s container in AppServiceProvider:

    public function register()
    {
        $this->app->singleton('grandID', function ($app) {
            return $this->app->make('grand_id.service');
        });
    }
    
  2. Request Handling Use Laravel’s Request facade with Symfony’s GrandIDService:

    use Illuminate\Support\Facades\Request;
    
    public function callback(GrandIDService $grandID): Response
    {
        $session = $grandID->handleCallback(Request::capture());
        // ...
    }
    
  3. Database Integration Extend the GrandIDSession entity to add Laravel-specific fields (e.g., user_id):

    // src/Entity/GrandIDSession.php
    namespace App\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    use GrandID\Bundle\GrandIDBundle\Entity\GrandIDSession as BaseGrandIDSession;
    
    #[ORM\Entity]
    class GrandIDSession extends BaseGrandIDSession
    {
        #[ORM\Column(type: 'integer', nullable: true)]
        private ?int $userId = null;
    }
    
  4. Mocking in Tests Use the mock system for unit tests:

    public function testGrandIDLogin()
    {
        $grandID = $this->app->make('grandID');
        $mockSession = $grandID->createMockSession(['email' => 'test@example.com']);
    
        $this->assertEquals('test@example.com', $grandID->getSessionById($mockSession->getId())->getEmail());
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated API

    • The bundle was last updated in 2018 and may not align with Grand ID’s current API. Verify endpoints (e.g., /auth, /user) against Grand ID’s latest docs.
    • Workaround: Override service methods in a custom bundle or extend the GrandIDService class.
  2. Database Schema Mismatch

    • The grand_id_sessions table assumes specific fields (e.g., session_id, access_token). Custom fields may break functionality.
    • Fix: Extend the GrandIDSession entity (as shown above) and update migrations:
      php bin/console doctrine:schema:update --force
      
  3. Token Expiry Handling

    • The bundle does not auto-refresh expired tokens. Implement a listener for grand_id.token.expired or manually check token validity:
      if ($grandID->isTokenExpired($session)) {
          $grandID->refreshToken($session->getId());
      }
      
  4. Symfony-Specific Assumptions

    • The bundle relies on Symfony’s HttpFoundation and EventDispatcher. In Laravel, wrap interactions in try-catch blocks for Request or Response objects:
      try {
          $authUrl = $grandID->getAuthUrl('http://callback.url');
      } catch (\InvalidArgumentException $e) {
          return response()->json(['error' => 'Invalid callback URL'], 400);
      }
      

Debugging Tips

  1. Enable Debug Mode Set GRAND_ID_DEBUG=true in .env to log API requests/responses:

    # config/packages/grand_id.yaml
    grand_id:
        debug: '%env(bool:GRAND_ID_DEBUG)%'
    
  2. Mock Debugging Verify mock sessions are stored correctly:

    php bin/console doctrine:query:sql "SELECT * FROM grand_id_sessions"
    
  3. API Response Validation Grand ID may return non-200 responses. Validate responses in a custom service layer:

    public function getUserData(string $token): array
    {
        $response = $this->grandID->getUserData($token);
        if ($response['status'] !== 200) {
            throw new \RuntimeException('Grand ID API error: ' . $response['body']);
        }
        return json_decode($response['body'], true);
    }
    

Extension Points

  1. Custom Session Storage Override the GrandIDSessionManager to use Laravel’s cache or session driver:

    // src/Service/CustomGrandIDSessionManager.php
    namespace App\Service;
    
    use GrandID\Bundle\GrandIDBundle\Service\GrandIDSessionManager;
    use Illuminate\Support\Facades\Cache;
    
    class CustomGrandIDSessionManager extends GrandIDSessionManager
    {
        public function saveSession($session)
        {
            Cache::put("grand_id_{$session->getId()}", $session, now()->addHours(1));
        }
    
        public function findSessionById($id)
        {
            return Cache::get("grand_id_{$id}");
        }
    }
    
  2. Event Customization Extend the GrandIDEvents class to add Laravel-specific events:

    // src/Event/GrandIDLaravelEvents.php
    namespace App\Event;
    
    use Symfony\Contracts\EventDispatcher\Event;
    
    final class GrandIDLaravelEvents
    {
        public const USER_LOGIN = 'grand_id.user.login';
    }
    
  3. API Client Wrapper Replace the underlying HTTP client (e.g., Symfony’s HttpClient) with Guzzle for Laravel:

    // src/Service/CustomGrandIDService.php
    use GuzzleHttp\Client;
    
    class CustomGrandIDService extends GrandIDService
    {
        protected function createClient()
        {
            return new Client([
                'base_uri' => $this->getApiUrl(),
                'headers' => [
                    'Accept' => 'application/json',
                ],
            ]);
        }
    }
    

Configuration Quirks

  • Environment Variables: Ensure GRAND_ID_CLIENT_ID and GRAND_ID_CLIENT_SECRET are set in .env:
    GRAND_ID_CLIENT_ID=your_client_id_here
    GRAND_ID_CLIENT_SECRET=your_secret_here
    
  • CORS Issues: Grand ID’s callback URLs must match
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime