Skip to content

Commit

Permalink
Merge pull request #21 from keepsuit/api-exception
Browse files Browse the repository at this point in the history
Api exception
  • Loading branch information
cappuc authored May 22, 2024
2 parents 7bbc72d + a16d7ac commit c228892
Show file tree
Hide file tree
Showing 9 changed files with 194 additions and 93 deletions.
6 changes: 4 additions & 2 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ includes:
- phpstan-baseline.neon

parameters:
level: 6
level: 8
paths:
- src
- config
- database
tmpDir: build/phpstan
checkOctaneCompatibility: true
checkModelProperties: true
checkMissingIterableValueType: false

ignoreErrors:
- identifier: missingType.iterableValue

2 changes: 1 addition & 1 deletion src/Api/ZohoAccessToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function get(): string
$this->accessToken = $this->refreshAccessToken();
}

return $this->accessToken?->token;
return $this->accessToken?->token ?? '';
}

protected function refreshAccessToken(): ?Token
Expand Down
21 changes: 21 additions & 0 deletions src/Api/ZohoApiException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Keepsuit\Campaigns\Api;

use RuntimeException;

class ZohoApiException extends RuntimeException
{
final public function __construct(string $message, int $code = 0)
{
parent::__construct($message, $code);
}

public static function fromResponse(array $response): static
{
return new static(
message: $response['message'] ?? 'An error occurred',
code: (int) $response['code'],
);
}
}
102 changes: 70 additions & 32 deletions src/Api/ZohoCampaignsApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Keepsuit\Campaigns\Api;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

class ZohoCampaignsApi
Expand All @@ -13,13 +15,20 @@ public function __construct(
}

/**
* @return array{
* message: string,
* status: string,
* code: int,
* }
* Subscribes a contact to a list.
*
* @link https://www.zoho.com/campaigns/help/developers/contact-subscribe.html
*
* @param string $listKey The list key.
* @param string $email The email address to subscribe.
* @param array $contactInfo Additional contact information to subscribe.
* @param array $additionalParams Additional parameters to pass to the API.
* @return string Response message from the API.
*
* @throws ZohoApiException
* @throws ConnectionException
*/
public function listSubscribe(string $listKey, string $email, array $contactInfo = [], array $additionalParams = []): array
public function listSubscribe(string $listKey, string $email, array $contactInfo = [], array $additionalParams = []): string
{
$params = array_merge([
'listkey' => $listKey,
Expand All @@ -29,23 +38,31 @@ public function listSubscribe(string $listKey, string $email, array $contactInfo
], $contactInfo)),
], $additionalParams);

return Http::baseUrl($this->endpoint())
->withToken($this->accessToken->get(), 'Zoho-oauthtoken')
->withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
])
$response = $this->newRequest()
->post(sprintf('/json/listsubscribe?%s', http_build_query($params)))
->json();

if ($response['status'] === 'error') {
throw ZohoApiException::fromResponse($response);
}

return $response['message'] ?? '';
}

/**
* @return array{
* message: string,
* status: string,
* code: int,
* }
* Unsubscribes a contact from a list.
*
* @link https://www.zoho.com/campaigns/help/developers/contact-unsubscribe.html
*
* @param string $listKey The list key.
* @param string $email The email address to unsubscribe.
* @param array $additionalParams Additional parameters to pass to the API.
* @return string Response message from the API.
*
* @throws ZohoApiException
* @throws ConnectionException
*/
public function listUnsubscribe(string $listKey, string $email, array $additionalParams = []): array
public function listUnsubscribe(string $listKey, string $email, array $additionalParams = []): string
{
$params = array_merge([
'listkey' => $listKey,
Expand All @@ -55,18 +72,22 @@ public function listUnsubscribe(string $listKey, string $email, array $additiona
]),
], $additionalParams);

return Http::baseUrl($this->endpoint())
->withToken($this->accessToken->get(), 'Zoho-oauthtoken')
->withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
])
$response = $this->newRequest()
->post(sprintf('/json/listunsubscribe?%s', http_build_query($params)))
->json();

if ($response['status'] === 'error') {
throw ZohoApiException::fromResponse($response);
}

return $response['message'] ?? '';
}

/**
* Retrieves the list of subscribers for a given list key with various options.
*
* @link https://www.zoho.com/campaigns/help/developers/get-list-subscribers.html
*
* @param string $listKey The list key.
* @param string $status The status of the subscribers to retrieve. Possible values are 'active', 'recent', 'mostrecent', 'unsub', and 'bounce'. Default is 'active'
* @param string $sort The sort order of the results. Possible values are 'asc' and 'desc'. Default is 'asc'.
Expand All @@ -80,6 +101,9 @@ public function listUnsubscribe(string $listKey, string $email, array $additiona
* lastname: string,
* companyname: string,
* }> The list of subscribers.
*
* @throws ZohoApiException
* @throws ConnectionException
*/
public function listSubscribers(
string $listKey,
Expand All @@ -98,23 +122,28 @@ public function listSubscribers(
'status' => $status,
], $additionalParams);

$response = Http::baseUrl($this->endpoint())
->withToken($this->accessToken->get(), 'Zoho-oauthtoken')
->withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
])
$response = $this->newRequest()
->get(sprintf('/getlistsubscribers?%s', http_build_query($params)))
->json();

if ($response['status'] === 'error') {
throw ZohoApiException::fromResponse($response);
}

return $response['list_of_details'] ?? [];
}

