Skip to content

Commit

Permalink
Add stock summary retrieval and decoding functionality (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
elminson committed Mar 1, 2024
1 parent e88721d commit c24c085
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/ApiClient.php
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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']);
}
}

0 comments on commit c24c085

Please sign in to comment.