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

Google Api Bundle Laravel Package

dvlpm/google-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require dvlpm/google-api-bundle in your project root. Ensure your project uses Symfony 4+ and PHP 7.4+ (implicitly required by the underlying google-api-php-client).

  2. Credentials Setup

    • Download your credentials.json from the Google Cloud Console.
    • Place it in config/google_api_bundle/credentials.json (default) or configure a custom path (see below).
  3. First Use Case Inject the Google\Client service into a controller/service and use it to interact with a Google API (e.g., Drive, Calendar). Example:

    use Google\Client;
    use Google\Service\Drive;
    
    #[Route('/drive/files', name: 'drive_files')]
    public function listFiles(Client $client): JsonResponse
    {
        $driveService = new Drive($client);
        $results = $driveService->files->listFiles();
        return $this->json($results->getFiles());
    }
    

Implementation Patterns

Dependency Injection

  • Autowiring: The bundle auto-configures the Google\Client service, so you can inject it directly via type-hinting (as shown above).
  • Custom Scopes: Define required OAuth scopes in config/packages/google_api.yaml:
    google_api:
        scopes:
            - https://www.googleapis.com/auth/drive.readonly
            - https://www.googleapis.com/auth/userinfo.email
    

Service Integration

  • Service Layer Abstraction: Create a dedicated service class to encapsulate Google API logic (e.g., GoogleDriveService):

    class GoogleDriveService {
        public function __construct(private Client $client) {}
    
        public function getFiles(): array {
            $drive = new Drive($this->client);
            return $drive->files->listFiles()->getFiles();
        }
    }
    

    Register it as a service in services.yaml if needed.

  • Token Management: The bundle automatically handles token persistence via token_file (default: var/google_api_bundle/tokens.json). Override the path in config if needed.

Workflows

  1. OAuth Flow:

    • Use the Client service to generate auth URLs:
      $authUrl = $client->createAuthUrl();
      
    • Handle callbacks with $client->authenticate($code).
  2. API Calls:

    • Initialize a Google API service (e.g., Drive, Calendar) with the Client:
      $service = new \Google\Service\Drive($client);
      
    • Execute API methods (e.g., $service->files->create()).
  3. Batch Operations:

    • Use the Client to configure batch requests:
      $batch = $client->createBatch();
      $batch->add($service->files->create(...));
      

Gotchas and Tips

Pitfalls

  1. Credentials Path:

    • If credentials.json isn’t found, the bundle throws a RuntimeException. Verify the path in config/google_api.yaml or place the file in the default location.
    • Fix: Double-check file permissions (chmod 644 credentials.json).
  2. Token File Permissions:

    • The tokens.json file must be writable by the web server. Default location: var/google_api_bundle/tokens.json.
    • Fix: Run mkdir -p var/google_api_bundle && chmod -R 775 var/google_api_bundle.
  3. Scopes Misconfiguration:

    • Missing or incorrect scopes in google_api.yaml will cause OAuth failures.
    • Debug: Check the Client instance for errors:
      if ($client->isAuthRequired()) {
          throw new \RuntimeException('Authentication required. Check scopes.');
      }
      
  4. Deprecation Warnings:

    • The underlying google-api-php-client may emit deprecation notices. Update the package:
      composer update google/apiclient
      

Debugging

  • Enable Debugging: Add this to config/packages/google_api.yaml to log errors:

    google_api:
        debug: true
    

    Check var/log/dev.log for OAuth/Client errors.

  • Manual Client Initialization: Override the bundle’s Client service in config/services.yaml for custom configurations:

    services:
        Google_Client:
            class: Google\Client
            calls:
                - [setDeveloperKey, ['%env(GOOGLE_API_KEY)%']]
    

Extension Points

  1. Custom Client Configuration: Extend the bundle’s GoogleApiBundle to add pre-configured services:

    // src/GoogleApiBundle/DependencyInjection/GoogleApiExtension.php
    public function load(array $configs, ContainerBuilder $container) {
        $container->setParameter('google_api.custom_scope', $config['custom_scope']);
    }
    
  2. Event Listeners: Subscribe to the bundle’s events (e.g., google_api.client_initialized) to modify the Client instance dynamically.

  3. Testing: Mock the Client service in tests:

    $this->container->set('Google_Client', $this->createMock(Client::class));
    

Tips

  • Environment Variables: Use .env for sensitive data (e.g., GOOGLE_CREDENTIALS_PATH):

    google_api:
        credentials_file: '%env(GOOGLE_CREDENTIALS_PATH)%'
    
  • API Service Caching: Cache API responses (e.g., Drive files) using Symfony’s cache system:

    $cache = $this->container->get('cache.app');
    $cachedFiles = $cache->get('drive_files');
    if (!$cachedFiles) {
        $cachedFiles = $driveService->listFiles();
        $cache->set('drive_files', $cachedFiles, 3600);
    }
    
  • Service-to-Service Auth: For server-to-server auth (no user interaction), use service account credentials:

    google_api:
        credentials_file: 'config/google_api_bundle/service-account.json'
        auth_class: Google_Auth_AssertionCredentials
    

    Configure assertions in code:

    $client->setAuthConfig($credentialsFile);
    $client->setAssertionCredentials(new AssertionCredentials(...));
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky