diff --git a/.github/workflows/serpapi-php.yml b/.github/workflows/serpapi-php.yml index 83cda27..256998b 100644 --- a/.github/workflows/serpapi-php.yml +++ b/.github/workflows/serpapi-php.yml @@ -66,4 +66,4 @@ jobs: - name: Run test suite run: composer run-script test env: - SERPAPI_KEY: ${{ secrets.SERPAPI_KEY }} + SERPAPI_KEY: ${{ secrets.SERPAPI_KEY || secrets.API_KEY }} diff --git a/README.md b/README.md index 2903e82..c084b9e 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ $results = $client->search(['q' => 'coffee', 'timeout' => 10]); ### Default search parameters -The constructor also accepts a single array. `api_key`, `engine`, `timeout`, and `persistent` configure the client; every other key becomes a default search parameter sent with every request: +The constructor also accepts a single array. `api_key`, `engine`, `timeout`, `persistent`, and `assoc` configure the client; every other key becomes a default search parameter sent with every request: ```php use SerpApi\Client; @@ -166,6 +166,8 @@ $results = $client->search(['q' => 'coffee', 'gl' => null]); With positional arguments, pass default search parameters fourth: `new Client($apiKey, 'google', 30, ['hl' => 'en'])`. +Set `assoc` to `true` to decode every JSON response into associative arrays. Use `searchArray()` to request an associative array for an individual search. + ### Persistent connections The client keeps its connection to SerpApi open and reuses it, so only the first request pays for the DNS lookup and TLS handshake. The connection closes when the client is destroyed, or explicitly with `close()`: @@ -978,6 +980,7 @@ Contributions are welcome. Feel free to submit a pull request! ## Change log + * 1.1 - Ruby client parity: connection reuse, default search parameters, associative array decoding, Markdown output * 1.0 - First stable version ## Conclusion diff --git a/README.md.erb b/README.md.erb index 0d99cee..132cb58 100644 --- a/README.md.erb +++ b/README.md.erb @@ -166,7 +166,7 @@ $results = $client->search(['q' => 'coffee', 'timeout' => 10]); ### Default search parameters -The constructor also accepts a single array. `api_key`, `engine`, `timeout`, and `persistent` configure the client; every other key becomes a default search parameter sent with every request: +The constructor also accepts a single array. `api_key`, `engine`, `timeout`, `persistent`, and `assoc` configure the client; every other key becomes a default search parameter sent with every request: ```php use SerpApi\Client; @@ -190,6 +190,8 @@ $results = $client->search(['q' => 'coffee', 'gl' => null]); With positional arguments, pass default search parameters fourth: `new Client($apiKey, 'google', 30, ['hl' => 'en'])`. +Set `assoc` to `true` to decode every JSON response into associative arrays. Use `searchArray()` to request an associative array for an individual search. + ### Persistent connections The client keeps its connection to SerpApi open and reuses it, so only the first request pays for the DNS lookup and TLS handshake. The connection closes when the client is destroyed, or explicitly with `close()`: @@ -549,6 +551,7 @@ Contributions are welcome. Feel free to submit a pull request! ## Change log + * 1.1 - Ruby client parity: connection reuse, default search parameters, associative array decoding, Markdown output * 1.0 - First stable version ## Conclusion diff --git a/phpstan.neon b/phpstan.neon index f0d3853..b401012 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -3,3 +3,12 @@ parameters: paths: - src - demo + + # The library supports PHP 7.2 through 8.5. Analysis runs against PHP 8.1; + # the 7.x resource form is exercised by the CI matrix. + phpVersion: 80100 + + ignoreErrors: + # PHPStan only sees one arm of the cURL handle union for a single version. + - identifier: property.unusedType + path: src/Client.php diff --git a/src/Client.php b/src/Client.php index af3efc8..b2ec97f 100644 --- a/src/Client.php +++ b/src/Client.php @@ -4,7 +4,7 @@ class Client { - public const VERSION = '1.0.0'; + public const VERSION = '1.1.0'; public const BASE_URL = 'https://serpapi.com'; public const DEFAULT_TIMEOUT = 120; @@ -26,6 +26,9 @@ class Client /** @var bool Keep one connection open and reuse it across requests */ private $persistent = true; + /** @var bool Decode JSON responses to associative arrays */ + private $assoc = false; + /** @var resource|\CurlHandle|null Shared cURL handle: a resource on PHP 7, a CurlHandle on PHP 8 */ private $handle; @@ -35,9 +38,9 @@ class Client * * new Client(['api_key' => '...', 'engine' => 'google', 'hl' => 'en']) * - * `api_key`, `engine`, `timeout` and `persistent` configure the client - * and take precedence over the positional arguments. Every other key - * becomes a default search parameter, sent with every request unless + * `api_key`, `engine`, `timeout`, `persistent` and `assoc` configure the + * client and take precedence over the positional arguments. Every other + * key becomes a default search parameter, sent with every request unless * overridden per call. * * @param string|array $apiKey API key, or a configuration array @@ -61,6 +64,7 @@ public function __construct( $engine = self::pull($params, 'engine', $engine); $timeout = self::pull($params, 'timeout', $timeout); $persistent = self::pull($params, 'persistent', true); + $assoc = self::pull($params, 'assoc', false); if (empty($engine)) { throw new SerpApiException('engine must be present'); @@ -70,6 +74,7 @@ public function __construct( $this->engine = (string) $engine; $this->timeout = (int) $timeout; $this->persistent = (bool) $persistent; + $this->assoc = (bool) $assoc; $this->params = $params; } @@ -104,6 +109,11 @@ public function setApiKey(string $apiKey): void $this->apiKey = $apiKey; } + public function set_api_key(string $api_key): void + { + $this->setApiKey($api_key); + } + /** * Get the current API key. */ @@ -112,6 +122,11 @@ public function getApiKey(): string return $this->apiKey; } + public function get_api_key(): string + { + return $this->getApiKey(); + } + /** * Get the current engine. */ @@ -120,6 +135,11 @@ public function getEngine(): string return $this->engine; } + public function get_engine(): string + { + return $this->getEngine(); + } + /** * Get the request timeout in seconds. */ @@ -128,6 +148,11 @@ public function getTimeout(): int return $this->timeout; } + public function get_timeout(): int + { + return $this->getTimeout(); + } + /** * Get the default search parameters sent with every request. * @@ -138,6 +163,22 @@ public function getParams(): array return $this->params; } + /** + * Get the engine, API key, and default search parameters. + * + * @return array + */ + public function get_params(): array + { + $params = ['engine' => $this->engine]; + + if (!empty($this->apiKey)) { + $params['api_key'] = $this->apiKey; + } + + return array_merge($params, $this->params); + } + /** * Whether the client reuses one connection across requests. */ @@ -146,6 +187,24 @@ public function isPersistent(): bool return $this->persistent; } + public function is_persistent(): bool + { + return $this->isPersistent(); + } + + /** + * Whether JSON responses are decoded to associative arrays. + */ + public function isAssoc(): bool + { + return $this->assoc; + } + + public function is_assoc(): bool + { + return $this->isAssoc(); + } + /** * Close the shared connection. Safe to call more than once; the client * stays usable and reconnects on the next request. @@ -227,6 +286,7 @@ public function __debugInfo(): array 'engine' => $this->engine, 'timeout' => $this->timeout, 'persistent' => $this->persistent, + 'assoc' => $this->assoc, 'apiKey' => $this->maskedApiKey(), 'params' => $this->params, ]; @@ -255,11 +315,12 @@ private function maskedApiKey(): string * Run a search and return decoded JSON. * * @param array $params + * @return object|array * @throws SerpApiException */ - public function search(array $params = []): object + public function search(array $params = []) { - return $this->get('/search', 'json', $params); + return $this->get('/search', 'json', $params, $this->assoc); } /** @@ -299,9 +360,10 @@ public function html(array $params = []): string /** * Get account information using Account API. * + * @return object|array * @throws SerpApiException */ - public function account(?string $apiKey = null): object + public function account(?string $apiKey = null) { $params = empty($apiKey) ? [] : ['api_key' => $apiKey]; return $this->get('/account', 'json', $params); @@ -311,7 +373,7 @@ public function account(?string $apiKey = null): object * Get locations using Location API. * * @param array $params - * @return array + * @return array> * @throws SerpApiException */ public function location(array $params = []): array @@ -322,8 +384,7 @@ public function location(array $params = []): array /** * Retrieve search result from the Search Archive API. * - * @return object|string - * @phpstan-return ($format is 'json' ? object : string) + * @return object|array|string * @throws SerpApiException */ public function searchArchive(string $searchId, string $format = 'json') @@ -340,6 +401,11 @@ public function searchArchive(string $searchId, string $format = 'json') return $this->get("/searches/{$safeSearchId}.{$format}", $format, []); } + public function search_archive(string $search_id, string $format = 'json') + { + return $this->searchArchive($search_id, $format); + } + /** * @param array $params * @param bool $assoc Decode JSON objects to associative arrays instead of stdClass @@ -364,6 +430,7 @@ private function get(string $endpoint, string $format = 'json', array $params = } $timeout = (int) self::pull($params, 'timeout', $this->timeout); + self::pull($params, 'assoc', false); $query = $this->buildQuery($params, (string) $apiKey, $format); @@ -386,7 +453,7 @@ private function get(string $endpoint, string $format = 'json', array $params = $this->raiseHttpError($httpCode, $endpoint, $query, null, null, $format); } - $decoded = json_decode($response, $assoc); + $decoded = json_decode($response, $this->assoc || $assoc); if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) { $this->raiseParserError($httpCode, $endpoint, $query); } diff --git a/src/SerpApiException.php b/src/SerpApiException.php index d3757b0..44ffb15 100644 --- a/src/SerpApiException.php +++ b/src/SerpApiException.php @@ -45,6 +45,11 @@ public function getSerpApiError(): ?string return $this->serpApiError; } + public function get_serpapi_error(): ?string + { + return $this->getSerpApiError(); + } + /** * @return array|null */ @@ -53,21 +58,44 @@ public function getSearchParams(): ?array return $this->searchParams; } + /** + * @return array|null + */ + public function get_search_params(): ?array + { + return $this->getSearchParams(); + } + public function getResponseStatus(): ?int { return $this->responseStatus; } + public function get_response_status(): ?int + { + return $this->getResponseStatus(); + } + public function getSearchId(): ?string { return $this->searchId; } + public function get_search_id(): ?string + { + return $this->getSearchId(); + } + public function getDecoder(): ?string { return $this->decoder; } + public function get_decoder(): ?string + { + return $this->getDecoder(); + } + /** * @return array */ @@ -84,4 +112,21 @@ public function toArray(): array return $value !== null; }); } + + /** + * @return array + */ + public function to_array(): array + { + return array_filter([ + 'message' => $this->getMessage(), + 'serpapi_error' => $this->serpApiError, + 'search_params' => $this->searchParams, + 'response_status' => $this->responseStatus, + 'search_id' => $this->searchId, + 'decoder' => $this->decoder, + ], static function ($value) { + return $value !== null; + }); + } } diff --git a/tests/ClientAssocTest.php b/tests/ClientAssocTest.php new file mode 100644 index 0000000..8e6cfae --- /dev/null +++ b/tests/ClientAssocTest.php @@ -0,0 +1,81 @@ +assertFalse((new RecordingClient('secret'))->isAssoc()); + } + + public function testAssocCanBeEnabled() + { + $client = new RecordingClient(['api_key' => 'secret', 'assoc' => true]); + $this->assertTrue($client->isAssoc()); + + $results = $client->willReturn('{"organic_results":[{"title":"Coffee"}]}')->search(); + $this->assertSame('Coffee', $results['organic_results'][0]['title']); + } + + public function testAssocIsNotSentAsASearchParameter() + { + $client = new RecordingClient(['api_key' => 'secret', 'assoc' => true]); + $client->search(['q' => 'coffee']); + + $this->assertArrayNotHasKey('assoc', $client->getParams()); + $this->assertArrayNotHasKey('assoc', $client->lastQuery()); + } + + public function testPerCallAssocIsNotSentAsASearchParameter() + { + $client = new RecordingClient('secret'); + $client->search(['q' => 'coffee', 'assoc' => true]); + + $this->assertArrayNotHasKey('assoc', $client->lastQuery()); + $this->assertSame('coffee', $client->lastQuery()['q']); + } + + public function testDigReadsBothObjectAndArrayShapes() + { + $client = new RecordingClient('secret'); + + foreach ([json_decode('{"error":"boom"}'), json_decode('{"error":"boom"}', true)] as $data) { + $this->assertEquals('boom', $this->dig($client, $data, 'error')); + $this->assertNull($this->dig($client, $data, 'missing')); + } + } + + public function testDigToleratesScalarAndNullResponses() + { + $client = new RecordingClient('secret'); + + $this->assertNull($this->dig($client, null, 'error')); + $this->assertNull($this->dig($client, 'a string', 'error')); + } + + /** + * @param mixed $data + * @return mixed + */ + private function dig(Client $client, $data, string $key) { + $method = new \ReflectionMethod(Client::class, 'dig'); + + if (PHP_VERSION_ID < 80100) { + $method->setAccessible(true); + } + + return $method->invoke($client, $data, $key); + } +} diff --git a/tests/ClientInspectTest.php b/tests/ClientInspectTest.php index 9c60cd1..ebebd14 100644 --- a/tests/ClientInspectTest.php +++ b/tests/ClientInspectTest.php @@ -56,7 +56,7 @@ public function testVarDumpDoesNotExposeTheApiKey() $this->assertStringNotContainsString(self::LONG_KEY, $dump); $this->assertStringContainsString('abcd****wxyz', $dump); - $this->assertStringContainsString('"hl"', $dump); + $this->assertStringContainsString("'hl'", $dump); } public function testPrintRDoesNotExposeTheApiKey() diff --git a/tests/ClientIntegrationTest.php b/tests/ClientIntegrationTest.php index 6c73272..6b60973 100644 --- a/tests/ClientIntegrationTest.php +++ b/tests/ClientIntegrationTest.php @@ -4,67 +4,14 @@ class ClientIntegrationTest extends SerpApiTestCase { - /** @var array */ - private $searchParams; - - protected function setUp(): void + public function testMarkdownSearchReturnsContent() { - parent::setUp(); - $this->searchParams = [ + $response = $this->serpApiClient()->md([ 'q' => 'Coffee', 'location' => 'Austin,Texas', - ]; - } - - public function testAccount() - { - $client = $this->serpApiClient(); - $response = $client->account(); - $this->assertEquals($client->getApiKey(), $response->api_key); - } + ]); - public function testHtml() - { - $client = $this->serpApiClient(); - $response = $client->html($this->searchParams); - $this->assertGreaterThan(10000, strlen($response)); - } - - public function testMd() - { - $client = $this->serpApiClient(); - $response = $client->md($this->searchParams); $this->assertStringStartsWith('---', $response); $this->assertStringContainsString('## Organic Results', $response); } - - public function testSearch() - { - $client = $this->serpApiClient(); - $response = $client->search($this->searchParams); - $this->assertEquals('Success', $response->search_metadata->status); - $this->assertResponseHasProperty($response, 'organic_results'); - $this->assertNotEmpty($response->organic_results); - } - - public function testLocation() - { - $client = $this->serpApiClient(); - $location_list = $client->location(['q' => 'Austin', 'limit' => 3]); - $this->assertCount(3, $location_list); - $this->assertStringContainsString('Austin', $location_list[0]->name); - $this->assertGreaterThan(0, $location_list[0]->google_id); - } - - public function testSearchArchive() - { - $client = $this->serpApiClient(); - $result = $client->search($this->searchParams); - $archived_result = $client->searchArchive($result->search_metadata->id); - $this->assertEquals($result->search_metadata->id, $archived_result->search_metadata->id); - - $archived_markdown = $client->searchArchive($result->search_metadata->id, 'md'); - $this->assertStringStartsWith('---', $archived_markdown); - $this->assertStringContainsString('## Organic Results', $archived_markdown); - } } diff --git a/tests/ClientLegacyApiTest.php b/tests/ClientLegacyApiTest.php new file mode 100644 index 0000000..7f667ab --- /dev/null +++ b/tests/ClientLegacyApiTest.php @@ -0,0 +1,63 @@ + 'secret', + 'engine' => 'bing', + 'timeout' => 30, + 'persistent' => false, + 'assoc' => true, + 'hl' => 'en', + ]); + + $this->assertSame('secret', $client->get_api_key()); + $this->assertSame('bing', $client->get_engine()); + $this->assertSame(30, $client->get_timeout()); + $this->assertSame(false, $client->is_persistent()); + $this->assertSame(true, $client->is_assoc()); + $this->assertSame(['engine' => 'bing', 'api_key' => 'secret', 'hl' => 'en'], $client->get_params()); + + $client->set_api_key('updated'); + $this->assertSame('updated', $client->get_api_key()); + } + + public function testSnakeCaseArchiveAliasPreservesValidation() + { + $this->expectException(SerpApiException::class); + $this->expectExceptionMessage('search_id must be present'); + + (new Client('secret'))->search_archive(''); + } + + public function testSnakeCaseExceptionAccessorsPreserveExistingKeys() + { + $exception = new SerpApiException('failure', 'invalid key', ['q' => 'coffee'], 401, 'abc123', 'json'); + + $this->assertSame('invalid key', $exception->get_serpapi_error()); + $this->assertSame(['q' => 'coffee'], $exception->get_search_params()); + $this->assertSame(401, $exception->get_response_status()); + $this->assertSame('abc123', $exception->get_search_id()); + $this->assertSame('json', $exception->get_decoder()); + $this->assertSame([ + 'message' => 'failure', + 'serpapi_error' => 'invalid key', + 'search_params' => ['q' => 'coffee'], + 'response_status' => 401, + 'search_id' => 'abc123', + 'decoder' => 'json', + ], $exception->to_array()); + } +} diff --git a/tests/ExampleSearchGoogleLightSearchTest.php b/tests/ExampleSearchGoogleLightSearchTest.php new file mode 100644 index 0000000..8bf4512 --- /dev/null +++ b/tests/ExampleSearchGoogleLightSearchTest.php @@ -0,0 +1,22 @@ + */ + private $search_params; + + protected function setUp(): void { + parent::setUp(); + $this->search_params = [ + 'engine' => 'google_light_search', + 'q' => 'coffee', + ]; + } + + public function test_result_exists() { + $client = $this->serpApiClient(); + $response = $client->search($this->search_params); + $this->assertResponseHasProperty($response, 'organic_results', 'Error on `google_light_search` engine: no `organic_results`'); + } +} diff --git a/tests/SerpApiTestCase.php b/tests/SerpApiTestCase.php index 6d4c1cf..44963d7 100644 --- a/tests/SerpApiTestCase.php +++ b/tests/SerpApiTestCase.php @@ -30,15 +30,17 @@ protected function requiresApiKey(): bool protected function resolveApiKey(): ?string { - $env = $_ENV['SERPAPI_KEY'] ?? null; + foreach (['SERPAPI_KEY', 'API_KEY'] as $name) { + $env = $_ENV[$name] ?? null; - if (!empty($env)) { - return $env; - } + if (!empty($env)) { + return $env; + } - $value = getenv('SERPAPI_KEY'); - if (!empty($value)) { - return $value; + $value = getenv($name); + if (!empty($value)) { + return $value; + } } return null;