Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/serpapi-php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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()`:
Expand Down Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion README.md.erb
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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()`:
Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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
89 changes: 78 additions & 11 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;

Expand All @@ -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<string, mixed> $apiKey API key, or a configuration array
Expand All @@ -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');
Expand All @@ -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;
}

Expand Down Expand Up @@ -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.
*/
Expand All @@ -112,6 +122,11 @@ public function getApiKey(): string
return $this->apiKey;
}

public function get_api_key(): string
{
return $this->getApiKey();
}

/**
* Get the current engine.
*/
Expand All @@ -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.
*/
Expand All @@ -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.
*
Expand All @@ -138,6 +163,22 @@ public function getParams(): array
return $this->params;
}

/**
* Get the engine, API key, and default search parameters.
*
* @return array<string, mixed>
*/
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.
*/
Expand All @@ -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.
Expand Down Expand Up @@ -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,
];
Expand Down Expand Up @@ -255,11 +315,12 @@ private function maskedApiKey(): string
* Run a search and return decoded JSON.
*
* @param array<string, mixed> $params
* @return object|array<string, mixed>
* @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);
}

/**
Expand Down Expand Up @@ -299,9 +360,10 @@ public function html(array $params = []): string
/**
* Get account information using Account API.
*
* @return object|array<string, mixed>
* @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);
Expand All @@ -311,7 +373,7 @@ public function account(?string $apiKey = null): object
* Get locations using Location API.
*
* @param array<string, mixed> $params
* @return array<int, object>
* @return array<int, object|array<string, mixed>>
* @throws SerpApiException
*/
public function location(array $params = []): array
Expand All @@ -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, mixed>|string
* @throws SerpApiException
*/
public function searchArchive(string $searchId, string $format = 'json')
Expand All @@ -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<string, mixed> $params
* @param bool $assoc Decode JSON objects to associative arrays instead of stdClass
Expand All @@ -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);

Expand All @@ -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);
}
Expand Down
45 changes: 45 additions & 0 deletions src/SerpApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ public function getSerpApiError(): ?string
return $this->serpApiError;
}

public function get_serpapi_error(): ?string
{
return $this->getSerpApiError();
}

/**
* @return array<string, mixed>|null
*/
Expand All @@ -53,21 +58,44 @@ public function getSearchParams(): ?array
return $this->searchParams;
}

/**
* @return array<string, mixed>|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<string, mixed>
*/
Expand All @@ -84,4 +112,21 @@ public function toArray(): array
return $value !== null;
});
}

/**
* @return array<string, mixed>
*/
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;
});
}
}
Loading