diff --git a/README.md b/README.md index c681604..8ae4efc 100644 --- a/README.md +++ b/README.md @@ -81,8 +81,11 @@ Once you have an instance of `MailingList`, you can do the following operations: - add a `Recipient` ```php use Fazland\MailUpRestClient\Recipient; - -$list->addRecipient(new Recipient('Aragorn', 'aragorn@gondor.com', '3333333333', '+39')); +$recipient = new Recipient('Aragorn', 'aragorn@gondor.com', '3333333333', '+39'); +$list->addRecipient($recipient); +// OR +$confirmByEmail = true; +$list->addRecipient($recipient, $confirmByEmail); // resubscribe an unsubscribed recipient (after *required* confirmation by email) ``` - update a `Recipient` ```php @@ -98,7 +101,13 @@ $list->removeRecipient(new Recipient('Aragorn', 'aragorn@gondor.com', '333333333 ``` - find a `Recipient` by its `email` ```php -$recipient = $list->findRecipient('aragorn@gondor.com'); // null returned if current email was not found +$recipient = $list->findRecipient('aragorn@gondor.com'); // null returned if current email was not found. Equal to $list->findRecipient('aragorn@gondor.com', Recipient::STATUS_SUBSCRIBED); +// OR +$list->findRecipient('aragorn@gondor.com', Recipient::STATUS_UNSUBSCRIBED); +// OR +$list->findRecipient('aragorn@gondor.com', Recipient::STATUS_PENDING); +// OR +$list->findRecipient('aragorn@gondor.com', Recipient::STATUS_ANY); // find by any of the statuses ``` - retrieve all the groups of the current list: ```php @@ -111,6 +120,8 @@ $countRecipients = $list->countRecipients(); // equal to $list->countRecipients( $countRecipients = $list->countRecipients(Recipient::STATUS_UNSUBSCRIBED); // OR $countRecipients = $list->countRecipients(Recipient::STATUS_PENDING); +// OR +$countRecipients = $list->countRecipients(Recipient::STATUS_ANY); ``` - get recipients paginated (you can specify the same status used in MailingList::countRecipients()): ```php diff --git a/lib/Context.php b/lib/Context.php index f5ecefe..450ca7a 100644 --- a/lib/Context.php +++ b/lib/Context.php @@ -19,7 +19,7 @@ class Context { const AUTH_TOKEN_URI = 'https://services.mailup.com/Authorization/OAuth/Token'; - const BASE_URI = 'https://services.mailup.com/API/v1.1/Rest'; + const BASE_URI = 'https://services.mailup.com/API/v1.1/Rest'; /** * @var string @@ -67,17 +67,18 @@ public function __construct(array $options = [], HttpClient $client = null) $client = HttpClientDiscovery::find(); } - $this->token = new Token\NullToken(); - $this->client = $client; + $this->token = new Token\NullToken(); + $this->client = $client; $this->messageFactory = MessageFactoryDiscovery::find(); $options = $this->resolveOptions($options); $this->setCacheDir($options['cache_dir']); - $this->clientId = $options['client_id']; + + $this->clientId = $options['client_id']; $this->clientSecret = $options['client_secret']; - $this->username = $options['username']; - $this->password = $options['password']; + $this->username = $options['username']; + $this->password = $options['password']; } /** @@ -92,7 +93,8 @@ public function setCacheDir(string $cacheDir = null) { $this->cacheDir = $cacheDir; - if (null !== $this->cacheDir && file_exists($fn = $this->cacheDir.DIRECTORY_SEPARATOR.'access_token.json')) { + $fn = $this->cacheDir . DIRECTORY_SEPARATOR . 'access_token.json'; + if (null !== $this->cacheDir && file_exists($fn)) { if (false === $json = @file_get_contents($fn)) { // Error return; @@ -120,19 +122,28 @@ public function setCacheDir(string $cacheDir = null) * * @throws InvalidResponseException */ - public function makeRequest(string $path, string $method, $params = null): ResponseInterface - { + public function makeRequest( + string $path, + string $method, + $params = null + ): ResponseInterface { $this->refreshToken(); - $request = $this->messageFactory->createRequest($method, self::BASE_URI.$path, [ - 'Content-Type' => 'application/json', - 'Authorization' => 'Bearer '.$this->token->getAccessToken(), - ], json_encode($params)); + $request = $this->messageFactory->createRequest( + $method, + self::BASE_URI.$path, + [ + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer '.$this->token->getAccessToken(), + ], + json_encode($params) + ); $response = $this->client->sendRequest($request); if (200 !== $response->getStatusCode()) { - $responseBody = (string)$response->getBody(); - $message = "Response not OK when requesting an access token. Response body: $responseBody"; + $responseBody = (string) $response->getBody(); + $message = "Response not OK when requesting an access token. " + . "Response body: {$responseBody}"; throw new InvalidResponseException($response, $message); } @@ -154,30 +165,36 @@ private function refreshToken() if (! $this->token->isValid()) { $body = http_build_query([ - 'grant_type' => 'password', - 'client_id' => $this->clientId, + 'grant_type' => 'password', + 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, - 'username' => $this->username, - 'password' => $this->password, + 'username' => $this->username, + 'password' => $this->password, ]); } else { $body = http_build_query([ - 'grant_type' => 'refresh_token', - 'client_id' => $this->clientId, + 'grant_type' => 'refresh_token', + 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'refresh_token' => $this->token->getRefreshToken(), ]); } - $request = $this->messageFactory->createRequest('POST', self::AUTH_TOKEN_URI, [ - 'Content-Type' => 'application/x-www-form-urlencoded', - 'Authorization' => 'Basic '.base64_encode($this->clientId.':'.$this->clientSecret), - ], $body); + $request = $this->messageFactory->createRequest( + 'POST', + self::AUTH_TOKEN_URI, + [ + 'Content-Type' => 'application/x-www-form-urlencoded', + 'Authorization' => 'Basic '.base64_encode($this->clientId.':'.$this->clientSecret), + ], + $body + ); $response = $this->client->sendRequest($request); if (200 !== $response->getStatusCode()) { - $responseBody = (string)$response->getBody(); - $message = "Response not OK when requesting an access token. Response body: $responseBody"; + $responseBody = (string) $response->getBody(); + $message = "Response not OK when requesting an access token. " + . "Response body: {$responseBody}"; throw new InvalidResponseException($response, $message); } @@ -196,7 +213,7 @@ private function saveToken() mkdir($this->cacheDir); } - $fn = $this->cacheDir.DIRECTORY_SEPARATOR.'access_token.json'; + $fn = $this->cacheDir . DIRECTORY_SEPARATOR . 'access_token.json'; file_put_contents($fn, json_encode($this->token)); } diff --git a/lib/DynamicField.php b/lib/DynamicField.php index 1221e88..4457a4e 100644 --- a/lib/DynamicField.php +++ b/lib/DynamicField.php @@ -26,8 +26,8 @@ final class DynamicField implements \JsonSerializable public function __construct(string $fieldName, string $value, int $id) { $this->fieldName = $fieldName; - $this->value = $value; - $this->id = $id; + $this->value = $value; + $this->id = $id; } /** @@ -75,8 +75,8 @@ public function jsonSerialize(): array { return [ 'Description' => $this->fieldName, - 'Id' => $this->id, - 'Value' => $this->value, + 'Id' => $this->id, + 'Value' => $this->value, ]; } } diff --git a/lib/Exception/InvalidResponseException.php b/lib/Exception/InvalidResponseException.php index fa9a304..d8fb297 100644 --- a/lib/Exception/InvalidResponseException.php +++ b/lib/Exception/InvalidResponseException.php @@ -16,8 +16,12 @@ class InvalidResponseException extends \RuntimeException implements ExceptionInt */ private $response; - public function __construct(ResponseInterface $response, $message = "", $code = 0, \Exception $previous = null) - { + public function __construct( + ResponseInterface $response, + $message = "", + $code = 0, + \Exception $previous = null + ) { $this->response = $response; parent::__construct($message, $code, $previous); } diff --git a/lib/ListGroup.php b/lib/ListGroup.php index 019af5e..daac29a 100644 --- a/lib/ListGroup.php +++ b/lib/ListGroup.php @@ -54,8 +54,8 @@ class ListGroup extends Resource public function __construct(Context $context, MailingList $list, int $id) { $this->context = $context; - $this->id = $id; - $this->list = $list; + $this->id = $id; + $this->list = $list; } /** @@ -63,10 +63,13 @@ public function __construct(Context $context, MailingList $list, int $id) * @param MailingList $list * @param array $response * - * @return ListGroup + * @return self */ - public static function fromResponseArray(Context $context, MailingList $list, array $response) - { + public static function fromResponseArray( + Context $context, + MailingList $list, + array $response + ): self { $group = new self($context, $list, $response['idGroup']); $group ->setName($response['Name']) @@ -145,11 +148,12 @@ public function setDeletable(bool $deletable): self public function delete() { if (! $this->deletable) { - throw new CannotDeleteGroupException("$this->name group is not deletable"); + throw new CannotDeleteGroupException("{$this->name} group is not deletable"); } $this->context->makeRequest( - "/ConsoleService.svc/Console/List/{$this->list->getId()}/Group/{$this->id}", + "/ConsoleService.svc/Console/List/{$this->list->getId()}". + "/Group/{$this->id}", 'DELETE' ); } @@ -158,16 +162,25 @@ public function delete() * Subscribes the specified {@see Recipient} to current MailUp group. * * @param Recipient $recipient + * @param bool $confirmByEmail Enable Confirmed Opt-in + * (required for resubscribing recipients) * * @return Recipient */ - public function addRecipient(Recipient $recipient) - { + public function addRecipient( + Recipient $recipient, + bool $confirmByEmail = false + ): Recipient { + $queryString = http_build_query([ + 'ConfirmEmail' => var_export($confirmByEmail, true), + ]); $response = $this->context->makeRequest( - "/ConsoleService.svc/Console/Group/$this->id/Recipient", - 'POST', - $recipient - ); + "/ConsoleService.svc/Console/Group/{$this->id}". + "/Recipient". + "?{$queryString}", + 'POST', + $recipient + ); $recipient->setId(self::getJSON($response)); @@ -182,7 +195,8 @@ public function addRecipient(Recipient $recipient) public function removeRecipient(Recipient $recipient) { $this->context->makeRequest( - "/ConsoleService.svc/Console/Group/$this->id/Unsubscribe/{$recipient->getId()}", + "/ConsoleService.svc/Console/Group/{$this->id}". + "/Unsubscribe/{$recipient->getId()}", 'DELETE' ); } @@ -194,17 +208,20 @@ public function removeRecipient(Recipient $recipient) */ public function getRecipients(): array { - $response = $this->context->makeRequest("ConsoleService.svc/Console/Group/{$this->id}/Recipient", 'GET'); + $response = $this->context->makeRequest( + "ConsoleService.svc/Console/Group/{$this->id}". + "/Recipient", + 'GET' + ); $body = self::getJSON($response); - $items = $body['Items']; - if (! count($items)) { + if (! count($body['Items'])) { return null; } $recipients = []; - foreach ($items as $item) { + foreach ($body['Items'] as $item) { $recipients[] = Recipient::fromResponseArray($item); } diff --git a/lib/MailingList.php b/lib/MailingList.php index bd36159..e981590 100644 --- a/lib/MailingList.php +++ b/lib/MailingList.php @@ -15,8 +15,8 @@ class MailingList extends Resource const OPTOUT_ONE_CLICK = 0; const OPTOUT_CONFIRMED = 1; - const SCOPE_NEWSLETTER = 'newsletters'; - const SCOPE_MARKETING = 'Direct_Advertising'; + const SCOPE_NEWSLETTER = 'newsletters'; + const SCOPE_MARKETING = 'Direct_Advertising'; const SCOPE_TRANSACTIONAL = 'Transactional'; /** @@ -65,8 +65,8 @@ private function __construct(Context $context) private static function fromResponseArray(Context $context, array $response) { $list = new self($context); - $list->id = $response['idList']; - $list->name = $response['Name']; + $list->id = $response['idList']; + $list->name = $response['Name']; $list->companyName = $response['Company']; $list->description = $response['Description']; @@ -124,10 +124,11 @@ public function getDescription(): string public function import(array $recipients): int { $response = $this->context->makeRequest( - "/ConsoleService.svc/Console/List/{$this->id}/Recipients", - 'POST', - $recipients - ); + "/ConsoleService.svc/Console/List/{$this->id}". + "/Recipients", + 'POST', + $recipients + ); return self::getJSON($response); } @@ -136,16 +137,26 @@ public function import(array $recipients): int * Subscribes the specified {@see Recipient} to current MailUp list. * * @param Recipient $recipient + * @param bool $confirmByEmail Enable Confirmed Opt-in + * (required for resubscribing recipients) * * @return Recipient */ - public function addRecipient(Recipient $recipient): Recipient - { + public function addRecipient( + Recipient $recipient, + bool $confirmByEmail = false + ): Recipient { + $queryString = http_build_query([ + 'ConfirmEmail' => var_export($confirmByEmail, true), + ]); + $response = $this->context->makeRequest( - "/ConsoleService.svc/Console/List/$this->id/Recipient", - 'POST', - $recipient - ); + "/ConsoleService.svc/Console/List/{$this->id}". + "/Recipient". + "?{$queryString}", + 'POST', + $recipient + ); $recipient->setId(self::getJSON($response)); @@ -160,7 +171,8 @@ public function addRecipient(Recipient $recipient): Recipient public function removeRecipient(Recipient $recipient) { $this->context->makeRequest( - "/ConsoleService.svc/Console/List/$this->id/Unsubscribe/{$recipient->getId()}", + "/ConsoleService.svc/Console/List/{$this->id}". + "/Unsubscribe/{$recipient->getId()}", 'DELETE' ); } @@ -172,32 +184,57 @@ public function removeRecipient(Recipient $recipient) */ public function updateRecipient(Recipient $recipient) { - $this->context->makeRequest("/ConsoleService.svc/Console/Recipient/Detail", 'PUT', $recipient); + $this->context->makeRequest( + "/ConsoleService.svc/Console/Recipient/Detail", + 'PUT', + $recipient + ); } /** * @param string $email + * @param string $status * * @return Recipient|null */ - public function findRecipient(string $email) - { + public function findRecipient( + string $email, + string $status = Recipient::STATUS_SUBSCRIBED + ) { + if ( + Recipient::STATUS_ANY !== $status + && ! in_array($status, Recipient::SUBSCRIPTION_STATUSES) + ) { + throw new \InvalidArgumentException( + "Subscription status should be ". + "'" . implode("', '", Recipient::SUBSCRIPTION_STATUSES) . "' ". + "or '" . Recipient::STATUS_ANY . "'." + ); + } + + $statuses = Recipient::STATUS_ANY === $status + ? Recipient::SUBSCRIPTION_STATUSES + : [$status]; + $emailEncoded = urlencode($email); - $response = $this->context->makeRequest( - "/ConsoleService.svc/Console/List/{$this->id}/Recipients/Subscribed?filterby=\"Email.Contains(%27$emailEncoded%27)\"", - 'GET' - ); + $queryString = "filterby=Email.Contains(%27{$emailEncoded}%27)"; - $body = self::getJSON($response); + $recipients = []; + foreach ($statuses as $status) { + $path = "/ConsoleService.svc/Console/List/{$this->id}" + . "/Recipients/{$status}" + . "?{$queryString}"; + + $response = $this->context->makeRequest($path, 'GET'); + $body = self::getJSON($response); + $recipients = array_merge($recipients, $body['Items']); + } - $recipients = $body['Items']; if (! count($recipients)) { return null; } - $recipient = Recipient::fromResponseArray($recipients[0]); - - return $recipient; + return Recipient::fromResponseArray($recipients[0]); } /** @@ -205,73 +242,100 @@ public function findRecipient(string $email) */ public function getGroups(): array { - $response = $this->context->makeRequest("/ConsoleService.svc/Console/List/{$this->id}/Groups", 'GET'); + $response = $this->context->makeRequest( + "/ConsoleService.svc/Console/List/{$this->id}". + "/Groups", + 'GET' + ); $body = self::getJSON($response); - $items = $body['Items']; $groups = []; - - foreach ($items as $item) { - $groups[] = ListGroup::fromResponseArray($this->context, $this, $item); + foreach ($body['Items'] as $item) { + $groups[] = ListGroup::fromResponseArray( + $this->context, + $this, + $item + ); } return $groups; } /** - * @param string $subscriptionStatus + * @param string $status * * @return int */ - public function countRecipients(string $subscriptionStatus = Recipient::STATUS_SUBSCRIBED): int - { - if (! in_array($subscriptionStatus, Recipient::SUBSCRIPTION_STATUSES)) { - throw new \InvalidArgumentException('Subscription status can be only one of [' . implode(', ', Recipient::SUBSCRIPTION_STATUSES) . "]!"); + public function countRecipients( + string $status = Recipient::STATUS_SUBSCRIBED + ): int { + if ( + Recipient::STATUS_ANY !== $status + && ! in_array($status, Recipient::SUBSCRIPTION_STATUSES) + ) { + throw new \InvalidArgumentException( + "Subscription status should be ". + "'" . implode("', '", Recipient::SUBSCRIPTION_STATUSES) . "' ". + "or '" . Recipient::STATUS_ANY . "'." + ); } - $response = $this->context->makeRequest( - "/ConsoleService.svc/Console/List/{$this->id}/Recipients/{$subscriptionStatus}", - "GET" - ); + $statuses = Recipient::STATUS_ANY === $status + ? Recipient::SUBSCRIPTION_STATUSES + : [$status]; - $body = self::getJSON($response); + $count = 0; + foreach ($statuses as $status) { + $path = "/ConsoleService.svc/Console/List/{$this->id}" + . "/Recipients/{$status}"; - return $body['TotalElementsCount'] ?? 0; + $response = $this->context->makeRequest($path, 'GET'); + $body = self::getJSON($response); + $count += $body['TotalElementsCount'] ?? 0; + } + + return $count; } /** * @param int $pageNumber * @param int $pageSize - * @param string $subscriptionStatus + * @param string $status * * @return Recipient[] */ public function getRecipientsPaginated( int $pageNumber, int $pageSize, - string $subscriptionStatus = Recipient::STATUS_SUBSCRIBED + string $status = Recipient::STATUS_SUBSCRIBED ): array { - if (! in_array($subscriptionStatus, Recipient::SUBSCRIPTION_STATUSES)) { - throw new \InvalidArgumentException('Subscription status can be only one of [' . implode(', ', Recipient::SUBSCRIPTION_STATUSES) . "]!"); + if (! in_array($status, Recipient::SUBSCRIPTION_STATUSES)) { + $statuses = Recipient::SUBSCRIPTION_STATUSES; + $lastStatus = array_pop($statuses); + + throw new \InvalidArgumentException( + "Subscription status should be ". + "'" . implode("', '", $statuses) . "' ". + "or '" . $lastStatus . "'." + ); } $queryString = http_build_query([ 'PageNumber' => $pageNumber, - 'PageSize' => $pageSize, + 'PageSize' => $pageSize, ]); - $response = $this->context->makeRequest( - "/ConsoleService.svc/Console/List/{$this->id}/Recipients/{$subscriptionStatus}?$queryString", - "GET" - ); - - $body = self::getJSON($response); - - $items = $body['Items']; $recipients = []; - - foreach ($items as $item) { - $recipients[] = Recipient::fromResponseArray($item); + foreach (Recipient::SUBSCRIPTION_STATUSES as $status) { + $path = "/ConsoleService.svc/Console/List/{$this->id}" + . "/Recipients/{$status}" + . "?{$queryString}"; + + $response = $this->context->makeRequest($path, 'GET'); + $body = self::getJSON($response); + foreach ($body['Items'] as $item) { + $recipients[] = Recipient::fromResponseArray($item); + } } return $recipients; @@ -284,13 +348,14 @@ public function getRecipientsPaginated( */ public static function getAll(Context $context): array { - $response = $context->makeRequest('/ConsoleService.svc/Console/User/Lists', 'GET'); + $response = $context->makeRequest( + '/ConsoleService.svc/Console/User/Lists', + 'GET' + ); $body = self::getJSON($response); - $items = $body['Items']; - $lists = []; - foreach ($items as $item) { + foreach ($body['Items'] as $item) { $lists[] = self::fromResponseArray($context, $item); } @@ -305,49 +370,57 @@ public static function getAll(Context $context): array * * @return MailingList */ - public static function create(Context $context, string $name, string $ownerEmail, array $options = []): self - { + public static function create( + Context $context, + string $name, + string $ownerEmail, + array $options = [] + ): self { $options = self::resolveCreateOptions($options); $params = array_filter([ - 'bouncedemail' => $options['bounced_emails_addr'], - 'charset' => $options['charset'], - 'default_prefix' => $options['phone_default_intl_prefix'], - 'description' => $options['description'], - 'disclaimer' => $options['disclaimer'], - 'displayas' => $options['custom_to'], - 'format' => $options['format'], - 'frontendform' => $options['hosted_subscription_form'], + 'bouncedemail' => $options['bounced_emails_addr'], + 'charset' => $options['charset'], + 'default_prefix' => $options['phone_default_intl_prefix'], + 'description' => $options['description'], + 'disclaimer' => $options['disclaimer'], + 'displayas' => $options['custom_to'], + 'format' => $options['format'], + 'frontendform' => $options['hosted_subscription_form'], 'headerlistunsubscriber' => $options['list-unsubscribe_header'], - 'headerxabuse' => $options['abuse_report_notice'], - 'kbmax' => 100, - 'multipart_text' => $options['auto_generate_text_part'], - 'nl_sendername' => $options['sender_name'], - 'notifyemail' => $options['unsubscribe_notification_email'], - 'optout_type' => $options['optout_type'], - 'owneremail' => $ownerEmail, - 'public' => false, - 'replyto' => $options['reply_to_addr'], - 'sendconfirmsms' => $options['sms_on_subscription'], - 'subscribedemail' => $options['email_on_subscription'], - 'sendemailoptout' => $options['send_goodbye_mail'], - 'tracking' => $options['enable_tracking'], - 'Customer' => $options['is_customers_list'], - 'business' => $options['is_business_list'], - 'Name' => $name, - 'copyTemplate' => false, - 'copyWebhooks' => false, - 'idSettings' => '', - 'scope' => $options['scope'], - 'useDefaultSettings' => true + 'headerxabuse' => $options['abuse_report_notice'], + 'kbmax' => 100, + 'multipart_text' => $options['auto_generate_text_part'], + 'nl_sendername' => $options['sender_name'], + 'notifyemail' => $options['unsubscribe_notification_email'], + 'optout_type' => $options['optout_type'], + 'owneremail' => $ownerEmail, + 'public' => false, + 'replyto' => $options['reply_to_addr'], + 'sendconfirmsms' => $options['sms_on_subscription'], + 'subscribedemail' => $options['email_on_subscription'], + 'sendemailoptout' => $options['send_goodbye_mail'], + 'tracking' => $options['enable_tracking'], + 'Customer' => $options['is_customers_list'], + 'business' => $options['is_business_list'], + 'Name' => $name, + 'copyTemplate' => false, + 'copyWebhooks' => false, + 'idSettings' => '', + 'scope' => $options['scope'], + 'useDefaultSettings' => true ], function ($element) { return null === $element; }); - $response = $context->makeRequest('/ConsoleService.svc/Console/User/Lists', 'GET', $params); + $response = $context->makeRequest( + '/ConsoleService.svc/Console/User/Lists', + 'GET', + $params + ); $id = self::getJSON($response); $list = new self($context); - $list->id = $id; + $list->id = $id; $list->name = $name; return $list; @@ -362,28 +435,28 @@ private static function resolveCreateOptions(array $options): array { $resolver = new OptionsResolver(); $resolver->setDefaults([ - 'bounced_emails_addr' => null, - 'charset' => 'UTF-8', - 'phone_default_intl_prefix' => null, - 'description' => null, - 'disclaimer' => null, - 'custom_to' => null, - 'format' => 'html', - 'hosted_subscription_form' => false, - 'list-unsubscribe_header' => '<[listunsubscribe]>,<[mailto_uns]>', - 'abuse_report_notice' => 'Please report abuse here: http://[host]/p', - 'auto_generate_text_part' => true, - 'sender_name' => null, + 'bounced_emails_addr' => null, + 'charset' => 'UTF-8', + 'phone_default_intl_prefix' => null, + 'description' => null, + 'disclaimer' => null, + 'custom_to' => null, + 'format' => 'html', + 'hosted_subscription_form' => false, + 'list-unsubscribe_header' => '<[listunsubscribe]>,<[mailto_uns]>', + 'abuse_report_notice' => 'Please report abuse here: http://[host]/p', + 'auto_generate_text_part' => true, + 'sender_name' => null, 'unsubscribe_notification_email' => null, - 'optout_type' => self::OPTOUT_ONE_CLICK, - 'reply_to_addr' => null, - 'sms_on_subscription' => false, - 'email_on_subscription' => false, - 'send_goodbye_mail' => false, - 'enable_tracking' => true, - 'is_customers_list' => true, - 'is_business_list' => false, - 'scope' => self::SCOPE_NEWSLETTER, + 'optout_type' => self::OPTOUT_ONE_CLICK, + 'reply_to_addr' => null, + 'sms_on_subscription' => false, + 'email_on_subscription' => false, + 'send_goodbye_mail' => false, + 'enable_tracking' => true, + 'is_customers_list' => true, + 'is_business_list' => false, + 'scope' => self::SCOPE_NEWSLETTER, ]); return $resolver->resolve($options); diff --git a/lib/Recipient.php b/lib/Recipient.php index eba9cef..73c9423 100644 --- a/lib/Recipient.php +++ b/lib/Recipient.php @@ -10,14 +10,15 @@ */ class Recipient extends Resource implements \JsonSerializable { - const STATUS_SUBSCRIBED = "Subscribed"; + const STATUS_SUBSCRIBED = "Subscribed"; const STATUS_UNSUBSCRIBED = "Unsubscribed"; - const STATUS_PENDING = "Pending"; + const STATUS_PENDING = "Pending"; + const STATUS_ANY = "Any"; const SUBSCRIPTION_STATUSES = [ self::STATUS_SUBSCRIBED, self::STATUS_UNSUBSCRIBED, - self::STATUS_PENDING + self::STATUS_PENDING, ]; /** @@ -52,6 +53,7 @@ class Recipient extends Resource implements \JsonSerializable /** * Recipient constructor. + * * @param string $name * @param string $email * @param null|string $mobilePhone @@ -65,11 +67,11 @@ public function __construct( string $mobilePrefix = null, array $fields = [] ) { - $this->name = $name; - $this->email = $email; + $this->name = $name; + $this->email = $email; $this->mobileNumber = $mobilePhone; $this->mobilePrefix = $mobilePrefix; - $this->fields = $fields; + $this->fields = $fields; } /** @@ -153,7 +155,11 @@ public static function fromResponseArray(array $response): self { $toFields = function (array $fields) { foreach ($fields as $field) { - yield new DynamicField($field['Description'], $field['Value'], $field['Id']); + yield new DynamicField( + $field['Description'], + $field['Value'], + $field['Id'] + ); } }; @@ -176,11 +182,11 @@ public static function fromResponseArray(array $response): self public function jsonSerialize(): array { $recipient = [ - 'Name' => $this->name, - 'Email' => $this->email, + 'Name' => $this->name, + 'Email' => $this->email, 'MobileNumber' => $this->mobileNumber, 'MobilePrefix' => $this->mobilePrefix, - 'Fields' => $this->fields, + 'Fields' => $this->fields, ]; if (null !== $this->id) { @@ -197,7 +203,10 @@ public function jsonSerialize(): array */ public static function getDynamicFields(Context $context): array { - $response = $context->makeRequest('/ConsoleService.svc/Console/Recipient/DynamicFields', 'GET'); + $response = $context->makeRequest( + '/ConsoleService.svc/Console/Recipient/DynamicFields', + 'GET' + ); $body = self::getJSON($response); $fields = []; diff --git a/lib/Resource.php b/lib/Resource.php index 2c0a23e..2f76160 100644 --- a/lib/Resource.php +++ b/lib/Resource.php @@ -18,7 +18,7 @@ abstract class Resource */ public static function getJSON(ResponseInterface $response) { - $body = (string)$response->getBody(); + $body = (string) $response->getBody(); return json_decode($body, true); } } diff --git a/lib/Token/NullToken.php b/lib/Token/NullToken.php index b6490bb..2e04a51 100644 --- a/lib/Token/NullToken.php +++ b/lib/Token/NullToken.php @@ -12,7 +12,7 @@ final class NullToken implements TokenInterface /** * @inheritDoc */ - public function isValid() : bool + public function isValid(): bool { return false; } @@ -20,7 +20,7 @@ public function isValid() : bool /** * @inheritDoc */ - public function shouldBeRefreshed() : bool + public function shouldBeRefreshed(): bool { return true; } @@ -28,7 +28,7 @@ public function shouldBeRefreshed() : bool /** * @inheritDoc */ - public function getAccessToken() : string + public function getAccessToken(): string { throw new \LogicException('Invalid call'); } @@ -36,7 +36,7 @@ public function getAccessToken() : string /** * @inheritDoc */ - public function getRefreshToken() : string + public function getRefreshToken(): string { throw new \LogicException('Invalid call'); } diff --git a/lib/Token/Token.php b/lib/Token/Token.php index d233093..d037030 100644 --- a/lib/Token/Token.php +++ b/lib/Token/Token.php @@ -27,10 +27,13 @@ final class Token implements TokenInterface */ private $refreshToken; - public function __construct(string $accessToken, int $validUntilTimestamp, string $refreshToken) - { - $this->accessToken = $accessToken; - $this->validUntil = $validUntilTimestamp; + public function __construct( + string $accessToken, + int $validUntilTimestamp, + string $refreshToken + ) { + $this->accessToken = $accessToken; + $this->validUntil = $validUntilTimestamp; $this->refreshToken = $refreshToken; } @@ -46,11 +49,18 @@ public function __construct(string $accessToken, int $validUntilTimestamp, strin public static function fromJson(string $json): self { $object = @json_decode($json); - if (null === $object || ! isset($object->accessToken, $object->validUntil, $object->refreshToken)) { + if ( + null === $object + || ! isset($object->accessToken, $object->validUntil, $object->refreshToken) + ) { throw new InvalidTokenException(); } - $token = new self($object->accessToken, $object->validUntil, $object->refreshToken); + $token = new self( + $object->accessToken, + $object->validUntil, + $object->refreshToken + ); if (! $token->isValid()) { throw new InvalidTokenException(); } @@ -69,13 +79,20 @@ public static function fromJson(string $json): self */ public static function fromResponse(ResponseInterface $response): self { - $json = (string)$response->getBody(); + $json = (string) $response->getBody(); $object = @json_decode($json); - if (null === $object || ! isset($object->access_token, $object->expires_in, $object->refresh_token)) { + if ( + null === $object + || ! isset($object->access_token, $object->expires_in, $object->refresh_token) + ) { throw new InvalidTokenException(); } - $token = new self($object->access_token, time() + $object->expires_in, $object->refresh_token); + $token = new self( + $object->access_token, + time() + $object->expires_in, + $object->refresh_token + ); return $token; } @@ -117,8 +134,8 @@ public function getRefreshToken(): string public function jsonSerialize() { return [ - 'accessToken' => $this->accessToken, - 'validUntil' => $this->validUntil, + 'accessToken' => $this->accessToken, + 'validUntil' => $this->validUntil, 'refreshToken' => $this->refreshToken, ]; }