diff --git a/src/API/Anilist/Model.php b/src/API/Anilist/Model.php index 512703b7..e0db23c9 100644 --- a/src/API/Anilist/Model.php +++ b/src/API/Anilist/Model.php @@ -118,9 +118,9 @@ final class Model { $createData = $data['data']; $mediaId = $this->getMediaIdFromMalId($data['mal_id']); - + $createData['id'] = $mediaId; - + return $this->listItem->createFull($createData); } @@ -192,22 +192,22 @@ final class Model $mediaId = $this->getMediaIdFromMalId($malId, $type); return $this->getListIdFromMediaId($mediaId); } - + /** * Get the Anilist media id from its MAL id * this way is more accurate than getting the list item id * directly from the MAL id */ - private function getListIdFromMediaId(string $mediaId) + private function getListIdFromMediaId(string $mediaId): string { $config = $this->container->get('config'); $anilistUser = $config->get(['anilist', 'username']); - + $info = $this->runQuery('ListItemIdByMediaId', [ 'id' => $mediaId, 'userName' => $anilistUser, ]); - + /* dump([ 'media_id' => $mediaId, 'userName' => $anilistUser, @@ -231,7 +231,7 @@ final class Model 'id' => $malId, 'type' => mb_strtoupper($type), ]); - + /* dump([ 'mal_id' => $malId, 'response' => $info, diff --git a/src/API/HummingbirdClient.php b/src/API/HummingbirdClient.php index 538d8aab..44ddc5c1 100644 --- a/src/API/HummingbirdClient.php +++ b/src/API/HummingbirdClient.php @@ -1,4 +1,5 @@ true, + self::OP_AUTO_ENCODING => TRUE, self::OP_TRANSFER_TIMEOUT => 100000, self::OP_MAX_REDIRECTS => 5, - self::OP_AUTO_REFERER => true, - self::OP_DISCARD_BODY => false, + self::OP_AUTO_REFERER => TRUE, + self::OP_DISCARD_BODY => FALSE, self::OP_DEFAULT_HEADERS => [], self::OP_MAX_HEADER_BYTES => Parser::DEFAULT_MAX_HEADER_BYTES, self::OP_MAX_BODY_BYTES => Parser::DEFAULT_MAX_BODY_BYTES, ]; public function __construct( - CookieJar $cookieJar = null, - HttpSocketPool $socketPool = null, - ClientTlsContext $tlsContext = null + CookieJar $cookieJar = NULL, + HttpSocketPool $socketPool = NULL, + ClientTlsContext $tlsContext = NULL ) { $this->cookieJar = $cookieJar ?? new NullCookieJar; @@ -94,12 +107,13 @@ final class HummingbirdClient implements Client { } /** @inheritdoc */ - public function request($uriOrRequest, array $options = [], CancellationToken $cancellation = null): Promise + public function request($uriOrRequest, array $options = [], CancellationToken $cancellation = NULL): Promise { return call(function () use ($uriOrRequest, $options, $cancellation) { $cancellation = $cancellation ?? new NullCancellationToken; - foreach ($options as $option => $value) { + foreach ($options as $option => $value) + { $this->validateOption($option, $value); } @@ -107,27 +121,32 @@ final class HummingbirdClient implements Client { list($request, $uri) = $this->generateRequestFromUri($uriOrRequest); $options = $options ? array_merge($this->options, $options) : $this->options; - foreach ($this->options[self::OP_DEFAULT_HEADERS] as $name => $header) { - if (!$request->hasHeader($name)) { + foreach ($this->options[self::OP_DEFAULT_HEADERS] as $name => $header) + { + if ( ! $request->hasHeader($name)) + { $request = $request->withHeaders([$name => $header]); } } /** @var array $headers */ $headers = yield $request->getBody()->getHeaders(); - foreach ($headers as $name => $header) { - if (!$request->hasHeader($name)) { + foreach ($headers as $name => $header) + { + if ( ! $request->hasHeader($name)) + { $request = $request->withHeaders([$name => $header]); } } $originalUri = $uri; - $previousResponse = null; + $previousResponse = NULL; $maxRedirects = $options[self::OP_MAX_REDIRECTS]; $requestNr = 1; - do { + do + { /** @var Request $request */ $request = yield from $this->normalizeRequestBodyHeaders($request); $request = $this->normalizeRequestHeaders($request, $uri, $options); @@ -139,10 +158,11 @@ final class HummingbirdClient implements Client { $response = yield $this->doRequest($request, $uri, $options, $previousResponse, $cancellation); // Explicit $maxRedirects !== 0 check to not consume redirect bodies if redirect following is disabled - if ($maxRedirects !== 0 && $redirectUri = $this->getRedirectUri($response)) { + if ($maxRedirects !== 0 && $redirectUri = $this->getRedirectUri($response)) + { // Discard response body of redirect responses $body = $response->getBody(); - while (null !== yield $body->read()) ; + while (NULL !== yield $body->read()) ; /** * If this is a 302/303 we need to follow the location with a GET if the original request wasn't @@ -154,19 +174,22 @@ final class HummingbirdClient implements Client { */ $method = $request->getMethod(); $status = $response->getStatus(); - $isSameHost = $redirectUri->getAuthority(false) === $originalUri->getAuthority(false); + $isSameHost = $redirectUri->getAuthority(FALSE) === $originalUri->getAuthority(FALSE); - if ($isSameHost) { + if ($isSameHost) + { $request = $request->withUri($redirectUri); - if ($status >= 300 && $status <= 303 && $method !== 'GET') { + if ($status >= 300 && $status <= 303 && $method !== 'GET') + { $request = $request->withMethod('GET'); $request = $request->withoutHeader('Transfer-Encoding'); $request = $request->withoutHeader('Content-Length'); $request = $request->withoutHeader('Content-Type'); - $request = $request->withBody(null); + $request = $request->withBody(NULL); } - } else { + } else + { // We ALWAYS follow with a GET and without any set headers or body for redirects to other hosts. $optionsWithoutHeaders = $options; unset($optionsWithoutHeaders[self::OP_DEFAULT_HEADERS]); @@ -175,19 +198,22 @@ final class HummingbirdClient implements Client { $request = $this->normalizeRequestHeaders($request, $redirectUri, $optionsWithoutHeaders); } - if ($options[self::OP_AUTO_REFERER]) { + if ($options[self::OP_AUTO_REFERER]) + { $request = $this->assignRedirectRefererHeader($request, $originalUri, $redirectUri); } $previousResponse = $response; $originalUri = $redirectUri; $uri = $redirectUri; - } else { + } else + { break; } } while (++$requestNr <= $maxRedirects + 1); - if ($maxRedirects !== 0 && $redirectUri = $this->getRedirectUri($response)) { + if ($maxRedirects !== 0 && $redirectUri = $this->getRedirectUri($response)) + { throw new TooManyRedirectsException($response); } @@ -197,37 +223,43 @@ final class HummingbirdClient implements Client { private function validateOption(string $option, $value) { - switch ($option) { + switch ($option) + { case self::OP_AUTO_ENCODING: - if (!\is_bool($value)) { + if ( ! \is_bool($value)) + { throw new \TypeError("Invalid value for OP_AUTO_ENCODING, bool expected"); } break; case self::OP_TRANSFER_TIMEOUT: - if (!\is_int($value) || $value < 0) { + if ( ! \is_int($value) || $value < 0) + { throw new \Error("Invalid value for OP_TRANSFER_TIMEOUT, int >= 0 expected"); } break; case self::OP_MAX_REDIRECTS: - if (!\is_int($value) || $value < 0) { + if ( ! \is_int($value) || $value < 0) + { throw new \Error("Invalid value for OP_MAX_REDIRECTS, int >= 0 expected"); } break; case self::OP_AUTO_REFERER: - if (!\is_bool($value)) { + if ( ! \is_bool($value)) + { throw new \TypeError("Invalid value for OP_AUTO_REFERER, bool expected"); } break; case self::OP_DISCARD_BODY: - if (!\is_bool($value)) { + if ( ! \is_bool($value)) + { throw new \TypeError("Invalid value for OP_DISCARD_BODY, bool expected"); } @@ -240,14 +272,16 @@ final class HummingbirdClient implements Client { break; case self::OP_MAX_HEADER_BYTES: - if (!\is_int($value) || $value < 0) { + if ( ! \is_int($value) || $value < 0) + { throw new \Error("Invalid value for OP_MAX_HEADER_BYTES, int >= 0 expected"); } break; case self::OP_MAX_BODY_BYTES: - if (!\is_int($value) || $value < 0) { + if ( ! \is_int($value) || $value < 0) + { throw new \Error("Invalid value for OP_MAX_BODY_BYTES, int >= 0 expected"); } @@ -262,13 +296,16 @@ final class HummingbirdClient implements Client { private function generateRequestFromUri($uriOrRequest) { - if (is_string($uriOrRequest)) { + if (is_string($uriOrRequest)) + { $uri = $this->buildUriFromString($uriOrRequest); $request = new Request($uri); - } elseif ($uriOrRequest instanceof Request) { + } elseif ($uriOrRequest instanceof Request) + { $uri = $this->buildUriFromString($uriOrRequest->getUri()); $request = $uriOrRequest; - } else { + } else + { throw new HttpException( 'Request must be a valid HTTP URI or Amp\Artax\Request instance' ); @@ -279,27 +316,32 @@ final class HummingbirdClient implements Client { private function buildUriFromString($str): Uri { - try { + try + { $uri = new Uri($str); $scheme = $uri->getScheme(); - if (($scheme === "http" || $scheme === "https") && $uri->getHost()) { + if (($scheme === "http" || $scheme === "https") && $uri->getHost()) + { return $uri; } throw new HttpException("Request must specify a valid HTTP URI"); - } catch (InvalidUriException $e) { + } catch (InvalidUriException $e) + { throw new HttpException("Request must specify a valid HTTP URI", 0, $e); } } private function normalizeRequestBodyHeaders(Request $request): \Generator { - if ($request->hasHeader("Transfer-Encoding")) { + if ($request->hasHeader("Transfer-Encoding")) + { return $request->withoutHeader("Content-Length"); } - if ($request->hasHeader("Content-Length")) { + if ($request->hasHeader("Content-Length")) + { return $request; } @@ -307,14 +349,18 @@ final class HummingbirdClient implements Client { $body = $request->getBody(); $bodyLength = yield $body->getBodyLength(); - if ($bodyLength === 0) { + if ($bodyLength === 0) + { $request = $request->withHeader('Content-Length', '0'); $request = $request->withoutHeader('Transfer-Encoding'); - } else { - if ($bodyLength > 0) { + } else + { + if ($bodyLength > 0) + { $request = $request->withHeader("Content-Length", (string)$bodyLength); $request = $request->withoutHeader("Transfer-Encoding"); - } else { + } else + { $request = $request->withHeader("Transfer-Encoding", "chunked"); } } @@ -337,11 +383,13 @@ final class HummingbirdClient implements Client { { $autoEncoding = $options[self::OP_AUTO_ENCODING]; - if (!$autoEncoding) { + if ( ! $autoEncoding) + { return $request; } - if ($this->hasZlib) { + if ($this->hasZlib) + { return $request->withHeader('Accept-Encoding', 'gzip, deflate, identity'); } @@ -350,7 +398,8 @@ final class HummingbirdClient implements Client { private function normalizeRequestHostHeader(Request $request, Uri $uri): Request { - if ($request->hasHeader('Host')) { + if ($request->hasHeader('Host')) + { return $request; } @@ -373,9 +422,11 @@ final class HummingbirdClient implements Client { // Though servers are supposed to be able to handle standard port names on the end of the // Host header some fail to do this correctly. As a result, we strip the port from the end // if it's a standard 80 or 443 - if (strpos($host, ':80') === strlen($host) - 3) { + if (strpos($host, ':80') === strlen($host) - 3) + { return substr($host, 0, -3); - } elseif (strpos($host, ':443') === strlen($host) - 4) { + } elseif (strpos($host, ':443') === strlen($host) - 4) + { return substr($host, 0, -4); } @@ -384,7 +435,8 @@ final class HummingbirdClient implements Client { private function normalizeRequestUserAgent(Request $request): Request { - if ($request->hasHeader('User-Agent')) { + if ($request->hasHeader('User-Agent')) + { return $request; } @@ -393,7 +445,8 @@ final class HummingbirdClient implements Client { private function normalizeRequestAcceptHeader(Request $request): Request { - if ($request->hasHeader('Accept')) { + if ($request->hasHeader('Accept')) + { return $request; } @@ -407,7 +460,8 @@ final class HummingbirdClient implements Client { $domain = $uri->getHost(); $path = $uri->getPath(); - if (!$applicableCookies = $this->cookieJar->get($domain, $path)) { + if ( ! $applicableCookies = $this->cookieJar->get($domain, $path)) + { // No cookies matched our request; we're finished. return $request->withoutHeader("Cookie"); } @@ -416,13 +470,16 @@ final class HummingbirdClient implements Client { $cookiePairs = []; /** @var Cookie $cookie */ - foreach ($applicableCookies as $cookie) { - if (!$cookie->isSecure() || $isRequestSecure) { + foreach ($applicableCookies as $cookie) + { + if ( ! $cookie->isSecure() || $isRequestSecure) + { $cookiePairs[] = $cookie->getName() . "=" . $cookie->getValue(); } } - if ($cookiePairs) { + if ($cookiePairs) + { return $request->withHeader("Cookie", \implode("; ", $cookiePairs)); } @@ -433,13 +490,14 @@ final class HummingbirdClient implements Client { { $method = $request->getMethod(); - if ($method !== 'TRACE') { + if ($method !== 'TRACE') + { return $request; } // https://tools.ietf.org/html/rfc7231#section-4.3.8 /** @var Request $request */ - $request = $request->withBody(null); + $request = $request->withBody(NULL); // Remove all body and sensitive headers $request = $request->withHeaders([ @@ -453,7 +511,7 @@ final class HummingbirdClient implements Client { return $request; } - private function doRequest(Request $request, Uri $uri, array $options, Response $previousResponse = null, CancellationToken $cancellation): Promise + private function doRequest(Request $request, Uri $uri, array $options, Response $previousResponse = NULL, CancellationToken $cancellation): Promise { $deferred = new Deferred; @@ -469,20 +527,25 @@ final class HummingbirdClient implements Client { $protocolVersions = $request->getProtocolVersions(); - if (\in_array("1.1", $protocolVersions, true)) { + if (\in_array("1.1", $protocolVersions, TRUE)) + { $requestCycle->protocolVersion = "1.1"; - } elseif (\in_array("1.0", $protocolVersions, true)) { + } elseif (\in_array("1.0", $protocolVersions, TRUE)) + { $requestCycle->protocolVersion = "1.0"; - } else { + } else + { return new Failure(new HttpException( "None of the requested protocol versions are supported: " . \implode(", ", $protocolVersions) )); } asyncCall(function () use ($requestCycle) { - try { + try + { yield from $this->doWrite($requestCycle); - } catch (\Throwable $e) { + } catch (\Throwable $e) + { $this->fail($requestCycle, $e); } }); @@ -495,7 +558,8 @@ final class HummingbirdClient implements Client { $timeout = $requestCycle->options[self::OP_TRANSFER_TIMEOUT]; $timeoutToken = new NullCancellationToken; - if ($timeout > 0) { + if ($timeout > 0) + { $transferTimeoutWatcher = Loop::delay($timeout, function () use ($requestCycle, $timeout) { $this->fail($requestCycle, new TimeoutException( sprintf('Allowed transfer timeout exceeded: %d ms', $timeout) @@ -513,15 +577,19 @@ final class HummingbirdClient implements Client { $socketCheckoutUri = $requestCycle->uri->getScheme() . "://{$authority}"; $connectTimeoutToken = new CombinedCancellationToken($requestCycle->cancellation, $timeoutToken); - try { + try + { /** @var ClientSocket $socket */ $socket = yield $this->socketPool->checkout($socketCheckoutUri, $connectTimeoutToken); $requestCycle->socket = $socket; - } catch (ResolutionException $dnsException) { + } catch (ResolutionException $dnsException) + { throw new DnsException(\sprintf("Resolving the specified domain failed: '%s'", $requestCycle->uri->getHost()), 0, $dnsException); - } catch (ConnectException $e) { + } catch (ConnectException $e) + { throw new SocketException(\sprintf("Connection to '%s' failed", $authority), 0, $e); - } catch (CancelledException $e) { + } catch (CancelledException $e) + { // In case of a user cancellation request, throw the expected exception $requestCycle->cancellation->throwIfRequested(); @@ -533,8 +601,10 @@ final class HummingbirdClient implements Client { $this->fail($requestCycle, $error); }); - try { - if ($requestCycle->uri->getScheme() === 'https') { + try + { + if ($requestCycle->uri->getScheme() === 'https') + { $tlsContext = $this->tlsContext ->withPeerName($requestCycle->uri->getHost()) ->withPeerCapturing(); @@ -552,21 +622,25 @@ final class HummingbirdClient implements Client { $chunking = $requestCycle->request->getHeader("transfer-encoding") === "chunked"; $remainingBytes = $requestCycle->request->getHeader("content-length"); - if ($chunking && $requestCycle->protocolVersion === "1.0") { + if ($chunking && $requestCycle->protocolVersion === "1.0") + { throw new HttpException("Can't send chunked bodies over HTTP/1.0"); } // We always buffer the last chunk to make sure we don't write $contentLength bytes if the body is too long. $buffer = ""; - while (null !== $chunk = yield $body->read()) { + while (NULL !== $chunk = yield $body->read()) + { $requestCycle->cancellation->throwIfRequested(); - if ($chunk === "") { + if ($chunk === "") + { continue; } - if ($chunking) { + if ($chunking) + { $chunk = \dechex(\strlen($chunk)) . "\r\n" . $chunk . "\r\n"; }/* elseif ($remainingBytes !== null) { $remainingBytes -= \strlen($chunk); @@ -583,14 +657,16 @@ final class HummingbirdClient implements Client { // Flush last buffered chunk. yield $socket->write($buffer); - if ($chunking) { + if ($chunking) + { yield $socket->write("0\r\n\r\n"); }/* elseif ($remainingBytes !== null && $remainingBytes > 0) { throw new HttpException("Body contained fewer bytes than specified in Content-Length, aborting request"); }*/ yield from $this->doRead($requestCycle, $socket, $connectionInfo); - } finally { + } finally + { $requestCycle->cancellation->unsubscribe($cancellation); } } @@ -598,43 +674,48 @@ final class HummingbirdClient implements Client { private function fail(RequestCycle $requestCycle, \Throwable $error) { $toFails = []; - $socket = null; + $socket = NULL; - if ($requestCycle->deferred) { + if ($requestCycle->deferred) + { $toFails[] = $requestCycle->deferred; - $requestCycle->deferred = null; + $requestCycle->deferred = NULL; } - if ($requestCycle->body) { + if ($requestCycle->body) + { $toFails[] = $requestCycle->body; - $requestCycle->body = null; + $requestCycle->body = NULL; } - if ($requestCycle->bodyDeferred) { + if ($requestCycle->bodyDeferred) + { $toFails[] = $requestCycle->bodyDeferred; - $requestCycle->bodyDeferred = null; + $requestCycle->bodyDeferred = NULL; } - if ($requestCycle->socket) { + if ($requestCycle->socket) + { $this->socketPool->clear($requestCycle->socket); $socket = $requestCycle->socket; - $requestCycle->socket = null; + $requestCycle->socket = NULL; $socket->close(); } - foreach ($toFails as $toFail) { + foreach ($toFails as $toFail) + { $toFail->fail($error); } } private function collectConnectionInfo(ClientSocket $socket): ConnectionInfo { - $crypto = \stream_get_meta_data($socket->getResource())["crypto"] ?? null; + $crypto = \stream_get_meta_data($socket->getResource())["crypto"] ?? NULL; return new ConnectionInfo( $socket->getLocalAddress(), $socket->getRemoteAddress(), - $crypto ? TlsInfo::fromMetaData($crypto, \stream_context_get_options($socket->getResource())["ssl"]) : null + $crypto ? TlsInfo::fromMetaData($crypto, \stream_context_get_options($socket->getResource())["ssl"]) : NULL ); } @@ -655,33 +736,26 @@ final class HummingbirdClient implements Client { $requestUri = $uri->getPath() ?: '/'; - if ($query = $uri->getQuery()) { + if ($query = $uri->getQuery()) + { $requestUri .= '?' . $query; } $head = $request->getMethod() . ' ' . $requestUri . ' HTTP/' . $protocolVersion . "\r\n"; - $headers = $request->getHeaders(true); - /*$newHeaders = []; + $headers = $request->getHeaders(TRUE); - foreach($headers as $key => $val) + foreach ($headers as $field => $values) { - if ($key !== 'Content-Length') + if (\strcspn($field, "\r\n") !== \strlen($field)) { - $newHeaders[$key] = $val; - } - }*/ - - // Curse you Kitsu, for this stupid work-around because the login API endpoint doesn't allow for a Content-Length header! - //unset($headers['Content-Length']); - - foreach ($headers as $field => $values) { - if (\strcspn($field, "\r\n") !== \strlen($field)) { throw new HttpException("Blocked header injection attempt for header '{$field}'"); } - foreach ($values as $value) { - if (\strcspn($value, "\r\n") !== \strlen($value)) { + foreach ($values as $value) + { + if (\strcspn($value, "\r\n") !== \strlen($value)) + { throw new HttpException("Blocked header injection attempt for header '{$field}' with value '{$value}'"); } @@ -696,10 +770,11 @@ final class HummingbirdClient implements Client { private function doRead(RequestCycle $requestCycle, ClientSocket $socket, ConnectionInfo $connectionInfo): \Generator { - try { + try + { $backpressure = new Success; $bodyCallback = $requestCycle->options[self::OP_DISCARD_BODY] - ? null + ? NULL : static function ($data) use ($requestCycle, &$backpressure) { $backpressure = $requestCycle->body->emit($data); }; @@ -712,12 +787,14 @@ final class HummingbirdClient implements Client { Parser::OP_MAX_BODY_BYTES => $requestCycle->options[self::OP_MAX_BODY_BYTES], ]); - while (null !== $chunk = yield $socket->read()) { + while (NULL !== $chunk = yield $socket->read()) + { $requestCycle->cancellation->throwIfRequested(); $parseResult = $parser->parse($chunk); - if (!$parseResult) { + if ( ! $parseResult) + { continue; } @@ -725,54 +802,65 @@ final class HummingbirdClient implements Client { $response = $this->finalizeResponse($requestCycle, $parseResult, $connectionInfo); $shouldCloseSocketAfterResponse = $this->shouldCloseSocketAfterResponse($response); - $ignoreIncompleteBodyCheck = false; + $ignoreIncompleteBodyCheck = FALSE; $responseHeaders = $response->getHeaders(); - if ($requestCycle->deferred) { + if ($requestCycle->deferred) + { $deferred = $requestCycle->deferred; - $requestCycle->deferred = null; + $requestCycle->deferred = NULL; $deferred->resolve($response); - $response = null; // clear references - $deferred = null; // there's also a reference in the deferred - } else { + $response = NULL; // clear references + $deferred = NULL; // there's also a reference in the deferred + } else + { return; } // Required, otherwise responses without body hang - if ($parseResult["headersOnly"]) { + if ($parseResult["headersOnly"]) + { // Directly parse again in case we already have the full body but aborted parsing // to resolve promise with headers. - $chunk = null; + $chunk = NULL; - do { - try { + do + { + try + { $parseResult = $parser->parse($chunk); - } catch (ParseException $e) { + } catch (ParseException $e) + { $this->fail($requestCycle, $e); throw $e; } - if ($parseResult) { + if ($parseResult) + { break; } - if (!$backpressure instanceof Success) { + if ( ! $backpressure instanceof Success) + { yield $this->withCancellation($backpressure, $requestCycle->cancellation); } - if ($requestCycle->bodyTooLarge) { + if ($requestCycle->bodyTooLarge) + { throw new HttpException("Response body exceeded the specified size limit"); } - } while (null !== $chunk = yield $socket->read()); + } while (NULL !== $chunk = yield $socket->read()); $parserState = $parser->getState(); - if ($parserState !== Parser::AWAITING_HEADERS) { + if ($parserState !== Parser::AWAITING_HEADERS) + { // Ignore check if neither content-length nor chunked encoding are given. $ignoreIncompleteBodyCheck = $parserState === Parser::BODY_IDENTITY_EOF && - !isset($responseHeaders["content-length"]) && + ! isset($responseHeaders["content-length"]) && strcasecmp('identity', $responseHeaders['transfer-encoding'][0] ?? ""); - if (!$ignoreIncompleteBodyCheck) { + if ( ! $ignoreIncompleteBodyCheck) + { throw new SocketException(sprintf( 'Socket disconnected prior to response completion (Parser state: %s)', $parserState @@ -781,35 +869,39 @@ final class HummingbirdClient implements Client { } } - if ($shouldCloseSocketAfterResponse || $ignoreIncompleteBodyCheck) { + if ($shouldCloseSocketAfterResponse || $ignoreIncompleteBodyCheck) + { $this->socketPool->clear($socket); $socket->close(); - } else { + } else + { $this->socketPool->checkin($socket); } - $requestCycle->socket = null; + $requestCycle->socket = NULL; // Complete body AFTER socket checkin, so the socket can be reused for a potential redirect $body = $requestCycle->body; - $requestCycle->body = null; + $requestCycle->body = NULL; $bodyDeferred = $requestCycle->bodyDeferred; - $requestCycle->bodyDeferred = null; + $requestCycle->bodyDeferred = NULL; $body->complete(); $bodyDeferred->resolve(); return; } - } catch (\Throwable $e) { + } catch (\Throwable $e) + { $this->fail($requestCycle, $e); return; } - if ($socket->getResource() !== null) { - $requestCycle->socket = null; + if ($socket->getResource() !== NULL) + { + $requestCycle->socket = NULL; $this->socketPool->clear($socket); $socket->close(); } @@ -817,16 +909,19 @@ final class HummingbirdClient implements Client { // Required, because if the write fails, the read() call immediately resolves. yield new Delayed(0); - if ($requestCycle->deferred === null) { + if ($requestCycle->deferred === NULL) + { return; } $parserState = $parser->getState(); - if ($parserState === Parser::AWAITING_HEADERS && $requestCycle->retryCount < 1) { + if ($parserState === Parser::AWAITING_HEADERS && $requestCycle->retryCount < 1) + { $requestCycle->retryCount++; yield from $this->doWrite($requestCycle); - } else { + } else + { $this->fail($requestCycle, new SocketException(sprintf( 'Socket disconnected prior to response completion (Parser state: %s)', $parserState @@ -838,20 +933,20 @@ final class HummingbirdClient implements Client { { $body = new IteratorStream($requestCycle->body->iterate()); - if ($encoding = $this->determineCompressionEncoding($parserResult["headers"])) { + if ($encoding = $this->determineCompressionEncoding($parserResult["headers"])) + { $body = new ZlibInputStream($body, $encoding); } // Wrap the input stream so we can discard the body in case it's destructed but hasn't been consumed. // This allows reusing the connection for further requests. It's important to have __destruct in InputStream and // not in Message, because an InputStream might be pulled out of Message and used separately. - $body = new class($body, $requestCycle, $this->socketPool) implements InputStream - { + $body = new class($body, $requestCycle, $this->socketPool) implements InputStream { private $body; private $bodySize = 0; private $requestCycle; private $socketPool; - private $successfulEnd = false; + private $successfulEnd = FALSE; public function __construct(InputStream $body, RequestCycle $requestCycle, HttpSocketPool $socketPool) { @@ -864,14 +959,17 @@ final class HummingbirdClient implements Client { { $promise = $this->body->read(); $promise->onResolve(function ($error, $value) { - if ($value !== null) { + if ($value !== NULL) + { $this->bodySize += \strlen($value); $maxBytes = $this->requestCycle->options[Client::OP_MAX_BODY_BYTES]; - if ($maxBytes !== 0 && $this->bodySize >= $maxBytes) { - $this->requestCycle->bodyTooLarge = true; + if ($maxBytes !== 0 && $this->bodySize >= $maxBytes) + { + $this->requestCycle->bodyTooLarge = TRUE; } - } elseif ($error === null) { - $this->successfulEnd = true; + } elseif ($error === NULL) + { + $this->successfulEnd = TRUE; } }); @@ -880,17 +978,17 @@ final class HummingbirdClient implements Client { public function __destruct() { - if (!$this->successfulEnd && $this->requestCycle->socket) { + if ( ! $this->successfulEnd && $this->requestCycle->socket) + { $this->socketPool->clear($this->requestCycle->socket); $socket = $this->requestCycle->socket; - $this->requestCycle->socket = null; + $this->requestCycle->socket = NULL; $socket->close(); } } }; - $response = new class($parserResult["protocol"], $parserResult["status"], $parserResult["reason"], $parserResult["headers"], $body, $requestCycle->request, $requestCycle->previousResponse, new MetaInfo($connectionInfo)) implements Response - { + $response = new class($parserResult["protocol"], $parserResult["status"], $parserResult["reason"], $parserResult["headers"], $body, $requestCycle->request, $requestCycle->previousResponse, new MetaInfo($connectionInfo)) implements Response { private $protocolVersion; private $status; private $reason; @@ -907,7 +1005,7 @@ final class HummingbirdClient implements Client { array $headers, InputStream $body, Request $request, - Response $previousResponse = null, + Response $previousResponse = NULL, MetaInfo $metaInfo ) { @@ -943,7 +1041,8 @@ final class HummingbirdClient implements Client { public function getOriginalRequest(): Request { - if (empty($this->previousResponse)) { + if (empty($this->previousResponse)) + { return $this->request; } @@ -962,7 +1061,7 @@ final class HummingbirdClient implements Client { public function getHeader(string $field) { - return $this->headers[\strtolower($field)][0] ?? null; + return $this->headers[\strtolower($field)][0] ?? NULL; } public function getHeaderArray(string $field): array @@ -986,11 +1085,13 @@ final class HummingbirdClient implements Client { } }; - if ($response->hasHeader('Set-Cookie')) { + if ($response->hasHeader('Set-Cookie')) + { $requestDomain = $requestCycle->uri->getHost(); $cookies = $response->getHeaderArray('Set-Cookie'); - foreach ($cookies as $rawCookieStr) { + foreach ($cookies as $rawCookieStr) + { $this->storeResponseCookie($requestDomain, $rawCookieStr); } } @@ -1000,21 +1101,25 @@ final class HummingbirdClient implements Client { private function determineCompressionEncoding(array $responseHeaders): int { - if (!$this->hasZlib) { + if ( ! $this->hasZlib) + { return 0; } - if (!isset($responseHeaders["content-encoding"])) { + if ( ! isset($responseHeaders["content-encoding"])) + { return 0; } $contentEncodingHeader = \trim(\current($responseHeaders["content-encoding"])); - if (strcasecmp($contentEncodingHeader, 'gzip') === 0) { + if (strcasecmp($contentEncodingHeader, 'gzip') === 0) + { return \ZLIB_ENCODING_GZIP; } - if (strcasecmp($contentEncodingHeader, 'deflate') === 0) { + if (strcasecmp($contentEncodingHeader, 'deflate') === 0) + { return \ZLIB_ENCODING_DEFLATE; } @@ -1023,26 +1128,32 @@ final class HummingbirdClient implements Client { private function storeResponseCookie(string $requestDomain, string $rawCookieStr) { - try { + try + { $cookie = Cookie::fromString($rawCookieStr); - if (!$cookie->getDomain()) { + if ( ! $cookie->getDomain()) + { $cookie = $cookie->withDomain($requestDomain); - } else { + } else + { // https://tools.ietf.org/html/rfc6265#section-4.1.2.3 $cookieDomain = $cookie->getDomain(); // If a domain is set, left dots are ignored and it's always a wildcard $cookieDomain = \ltrim($cookieDomain, "."); - if ($cookieDomain !== $requestDomain) { + if ($cookieDomain !== $requestDomain) + { // ignore cookies on domains that are public suffixes - if (PublicSuffixList::isPublicSuffix($cookieDomain)) { + if (PublicSuffixList::isPublicSuffix($cookieDomain)) + { return; } // cookie origin would not be included when sending the cookie - if (\substr($requestDomain, 0, -\strlen($cookieDomain) - 1) . "." . $cookieDomain !== $requestDomain) { + if (\substr($requestDomain, 0, -\strlen($cookieDomain) - 1) . "." . $cookieDomain !== $requestDomain) + { return; } } @@ -1052,7 +1163,8 @@ final class HummingbirdClient implements Client { } $this->cookieJar->store($cookie); - } catch (CookieFormatException $e) { + } catch (CookieFormatException $e) + { // Ignore malformed Set-Cookie headers } } @@ -1064,15 +1176,18 @@ final class HummingbirdClient implements Client { $requestConnHeader = $request->getHeader('Connection'); $responseConnHeader = $response->getHeader('Connection'); - if ($requestConnHeader && !strcasecmp($requestConnHeader, 'close')) { - return true; - } elseif ($responseConnHeader && !strcasecmp($responseConnHeader, 'close')) { - return true; - } elseif ($response->getProtocolVersion() === '1.0' && !$responseConnHeader) { - return true; + if ($requestConnHeader && ! strcasecmp($requestConnHeader, 'close')) + { + return TRUE; + } elseif ($responseConnHeader && ! strcasecmp($responseConnHeader, 'close')) + { + return TRUE; + } elseif ($response->getProtocolVersion() === '1.0' && ! $responseConnHeader) + { + return TRUE; } - return false; + return FALSE; } private function withCancellation(Promise $promise, CancellationToken $cancellationToken): Promise @@ -1081,21 +1196,25 @@ final class HummingbirdClient implements Client { $newPromise = $deferred->promise(); $promise->onResolve(function ($error, $value) use (&$deferred) { - if ($deferred) { - if ($error) { + if ($deferred) + { + if ($error) + { $deferred->fail($error); - $deferred = null; - } else { + $deferred = NULL; + } else + { $deferred->resolve($value); - $deferred = null; + $deferred = NULL; } } }); $cancellationSubscription = $cancellationToken->subscribe(function ($e) use (&$deferred) { - if ($deferred) { + if ($deferred) + { $deferred->fail($e); - $deferred = null; + $deferred = NULL; } }); @@ -1108,8 +1227,9 @@ final class HummingbirdClient implements Client { private function getRedirectUri(Response $response) { - if (!$response->hasHeader('Location')) { - return null; + if ( ! $response->hasHeader('Location')) + { + return NULL; } $request = $response->getRequest(); @@ -1117,17 +1237,20 @@ final class HummingbirdClient implements Client { $status = $response->getStatus(); $method = $request->getMethod(); - if ($status < 300 || $status > 399 || $method === 'HEAD') { - return null; + if ($status < 300 || $status > 399 || $method === 'HEAD') + { + return NULL; } $requestUri = new Uri($request->getUri()); $redirectLocation = $response->getHeader('Location'); - try { + try + { return $requestUri->resolve($redirectLocation); - } catch (InvalidUriException $e) { - return null; + } catch (InvalidUriException $e) + { + return NULL; } } @@ -1148,7 +1271,8 @@ final class HummingbirdClient implements Client { $refererIsEncrypted = (\stripos($refererUri, 'https') === 0); $destinationIsEncrypted = (\stripos($newUri, 'https') === 0); - if (!$refererIsEncrypted || $destinationIsEncrypted) { + if ( ! $refererIsEncrypted || $destinationIsEncrypted) + { return $request->withHeader('Referer', $refererUri); } @@ -1164,7 +1288,8 @@ final class HummingbirdClient implements Client { */ public function setOptions(array $options) { - foreach ($options as $option => $value) { + foreach ($options as $option => $value) + { $this->setOption($option, $value); } } diff --git a/src/API/Kitsu/Auth.php b/src/API/Kitsu/Auth.php index 9fdeeae1..311d54cc 100644 --- a/src/API/Kitsu/Auth.php +++ b/src/API/Kitsu/Auth.php @@ -70,17 +70,9 @@ final class Auth { public function authenticate(string $password): bool { $config = $this->container->get('config'); - $username = $config->get(['kitsu_username']); - - // try - { - $auth = $this->model->authenticate($username, $password); - } - /* catch (Exception $e) - { - return FALSE; - }*/ + $username = $config->get('kitsu_username'); + $auth = $this->model->authenticate($username, $password); if (FALSE !== $auth) { @@ -104,6 +96,7 @@ final class Auth { $this->segment->set('auth_token', $auth['access_token']); $this->segment->set('auth_token_expires', $expire_time); $this->segment->set('refresh_token', $auth['refresh_token']); + return TRUE; } @@ -119,14 +112,7 @@ final class Auth { */ public function reAuthenticate(string $token): bool { - try - { - $auth = $this->model->reAuthenticate($token); - } - catch (Exception $e) - { - return FALSE; - } + $auth = $this->model->reAuthenticate($token); if (FALSE !== $auth) { @@ -186,7 +172,7 @@ final class Auth { { $token = $this->segment->get('auth_token', FALSE); $refreshToken = $this->segment->get('refresh_token', FALSE); - $isExpired = time() > $this->segment->get('auth_token_expires', 0); + $isExpired = time() >= $this->segment->get('auth_token_expires', 0); // Attempt to re-authenticate with refresh token if ($isExpired && $refreshToken) diff --git a/src/API/Kitsu/Model.php b/src/API/Kitsu/Model.php index 3ca3db29..d10f1171 100644 --- a/src/API/Kitsu/Model.php +++ b/src/API/Kitsu/Model.php @@ -121,11 +121,6 @@ final class Model { ]); $data = Json::decode(wait($response->getBody())); - if (array_key_exists('access_token', $data)) - { - return $data; - } - if (array_key_exists('error', $data)) { dump($data['error']); @@ -133,6 +128,11 @@ final class Model { die(); } + if (array_key_exists('access_token', $data)) + { + return $data; + } + return FALSE; } @@ -376,9 +376,7 @@ final class Model { // Bail out on no data if (empty($data)) { - $cacheItem->set([]); - $cacheItem->save(); - return $cacheItem->get(); + return []; } $included = JsonAPI::organizeIncludes($data['included']); @@ -638,9 +636,7 @@ final class Model { // Bail out on no data if (empty($data) || ( ! array_key_exists('included', $data))) { - $cacheItem->set([]); - $cacheItem->save(); - return $cacheItem->get(); + return []; } $included = JsonAPI::organizeIncludes($data['included']); diff --git a/src/Controller/Index.php b/src/Controller/Index.php index 0853fdce..b30fa09e 100644 --- a/src/Controller/Index.php +++ b/src/Controller/Index.php @@ -79,7 +79,7 @@ final class Index extends BaseController { { $redirectUrl = 'https://anilist.co/api/v2/oauth/authorize?' . http_build_query([ - 'client_id' => 271, + 'client_id' => $this->config->get(['anilist', 'client_id']), 'response_type' => 'code', ]); @@ -109,6 +109,7 @@ final class Index extends BaseController { { $auth = $this->container->get('auth'); $post = $this->request->getParsedBody(); + if ($auth->authenticate($post['password'])) { $this->sessionRedirect(); diff --git a/src/Dispatcher.php b/src/Dispatcher.php index ea8f7e31..d0050f4b 100644 --- a/src/Dispatcher.php +++ b/src/Dispatcher.php @@ -18,7 +18,7 @@ namespace Aviat\AnimeClient; use function Aviat\Ion\_dir; -use Aura\Router\Matcher; +use Aura\Router\{Matcher, Rule}; use Aviat\AnimeClient\API\FailedResponseException; use Aviat\Ion\Di\ContainerInterface; @@ -314,7 +314,7 @@ final class Dispatcher extends RoutingBase { $params = []; switch($failure->failedRule) { - case 'Aura\Router\Rule\Allows': + case Rule\Allows::class: $params = [ 'http_code' => 405, 'title' => '405 Method Not Allowed', @@ -322,7 +322,7 @@ final class Dispatcher extends RoutingBase { ]; break; - case 'Aura\Router\Rule\Accepts': + case Rule\Accepts::class: $params = [ 'http_code' => 406, 'title' => '406 Not Acceptable', diff --git a/src/Model/Collection.php b/src/Model/Collection.php index 98635a42..3e51b688 100644 --- a/src/Model/Collection.php +++ b/src/Model/Collection.php @@ -42,15 +42,15 @@ class Collection extends DB { try { - $this->db = \Query($this->dbConfig['collection']); + $this->db = \Query($this->dbConfig); } catch (PDOException $e) {} // Is database valid? If not, set a flag so the // app can be run without a valid database - if ($this->dbConfig['collection']['type'] === 'sqlite') + if ($this->dbConfig['type'] === 'sqlite') { - $dbFileName = $this->dbConfig['collection']['file']; + $dbFileName = $this->dbConfig['file']; if ($dbFileName !== ':memory:' && file_exists($dbFileName)) { diff --git a/src/RoutingBase.php b/src/RoutingBase.php index 174a28b8..14780445 100644 --- a/src/RoutingBase.php +++ b/src/RoutingBase.php @@ -44,12 +44,6 @@ class RoutingBase { */ protected $routes; - /** - * Route configuration options - * @var array - */ - protected $routeConfig; - /** * Constructor * @@ -63,20 +57,19 @@ class RoutingBase { $this->container = $container; $this->config = $container->get('config'); $this->routes = $this->config->get('routes'); - $this->routeConfig = $this->config->get('route_config'); } /** * Retrieve the appropriate value for the routing key * - * @param string $key + * @param string|int|array $key * @return mixed */ public function __get($key) { - if (array_key_exists($key, $this->routeConfig)) + if ($this->config->has($key)) { - return $this->routeConfig[$key]; + return $this->config->get($key); } } diff --git a/src/Types/AbstractType.php b/src/Types/AbstractType.php index 393a7842..ec00bca8 100644 --- a/src/Types/AbstractType.php +++ b/src/Types/AbstractType.php @@ -17,11 +17,10 @@ namespace Aviat\AnimeClient\Types; use ArrayAccess; -use LogicException; abstract class AbstractType implements ArrayAccess { /** - * Populate values for unserializing data + * Populate values for un-serializing data * * @param $properties * @return mixed @@ -87,7 +86,7 @@ abstract class AbstractType implements ArrayAccess { { $existing = json_encode($this); - throw new LogicException("Trying to set non-existent property: '$name'. Existing properties: $existing"); + throw new UndefinedPropertyException("Trying to set undefined property: '$name'. Existing properties: $existing"); } $this->$name = $value; @@ -106,7 +105,7 @@ abstract class AbstractType implements ArrayAccess { return $this->$name; } - throw new LogicException("Trying to get non-existent property: '$name'"); + throw new UndefinedPropertyException("Trying to get undefined property: '$name'"); } /** diff --git a/src/Types/Config.php b/src/Types/Config.php index bd99e5ae..3ac54f7d 100644 --- a/src/Types/Config.php +++ b/src/Types/Config.php @@ -21,9 +21,13 @@ class Config extends AbstractType { public $anilist; public $cache; public $database; - public $route_config; // Settings in config.toml + public $asset_path; // Path to public folder for urls + public $default_anime_list_path; + public $default_list; + public $default_manga_list_path; + public $default_view_type; public $kitsu_username; public $show_anime_collection; public $show_manga_collection; @@ -34,7 +38,7 @@ class Config extends AbstractType { public $routes; // Generated config values - public $asset_dir; + public $asset_dir; // Path to public folder for local files public $base_config_dir; public $config_dir; public $data_cache_path; @@ -43,57 +47,16 @@ class Config extends AbstractType { public function setAnilist ($data): void { - $this->anilist = new class($data) extends AbstractType { - public $enabled; - - public $client_id; - public $client_secret; - public $redirect_uri; - - public $access_token; - public $refresh_token; - - public $user_id; - public $username; - }; + $this->anilist = new Config\Anilist($data); } public function setCache ($data): void { - $this->cache = new class($data) extends AbstractType { - public $driver; - public $connection; - public $options; - }; + $this->cache = new Config\Cache($data); } public function setDatabase ($data): void { - $this->database = new class($data) extends AbstractType { - public $collection; - - public function setCollection ($data): void - { - $this->collection = new class($data) extends AbstractType { - public $type; - public $host; - public $user; - public $pass; - public $port; - public $database; - public $file; - }; - } - }; - } - - public function setRoute_config ($data): void - { - $this->route_config = new class($data) extends AbstractType { - public $asset_path; - public $default_list; - public $default_anime_list_path; - public $default_manga_list_path; - }; + $this->database = new Config\Database($data); } } \ No newline at end of file diff --git a/src/Types/Config/Anilist.php b/src/Types/Config/Anilist.php new file mode 100644 index 00000000..7da74fa2 --- /dev/null +++ b/src/Types/Config/Anilist.php @@ -0,0 +1,33 @@ + + * @copyright 2015 - 2018 Timothy J. Warren + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @version 4.1 + * @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient + */ + +namespace Aviat\AnimeClient\Types\Config; + +use Aviat\AnimeClient\Types\AbstractType; + +class Anilist extends AbstractType { + public $enabled = FALSE; + + public $client_id; + public $client_secret; + public $redirect_uri; + + public $access_token; + public $refresh_token; + + public $user_id; + public $username; +} \ No newline at end of file diff --git a/src/Types/Config/Cache.php b/src/Types/Config/Cache.php new file mode 100644 index 00000000..929b4531 --- /dev/null +++ b/src/Types/Config/Cache.php @@ -0,0 +1,32 @@ + + * @copyright 2015 - 2018 Timothy J. Warren + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @version 4.1 + * @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient + */ + +namespace Aviat\AnimeClient\Types\Config; + +use Aviat\AnimeClient\Types\AbstractType; + +class Cache extends AbstractType { + public $driver; + public $connection = []; + public $options = []; + + /* public function setConnection($data): void + { + $this->connection = new class($data) extends AbstractType { + + }; + } */ +} \ No newline at end of file diff --git a/src/Types/Config/Database.php b/src/Types/Config/Database.php new file mode 100644 index 00000000..8c807caa --- /dev/null +++ b/src/Types/Config/Database.php @@ -0,0 +1,29 @@ + + * @copyright 2015 - 2018 Timothy J. Warren + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @version 4.1 + * @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient + */ + +namespace Aviat\AnimeClient\Types\Config; + +use Aviat\AnimeClient\Types\AbstractType; + +class Database extends AbstractType { + public $type; + public $host; + public $user; + public $pass; + public $port; + public $database; + public $file; +} \ No newline at end of file diff --git a/src/Types/UndefinedPropertyException.php b/src/Types/UndefinedPropertyException.php new file mode 100644 index 00000000..ff46700b --- /dev/null +++ b/src/Types/UndefinedPropertyException.php @@ -0,0 +1,21 @@ + + * @copyright 2015 - 2018 Timothy J. Warren + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @version 4.1 + * @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient + */ + +namespace Aviat\AnimeClient\Types; + +use LogicException; + +class UndefinedPropertyException extends LogicException {} \ No newline at end of file diff --git a/tests/AnimeClientTestCase.php b/tests/AnimeClientTestCase.php index 6d377b49..caeca83c 100644 --- a/tests/AnimeClientTestCase.php +++ b/tests/AnimeClientTestCase.php @@ -70,7 +70,7 @@ class AnimeClientTestCase extends TestCase { $APP_DIR = _dir($ROOT_DIR, 'app'); $config_array = [ - 'asset_path' => '//localhost/assets/', + 'asset_path' => '/assets', 'img_cache_path' => _dir(ROOT_DIR, 'public/images'), 'data_cache_path' => _dir(TEST_DATA_DIR, 'cache'), 'cache' => [ @@ -99,16 +99,9 @@ class AnimeClientTestCase extends TestCase { 'file' => ':memory:', ] ], - 'route_config' => [ - 'asset_path' => '/assets' - ], 'routes' => [ ], - 'mal' => [ - 'username' => 'foo', - 'password' => 'bar' - ] ]; // Set up DI container diff --git a/tests/ControllerTest.php b/tests/ControllerTest.php index a2ab09d4..9bb418ff 100644 --- a/tests/ControllerTest.php +++ b/tests/ControllerTest.php @@ -51,7 +51,7 @@ class ControllerTest extends AnimeClientTestCase { public function testControllersSanity() { $config = $this->container->get('config'); - $config->set(['database', 'collection'], [ + $config->set('database', [ 'type' => 'sqlite', 'database' => '', 'file' => ":memory:" diff --git a/tests/DispatcherTest.php b/tests/DispatcherTest.php index c70bcfb3..02b03c80 100644 --- a/tests/DispatcherTest.php +++ b/tests/DispatcherTest.php @@ -98,7 +98,7 @@ class DispatcherTest extends AnimeClientTestCase { ] ], ], - 'route_config' => [ + 'config' => [ 'anime_path' => 'anime', 'manga_path' => 'manga', 'default_list' => 'anime' @@ -132,8 +132,8 @@ class DispatcherTest extends AnimeClientTestCase { ] ]; - $data['manga_default_routing_anime']['config']['route_config']['default_list'] = 'manga'; - $data['manga_default_routing_manga']['config']['route_config']['default_list'] = 'manga'; + $data['manga_default_routing_anime']['config']['default_list'] = 'manga'; + $data['manga_default_routing_manga']['config']['default_list'] = 'manga'; return $data; } @@ -167,7 +167,7 @@ class DispatcherTest extends AnimeClientTestCase { public function testDefaultRoute() { $config = [ - 'route_config' => [ + 'config' => [ 'anime_path' => 'anime', 'manga_path' => 'manga', 'default_anime_list_path' => "watching", @@ -192,11 +192,12 @@ class DispatcherTest extends AnimeClientTestCase { ] ]; + $this->expectException(\InvalidArgumentException::class); + $this->doSetUp($config, "/", "localhost"); $this->assertEquals('//localhost/manga/all', $this->urlGenerator->defaultUrl('manga'), "Incorrect default url"); $this->assertEquals('//localhost/anime/watching', $this->urlGenerator->defaultUrl('anime'), "Incorrect default url"); - $this->expectException(\InvalidArgumentException::class); $this->urlGenerator->defaultUrl('foo'); } @@ -205,16 +206,12 @@ class DispatcherTest extends AnimeClientTestCase { return [ 'controller_list_sanity_check' => [ 'config' => [ - 'routes' => [ - - ], - 'route_config' => [ - 'anime_path' => 'anime', - 'manga_path' => 'manga', - 'default_anime_list_path' => "watching", - 'default_manga_list_path' => 'all', - 'default_list' => 'manga' - ], + 'anime_path' => 'anime', + 'manga_path' => 'manga', + 'default_anime_list_path' => "watching", + 'default_manga_list_path' => 'all', + 'default_list' => 'manga', + 'routes' => [], ], 'expected' => [ 'anime' => 'Aviat\AnimeClient\Controller\Anime', @@ -230,13 +227,11 @@ class DispatcherTest extends AnimeClientTestCase { 'routes' => [ ], - 'route_config' => [ - 'anime_path' => 'anime', - 'manga_path' => 'manga', - 'default_anime_path' => "/anime/watching", - 'default_manga_path' => '/manga/all', - 'default_list' => 'manga' - ], + 'anime_path' => 'anime', + 'manga_path' => 'manga', + 'default_anime_path' => "/anime/watching", + 'default_manga_path' => '/manga/all', + 'default_list' => 'manga' ], 'expected' => [ 'anime' => 'Aviat\AnimeClient\Controller\Anime',