ElephantIO / elephant.io

Send events to a socket.io server through PHP
https://elephantio.github.io/elephant.io/
MIT License
108 stars 34 forks source link

set headers as an associative array #4

Closed laszlo-karpati closed 1 year ago

laszlo-karpati commented 1 year ago

Refactor: Allow setting headers as an associative array

In this commit, I have refactored the code to enable the use of associative arrays for setting headers in the $options['headers'] and the $options['context']['headers'] configurations. Previously, headers were defined as a list of strings, but now you can use key-value pairs for a more intuitive and maintainable approach.

Usage

Before (DEPRECATED):

$client = new Client(Client::engine($version, $url, [
    'headers' => [
        'X-My-Header: websocket rocks',
        sprintf('Authorization: %s ' . $token),
        sprintf('User: %s', $userName),
    ]
]), $logger);

After:

$client = new Client(Client::engine($version, $url, [
    'headers' => [
        'X-My-Header' => 'websocket rocks',
        'Authorization' => $token,
        'User' => $userName,
    ]
]), $logger);

Refactor's reasons:

  1. Improved Readability and Maintainability: With this enhancement, we can define headers using key-value pairs, eliminating the need for string manipulation operations (e.g., substring, sprintf, regex) to format and read headers. This results in cleaner and more readable code.

  2. Alignment with Modern Practices: Many modern HTTP client libraries, including popular ones like Axios in the JavaScript world, utilize headers as key-value pairs. By adopting this approach, the codebase aligns with contemporary development practices, making it more accessible to developers familiar with these standards.

  3. Flexibility in Header Customization: This change provides a straightforward way to override the 'Host' header. For instance, it allows you to specify a custom 'Host' when connecting directly to an IP address. This added flexibility simplifies scenarios where fine-grained control over headers is required.