public function testCreateNewTokenUntilOneDoesNotExist()
 {
     $this->scopeService->expects($this->once())->method('getDefaultScopes')->will($this->returnValue(['read']));
     $this->tokenRepository->expects($this->at(0))->method('tokenExists')->with($this->isType('string'))->willReturn(true);
     $this->tokenRepository->expects($this->at(1))->method('tokenExists')->with($this->isType('string'))->willReturn(false);
     $this->tokenRepository->expects($this->once())->method('save')->will($this->returnArgument(0));
     $owner = $this->createMock(TokenOwnerInterface::class);
     $client = $this->createMock(Client::class);
     $token = $this->tokenService->createToken('http://www.example.com', $owner, $client, []);
     $this->assertEquals(40, strlen($token->getToken()));
 }
 /**
  * @throws OAuth2Exception (invalid_request) When grant type was not 'code'
  */
 public function createAuthorizationResponse(ServerRequestInterface $request, Client $client, TokenOwnerInterface $owner = null) : ResponseInterface
 {
     $queryParams = $request->getQueryParams();
     // We must validate some parameters first
     $responseType = $queryParams['response_type'] ?? null;
     if ($responseType !== self::GRANT_RESPONSE_TYPE) {
         throw OAuth2Exception::invalidRequest(sprintf('The desired grant type must be "code", but "%s" was given', $responseType));
     }
     // We try to fetch the redirect URI from query param as per spec, and if none found, we just use
     // the first redirect URI defined in the client
     $redirectUri = $queryParams['redirect_uri'] ?? $client->getRedirectUris()[0];
     // If the redirect URI cannot be found in the list, we throw an error as we don't want the user
     // to be redirected to an unauthorized URL
     if (!$client->hasRedirectUri($redirectUri)) {
         throw OAuth2Exception::invalidRequest('Redirect URI does not match the registered one');
     }
     // Scope and state allow to perform additional validation
     $scope = $queryParams['scope'] ?? null;
     $state = $queryParams['state'] ?? null;
     $authorizationCode = $this->authorizationCodeService->createToken($redirectUri, $owner, $client, $scope);
     $uri = http_build_query(array_filter(['code' => $authorizationCode->getToken(), 'state' => $state]));
     return new Response\RedirectResponse($redirectUri . '?' . $uri);
 }