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

Brawlhalla Api Bundle Laravel Package

dylandelobel/brawlhalla-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Run composer require dylandelobel/brawlhalla-api-bundle in your Laravel project. Ensure your composer.json includes "dylandelobel/brawlhalla-api-bundle": "^1.0" (or latest version).

  2. Configuration Create a config/brawlhalla_api.php file (or use brawlhalla_api_bundle.yaml if using Symfony-style config):

    return [
        'api_key' => env('BRAWL_API_KEY', ''),
    ];
    

    Add BRAWL_API_KEY to your .env:

    BRAWL_API_KEY=your_dev_key_here
    
  3. First Use Case: Fetching Clan Data Inject the BrawlhallaClient into a service/controller:

    use Dylandelobel\BrawlhallaApiBundle\Client\BrawlhallaClient;
    
    public function getClan(BrawlhallaClient $client, int $clanId) {
        $response = $client->getClan($clanId);
        return response()->json(json_decode($response->getBody(), true));
    }
    

Implementation Patterns

Core Workflows

  1. API Requests Use the client for standard endpoints:

    // Get clan details
    $client->getClan($id);
    
    // Get player stats
    $client->getPlayer($playerId);
    
    // Get match history
    $client->getMatches($playerId, ['limit' => 10]);
    
  2. Error Handling Wrap API calls in try-catch blocks:

    try {
        $response = $client->getClan($id);
        // Process response
    } catch (\Dylandelobel\BrawlhallaApiBundle\Exception\ApiException $e) {
        Log::error('Brawlhalla API Error: ' . $e->getMessage());
        return response()->json(['error' => 'Failed to fetch clan'], 500);
    }
    
  3. Rate Limiting Implement a decorator pattern to handle rate limits:

    class RateLimitedClient {
        private $client;
        private $lastRequestTime;
    
        public function __construct(BrawlhallaClient $client) {
            $this->client = $client;
        }
    
        public function getClan($id) {
            if ($this->shouldWait()) {
                sleep(1); // Adjust delay as needed
            }
            $this->lastRequestTime = time();
            return $this->client->getClan($id);
        }
    }
    
  4. Caching Responses Use Laravel’s cache layer to store API responses:

    public function getCachedClan(BrawlhallaClient $client, int $id) {
        return Cache::remember("brawlhalla_clan_{$id}", now()->addHours(1), function() use ($client, $id) {
            return $client->getClan($id);
        });
    }
    
  5. Dependency Injection Bind the client in AppServiceProvider for easier testing:

    public function register() {
        $this->app->bind(BrawlhallaClient::class, function ($app) {
            return new BrawlhallaClient($app['config']['brawlhalla_api.api_key']);
        });
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Never hardcode BRAWL_API_KEY in config files. Use .env strictly.
    • Restrict API key permissions in the Brawlhalla developer portal to read-only where possible.
  2. Rate Limits

    • The API enforces 60 requests per minute. Exceeding this returns 429 Too Many Requests.
    • Tip: Use exponential backoff for retries:
      $attempts = 0;
      $maxAttempts = 3;
      $delay = 1000; // ms
      
      while ($attempts < $maxAttempts) {
          try {
              return $client->getClan($id);
          } catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
              if ($e->getStatusCode() === 429 && $attempts < $maxAttempts) {
                  usleep($delay);
                  $delay *= 2;
                  $attempts++;
              } else {
                  throw $e;
              }
          }
      }
      
  3. Response Parsing

    • The bundle returns raw Response objects. Always decode JSON manually:
      $json = json_decode($response->getBody(), true);
      if (json_last_error() !== JSON_ERROR_NONE) {
          throw new \RuntimeException('Invalid JSON response');
      }
      
  4. Endpoint Limitations

    • Some endpoints (e.g., getMatches) require pagination. Handle next_page in responses:
      $matches = json_decode($response->getBody(), true);
      if (isset($matches['next_page'])) {
          $nextMatches = $client->get($matches['next_page']);
          $matches = array_merge($matches['data'], json_decode($nextMatches->getBody(), true)['data']);
      }
      
  5. Testing

    • Mock the BrawlhallaClient in tests:
      $mock = Mockery::mock(BrawlhallaClient::class);
      $mock->shouldReceive('getClan')
           ->once()
           ->andReturn(new Response(200, [], json_encode(['id' => 123])));
      
      $this->app->instance(BrawlhallaClient::class, $mock);
      

Tips

  1. Laravel-Specific Extensions

    • Create a facade for convenience:
      // app/Facades/Brawlhalla.php
      public static function clan($id) {
          return app(BrawlhallaClient::class)->getClan($id);
      }
      
      Register in AppServiceProvider:
      Facade::register('Brawlhalla', \App\Facades\Brawlhalla::class);
      
      Usage:
      $clan = Brawlhalla::clan(123);
      
  2. Event Dispatching

    • Trigger events on API responses for analytics:
      $response = $client->getPlayer($id);
      event(new \App\Events\BrawlhallaPlayerFetched(
          json_decode($response->getBody(), true)
      ));
      
  3. Queue API Calls

    • Offload heavy API calls to queues:
      Queue::push(new FetchClanJob($client, $clanId));
      
      Job:
      public function handle() {
          $response = $this->client->getClan($this->clanId);
          // Store or process result
      }
      
  4. Logging

    • Log API calls for debugging:
      Log::debug('Brawlhalla API Call', [
          'endpoint' => 'clan/' . $id,
          'response' => $response->getBody(),
      ]);
      
  5. Documentation Gaps

    • The bundle lacks PHPDoc for methods. Add these to autocompletion:
      /**
       * @param int $clanId
       * @return \Symfony\Component\HttpFoundation\Response
       * @throws \Dylandelobel\BrawlhallaApiBundle\Exception\ApiException
       */
      public function getClan(int $clanId);
      
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle