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

Parser Laravel Package

guzzle/parser

guzzle/parser provides lightweight message parsing utilities for Guzzle, helping you parse HTTP request/response messages, headers, and related components. Useful when working with raw HTTP strings or building tooling around Guzzle’s message format.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require guzzle/parser
    
    • No configuration required; the package is dependency-free and self-contained.
  2. First Use Case: Parsing Cookies

    use Guzzle\Parser\Cookie\CookieParser;
    
    $cookieHeader = 'name1=value1; name2=value2; expires=Wed, 21 Oct 2023 07:28:00 GMT';
    $cookies = CookieParser::parseHeader($cookieHeader);
    
    // Output: Array of `Guzzle\Parser\Cookie\Cookie` objects
    
  3. First Use Case: Parsing URIs

    use Guzzle\Parser\UriTemplate\UriTemplate;
    
    $template = 'http://example.com/{user}';
    $uri = UriTemplate::expand($template, ['user' => 'john']);
    
    // Output: 'http://example.com/john'
    
  4. Where to Look First

    • Documentation: Guzzle Parser Docs (for Guzzle 3 compatibility notes).
    • Source Code: Focus on:
      • Guzzle\Parser\Cookie\CookieParser (for cookie handling).
      • Guzzle\Parser\UriTemplate\UriTemplate (for URI templating).
      • Guzzle\Parser\Header\HeaderParser (for HTTP headers).

Implementation Patterns

1. Cookie Parsing Workflow

  • Input: Raw cookie strings (e.g., from Set-Cookie headers or Cookie headers).
  • Output: Structured Cookie objects with properties like name, value, expires, domain, etc.
  • Pattern:
    $parser = new CookieParser();
    $cookies = $parser->parseHeader($rawCookieHeader);
    
    foreach ($cookies as $cookie) {
        if ($cookie->isExpired()) {
            // Handle expired cookies
        }
    }
    
  • Integration Tip: Use with Guzzle HTTP client to parse cookies from responses:
    $client = new \GuzzleHttp\Client();
    $response = $client->request('GET', 'https://example.com');
    $cookies = CookieParser::parseHeader($response->getHeaderLine('Set-Cookie'));
    

2. URI Templating

  • Use Case: Dynamically generate URLs from templates (e.g., API endpoints).
  • Pattern:
    $template = 'https://api.example.com/v1/users/{userId}/posts/{postId}';
    $uri = UriTemplate::expand($template, [
        'userId' => 123,
        'postId' => 456
    ]);
    // Output: 'https://api.example.com/v1/users/123/posts/456'
    
  • Integration Tip: Combine with Guzzle HTTP client for dynamic requests:
    $client = new \GuzzleHttp\Client();
    $response = $client->get($uri);
    

3. HTTP Header Parsing

  • Use Case: Extract structured data from raw HTTP headers (e.g., Content-Range, Link).
  • Pattern:
    use Guzzle\Parser\Header\HeaderParser;
    
    $contentRange = 'bytes 1000-2000/5000';
    $range = HeaderParser::parseContentRange($contentRange);
    // Output: ['firstBytePos' => 1000, 'lastBytePos' => 2000, 'totalBytes' => 5000]
    
  • Integration Tip: Parse headers from Guzzle responses:
    $response = $client->request('GET', 'https://example.com/large-file');
    $range = HeaderParser::parseContentRange($response->getHeaderLine('Content-Range'));
    

4. Validation and Sanitization

  • Pattern: Use parsers to validate/sanitize user input (e.g., URLs, cookies).
  • Example:
    $userInput = 'name=test; domain=evil.com';
    try {
        $cookies = CookieParser::parseHeader($userInput);
        // Reject if domain is suspicious
    } catch (\InvalidArgumentException $e) {
        // Handle malformed input
    }
    

Gotchas and Tips

Pitfalls

  1. Guzzle 3 Compatibility

    • This package is a read-only subtree split of Guzzle 3. Some APIs may differ from Guzzle 4/5/6.
    • Example: UriTemplate in Guzzle 3 uses expand(), while newer versions may use resolve().
    • Fix: Stick to the documented methods for this package.
  2. Cookie Parsing Quirks

    • Edge Cases:
      • Malformed cookies (e.g., missing = or ;) may throw InvalidArgumentException.
      • Tip: Wrap parsing in a try-catch block for robustness.
    • Time Handling:
      • Cookie expiration times are parsed as DateTime objects. Ensure your server’s timezone is configured correctly to avoid expired misclassifications.
  3. URI Template Strictness

    • Strict Mode: By default, UriTemplate throws exceptions for unmatched variables.
    • Tip: Use UriTemplate::expandStrict() for strict validation or expand() for lenient parsing (fills missing vars with null).
  4. Header Parser Limitations

    • No RFC Compliance: Some headers (e.g., Link) may not support all RFC 7230/7231 variants.
    • Tip: Pre-process headers if strict compliance is needed (e.g., normalize Link headers before parsing).

Debugging Tips

  1. Log Raw Inputs

    • Always log raw strings (e.g., cookie headers, URIs) before parsing to debug malformed input:
      \Log::debug('Raw cookie header:', [$rawCookieHeader]);
      
  2. Use var_dump for Objects

    • Inspect parsed objects with var_dump to understand their structure:
      var_dump($cookies[0]->getDomain());
      
  3. Test Edge Cases

    • Test with:
      • Empty strings.
      • Unicode characters (e.g., name=用户).
      • Non-standard formats (e.g., Set-Cookie: id=123;; Secure).

Extension Points

  1. Custom Cookie Parsing

    • Extend Guzzle\Parser\Cookie\Cookie to add custom attributes:
      class CustomCookie extends \Guzzle\Parser\Cookie\Cookie {
          public function getCustomAttribute() { ... }
      }
      
    • Override CookieParser to handle your custom format.
  2. URI Template Extensions

    • Subclass UriTemplate to add custom variable resolvers:
      class CustomUriTemplate extends \Guzzle\Parser\UriTemplate\UriTemplate {
          protected function resolveVariable($name, $value) { ... }
      }
      
  3. Header Parser Hooks

    • Monkey-patch HeaderParser methods (e.g., parseContentRange) if you need pre/post-processing.

Performance Notes

  • Cookie Parsing: For high-volume requests (e.g., parsing thousands of cookies), cache parsed results if the same headers repeat.
  • URI Templating: Pre-compile templates if used repeatedly (though this package doesn’t natively support it).
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours