Skip to content

Commit

Permalink
refactor(headercredential): refactor applyToRequest method
Browse files Browse the repository at this point in the history
- Change parent class from KeyValueCredential to NullCredential
- Add headers property to store headers
- Modify constructor to accept an array of headers
- Implement applyToRequest method using array_reduce_with_keys function to apply headers to the request
  • Loading branch information
guanguans committed Feb 5, 2024
1 parent 8fb8d8b commit 2a5532a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/Foundation/Credentials/HeaderCredential.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,26 @@

namespace Guanguans\Notify\Foundation\Credentials;

class HeaderCredential extends KeyValueCredential
use Psr\Http\Message\RequestInterface;

class HeaderCredential extends NullCredential
{
public function __construct(string $value, string $key = 'Authorization')
private array $headers;

public function __construct(array $headers)
{
$this->headers = $headers;
}

public function applyToRequest(RequestInterface $request): RequestInterface
{
parent::__construct($key, $value);
return array_reduce_with_keys(
$this->headers,
static fn (RequestInterface $request, $value, string $header): RequestInterface => $request->withHeader(
$header,
$value
),
$request
);
}
}
16 changes: 16 additions & 0 deletions src/Foundation/Support/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,19 @@ public function __call($method, $parameters)
return $value;
}
}

if (! function_exists('array_reduce_with_keys')) {
/**
* @param null|mixed $carry
*
* @return null|mixed
*/
function array_reduce_with_keys(array $array, callable $callback, $carry = null)
{
foreach ($array as $key => $value) {
$carry = $callback($carry, $value, $key);
}

return $carry;
}
}

0 comments on commit 2a5532a

Please sign in to comment.