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

Handevaluator Bundle Laravel Package

bourdeau/handevaluator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:

    composer require bourdeau/handevaluator-bundle
    

    Ensure your config/bundles.php includes:

    return [
        // ...
        Bourdeau\HandEvaluatorBundle\BourdeauHandEvaluatorBundle::class => ['all' => true],
    ];
    
  2. Service Injection: The bundle provides a HandEvaluator service. Inject it into your controller/service:

    use Bourdeau\HandEvaluatorBundle\Evaluator\HandEvaluator;
    
    class PokerController extends Controller
    {
        public function __construct(private HandEvaluator $evaluator) {}
    
        public function evaluateHand(Request $request)
        {
            $hand = $this->evaluator->evaluate($request->input('cards'));
            return response()->json($hand);
        }
    }
    
  3. First Use Case: Evaluate a 5-card hand (e.g., ['2h', '3d', '5s', '9c', 'kd']):

    $result = $this->evaluator->evaluate(['2h', '3d', '5s', '9c', 'kd']);
    // Returns: ['rank' => 'high_card', 'value' => 13, 'cards' => [...]]
    

Implementation Patterns

Core Workflows

  1. Evaluating Hands:

    • Single Hand: Use evaluate() with an array of 5 card strings (e.g., ['Ah', 'Ks', 'Qh', 'Jd', 'Tc']).
    • Multiple Hands: Loop through hands and compare results:
      $hand1 = $this->evaluator->evaluate($hand1Cards);
      $hand2 = $this->evaluator->evaluate($hand2Cards);
      $winner = $hand1['value'] > $hand2['value'] ? 'Player 1' : 'Player 2';
      
  2. Texas Hold'em Integration: Combine 2 player cards + 5 community cards:

    $playerHand = array_merge($playerCards, $communityCards);
    $evaluation = $this->evaluator->evaluate(array_slice($playerHand, 0, 5));
    
  3. Rank-Based Logic: Use the rank key to implement game rules (e.g., payouts, tiebreakers):

    $ranks = ['high_card', 'pair', 'two_pair', 'three_of_a_kind', ..., 'royal_flush'];
    if ($result['rank'] === 'flush') {
        // Handle flush-specific logic
    }
    

Integration Tips

  • Validation: Sanitize input to ensure valid card formats (e.g., regex /\b[A-Ka-k2-9][sdch]\b/).
  • Performance: Cache frequent evaluations (e.g., in a poker tournament):
    $cache = Cache::remember("hand_{$handHash}", 60, function() use ($hand) {
        return $this->evaluator->evaluate($hand);
    });
    
  • Testing: Mock the HandEvaluator service in unit tests:
    $this->app->instance(HandEvaluator::class, $mockEvaluator);
    

Gotchas and Tips

Pitfalls

  1. Card Format Strictness:

    • Input must be exactly 2 characters (e.g., Ah, not A♥ or 10d).
    • Fix: Normalize input before evaluation:
      $normalized = array_map(function($card) {
          return strtoupper(substr($card, 0, 1)) . substr($card, 1);
      }, $rawCards);
      
  2. Hand Size Assumption:

    • The evaluator expects 5 cards. For Hold'em, manually combine player/community cards:
      // ❌ Wrong: Pass 7 cards directly
      // ✅ Correct: Evaluate best 5-card subset
      $bestHand = $this->evaluator->evaluate($this->getBestFiveCards($allCards));
      
  3. Rank Naming Quirks:

    • "Straight flush" is returned as straight_flush, not sf or straightflush.
    • Tip: Use a mapping for readability:
      $rankLabels = [
          'high_card' => 'High Card',
          'pair' => 'Pair',
          'straight_flush' => 'Straight Flush',
          // ...
      ];
      

Debugging

  • Invalid Cards: Throws InvalidArgumentException. Catch and log:
    try {
        $result = $this->evaluator->evaluate($cards);
    } catch (\InvalidArgumentException $e) {
        Log::error("Invalid card in hand: " . $e->getMessage());
    }
    
  • Edge Cases: Test with:
    • Duplicate cards (e.g., ['2h', '2d']).
    • Non-standard suits (e.g., ['2x'] → will fail).

Extension Points

  1. Custom Ranks: Override the evaluator logic by extending the bundle’s Evaluator\HandEvaluator class:

    class CustomHandEvaluator extends \Bourdeau\HandEvaluatorBundle\Evaluator\HandEvaluator
    {
        protected function getRank($hand)
        {
            // Custom logic here
            return parent::getRank($hand);
        }
    }
    

    Register the service in config/services.yaml:

    services:
        App\Evaluator\CustomHandEvaluator:
            arguments: ['@hand_evaluator']
            tags: ['hand_evaluator']
    
  2. Event Listeners: Hook into hand evaluation events (if the bundle supports them; check source for EventDispatcher usage).

  3. Performance Optimization:

    • For high-frequency use (e.g., poker bots), precompute all possible hand rankings and memoize:
      $this->evaluator->setCache(new ArrayCache()); // Hypothetical method
      
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
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