/**
* Retrieves the count of subscribers for a given list key and status.
*
* @link https://www.zoho.com/campaigns/help/developers/view-total-contacts.html
*
* @param string $listKey The list key.
* @param string $status The status of the subscribers to retrieve. Possible values are 'active', 'unsub', 'bounce' and 'spam'. Default is 'active'
* @return int The count of subscribers.
*
* @throws ZohoApiException
* @throws ConnectionException
*/
public function listSubscribersCount(
string $listKey,
Expand All @@ -127,17 +156,26 @@ public function listSubscribersCount(
'status' => $status,
], $additionalParams);

$response = Http::baseUrl($this->endpoint())
->withToken($this->accessToken->get(), 'Zoho-oauthtoken')
->withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
])
$response = $this->newRequest()
->get(sprintf('/listsubscriberscount?%s', http_build_query($params)))
->json();

if ($response['status'] === 'error') {
throw ZohoApiException::fromResponse($response);
}

return $response['no_of_contacts'] ?? 0;
}

protected function newRequest(): PendingRequest
{
return Http::baseUrl($this->endpoint())
->withToken($this->accessToken->get(), 'Zoho-oauthtoken')
->withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
]);
}

protected function endpoint(): string
{
return sprintf('https://campaigns.%s/api/v1.1', $this->region->domain());
Expand Down
46 changes: 21 additions & 25 deletions src/Campaigns.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

namespace Keepsuit\Campaigns;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use Keepsuit\Campaigns\Api\ZohoApiException;
use Keepsuit\Campaigns\Api\ZohoCampaignsApi;

class Campaigns
Expand All @@ -23,50 +25,38 @@ public function __construct(protected ZohoCampaignsApi $zohoApi)
}

/**
* @return array{success: bool, message?: string}
* @throws ConnectionException
* @throws ZohoApiException
*/
public function subscribe(string $email, ?array $contactInfo = [], ?string $listName = null): array
public function subscribe(string $email, array $contactInfo = [], ?string $listName = null): string
{
$listKey = $this->resolveListKey($listName);

$response = $this->zohoApi->listSubscribe($listKey, $email, $contactInfo);

return [
'success' => Arr::get($response, 'status') === 'success',
'message' => Arr::get($response, 'message'),
];
return $this->zohoApi->listSubscribe($listKey, $email, $contactInfo);
}

/**
* @return array{success: bool, message?: string}
* @throws ConnectionException
* @throws ZohoApiException
*/
public function unsubscribe(string $email, ?string $listName = null): array
public function resubscribe(string $email, array $contactInfo = [], ?string $listName = null): string
{
$listKey = $this->resolveListKey($listName);

$response = $this->zohoApi->listUnsubscribe($listKey, $email);
$additionalParams = ['donotmail_resub' => 'true'];

return [
'success' => Arr::get($response, 'status') === 'success',
'message' => Arr::get($response, 'message'),
];
return $this->zohoApi->listSubscribe($listKey, $email, $contactInfo, $additionalParams);
}

/**
* @return array{success: bool, message?: string}
* @throws ConnectionException
* @throws ZohoApiException
*/
public function resubscribe(string $email, ?array $contactInfo = [], ?string $listName = null): array
public function unsubscribe(string $email, ?string $listName = null): string
{
$listKey = $this->resolveListKey($listName);

$additionalParams = ['donotmail_resub' => 'true'];

$response = $this->zohoApi->listSubscribe($listKey, $email, $contactInfo, $additionalParams);

return [
'success' => Arr::get($response, 'status') === 'success',
'message' => Arr::get($response, 'message'),
];
return $this->zohoApi->listUnsubscribe($listKey, $email);
}

/**
Expand All @@ -83,6 +73,9 @@ public function resubscribe(string $email, ?array $contactInfo = [], ?string $li
* lastname: string,
* companyname: string,
* }> The list of subscribers.
*
* @throws ConnectionException
* @throws ZohoApiException
*/
public function subscribers(string $status = 'active', string $sort = 'asc', ?string $listName = null): LazyCollection
{
Expand Down Expand Up @@ -114,6 +107,9 @@ public function subscribers(string $status = 'active', string $sort = 'asc', ?st
* @param string $status The status of the subscribers to count. Possible values are 'active', 'unsub', 'bounce', and 'spam'.
* @param string|null $listName The name of the list. If null, the default list name will be used.
* @return int The count of subscribers.
*
* @throws ConnectionException
* @throws ZohoApiException
*/
public function subscribersCount(string $status = 'active', ?string $listName = null): int
{
Expand Down
7 changes: 4 additions & 3 deletions src/Commands/SetupCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,11 @@ protected function setupRegion(): string
$options = collect(ZohoRegion::cases())
->keyBy(fn (ZohoRegion $region) => $region->label());

$selectedOption = $this->choice('Select your region', $options->keys()->toArray());
assert(is_string($selectedOption));

/** @var ZohoRegion $region */
$region = $options->get(
$this->choice('Select your region', $options->keys()->toArray())
);
$region = $options->get($selectedOption);

config()->set('campaigns.region', $region->value);

Expand Down
6 changes: 3 additions & 3 deletions src/Facades/Campaigns.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
use Illuminate\Support\LazyCollection;

/**
* @method static array|null subscribe(string $email, ?array $contactInfo = [], string $listName = null)
* @method static array|null resubscribe(string $email, ?array $contactInfo = [], string $listName = null)
* @method static array|null unsubscribe(string $email, string $listName = null)
* @method static string subscribe(string $email, array $contactInfo = [], string $listName = null)
* @method static string resubscribe(string $email, array $contactInfo = [], string $listName = null)
* @method static string unsubscribe(string $email, string $listName = null)
* @method static LazyCollection subscribers(string $status = 'active', string $sort = 'asc', ?string $listName = null)
* @method static int subscribersCount(string $status = 'active', ?string $listName = null)
*
Expand Down
Loading

0 comments on commit c228892

Please sign in to comment.