<?php
 namespace League\OAuth2\Client\Tool; use GuzzleHttp\Exception\BadResponseException; use GuzzleHttp\Psr7\Uri; use InvalidArgumentException; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; trait ProviderRedirectTrait { protected $redirectLimit = 2; protected function followRequestRedirects(RequestInterface $request) { $response = null; $attempts = 0; while ($attempts < $this->redirectLimit) { $attempts++; $response = $this->getHttpClient()->send($request, [ 'allow_redirects' => false ]); if ($this->isRedirect($response)) { $redirectUrl = new Uri($response->getHeader('Location')[0]); $request = $request->withUri($redirectUrl); } else { break; } } return $response; } abstract public function getHttpClient(); public function getRedirectLimit() { return $this->redirectLimit; } protected function isRedirect(ResponseInterface $response) { $statusCode = $response->getStatusCode(); return $statusCode > 300 && $statusCode < 400 && $response->hasHeader('Location'); } public function getResponse(RequestInterface $request) { try { $response = $this->followRequestRedirects($request); } catch (BadResponseException $e) { $response = $e->getResponse(); } return $response; } public function setRedirectLimit($limit) { if (!is_int($limit)) { throw new InvalidArgumentException('redirectLimit must be an integer.'); } if ($limit < 1) { throw new InvalidArgumentException('redirectLimit must be greater than or equal to one.'); } $this->redirectLimit = $limit; return $this; } } 