Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add stock summary retrieval and decoding functionality #48

Merged
merged 7 commits into from
Mar 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/ApiClient.php
Expand Up @@ -249,4 +249,25 @@ private function getRandomQueryServer(): int
{
return rand(1, 2);
}

public function stockSummary(string $symbol): array
{
$qs = $this->getRandomQueryServer();
$cookieJar = new CookieJar();

// Initialize session cookies
$initialUrl = 'https://fc.yahoo.com';
$this->client->request('GET', $initialUrl, ['cookies' => $cookieJar, 'http_errors' => false, 'headers' => $this->getHeaders()]);

// Get crumb value
$initialUrl = 'https://query'.$qs.'.finance.yahoo.com/v1/test/getcrumb';
$crumb = (string) $this->client->request('GET', $initialUrl, ['cookies' => $cookieJar, 'headers' => $this->getHeaders()])->getBody();

// Fetch quotes
$modules = 'financialData,quoteType,defaultKeyStatistics,assetProfile,summaryDetail';
$url = 'https://query'.$qs.'.finance.yahoo.com/v10/finance/quoteSummary/'.$symbol.'?crumb='.$crumb.'&modules='.$modules;
$responseBody = (string) $this->client->request('GET', $url, ['cookies' => $cookieJar, 'headers' => $this->getHeaders()])->getBody();

return $this->resultDecoder->transformQuotesSumamary($responseBody);
}
}
10 changes: 10 additions & 0 deletions src/ResultDecoder.php
Expand Up @@ -272,4 +272,14 @@ private function createQuote(array $json): Quote

return new Quote($mappedValues);
}

public function transformQuotesSumamary(string $responseBody): array
{
$decoded = json_decode($responseBody, true);
if (!isset($decoded['quoteSummary']['result']) || !\is_array($decoded['quoteSummary']['result'])) {
throw new ApiException('Yahoo Search API returned an invalid result.', ApiException::INVALID_RESPONSE);
}

return $decoded['quoteSummary']['result'];
}
}
8 changes: 8 additions & 0 deletions tests/ApiClientIntegrationTest.php
Expand Up @@ -308,4 +308,12 @@ public function runBare(): void
throw $e; // Throw the last exception
}
}

public function testStockSummary()
{
$returnValue = $this->client->stockSummary(self::APPLE_SYMBOL);

$this->assertIsArray($returnValue);
$this->assertEquals(self::APPLE_SYMBOL, $returnValue[0]['quoteType']['symbol']);
}
}