Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New functionality #3

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
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
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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', '[email protected]', '3333333333', '+39'));
$recipient = new Recipient('Aragorn', '[email protected]', '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
Expand All @@ -98,7 +101,13 @@ $list->removeRecipient(new Recipient('Aragorn', '[email protected]', '333333333
```
- find a `Recipient` by its `email`
```php
$recipient = $list->findRecipient('[email protected]'); // null returned if current email was not found
$recipient = $list->findRecipient('[email protected]'); // null returned if current email was not found. Equal to $list->findRecipient('[email protected]', Recipient::STATUS_SUBSCRIBED);
// OR
$list->findRecipient('[email protected]', Recipient::STATUS_UNSUBSCRIBED);
// OR
$list->findRecipient('[email protected]', Recipient::STATUS_PENDING);
// OR
$list->findRecipient('[email protected]', Recipient::STATUS_ANY); // find by any of the statuses
```
- retrieve all the groups of the current list:
```php
Expand All @@ -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
Expand Down
73 changes: 45 additions & 28 deletions lib/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please, do not use internal indentation for assignments


/**
* @var string
Expand Down Expand Up @@ -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'];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please, do not use internal indentation for assignments

}

/**
Expand All @@ -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;
Expand Down Expand Up @@ -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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add last ,

);

$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}";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do not break a line (event strings) if it stays within the soft limit of PSR-2 (120 chars, http://www.php-fig.org/psr/psr-2/#overview).

Also, keep the operator in the line of the first argument. In this case it should be (but it is not for what mentioned above):

$message = "Response not OK when requesting an access token. "  .
     "Response body: {$responseBody}"
;


throw new InvalidResponseException($response, $message);
}
Expand All @@ -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,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please, do not use internal indentation for assignments

'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),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

spaces between . operator and its arguments

],
$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}";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above (multiple lines and strings)


throw new InvalidResponseException($response, $message);
}
Expand All @@ -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));
}

Expand Down
8 changes: 4 additions & 4 deletions lib/DynamicField.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

internal indentation

}

/**
Expand Down Expand Up @@ -75,8 +75,8 @@ public function jsonSerialize(): array
{
return [
'Description' => $this->fieldName,
'Id' => $this->id,
'Value' => $this->value,
'Id' => $this->id,
'Value' => $this->value,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

internal indentation

];
}
}
8 changes: 6 additions & 2 deletions lib/Exception/InvalidResponseException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add string and int argument types?

$this->response = $response;
parent::__construct($message, $code, $previous);
}
Expand Down
53 changes: 35 additions & 18 deletions lib/ListGroup.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,22 @@ 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;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

internal indentation

}

/**
* @param Context $context
* @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'])
Expand Down Expand Up @@ -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}",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above (multiple lines and strings)

'DELETE'
);
}
Expand All @@ -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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above (120 chars as soft line limit and internal indentation)

*
* @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
);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above (multiple lines and strings), also there must be only 1 indent


$recipient->setId(self::getJSON($response));

Expand All @@ -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()}",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above (multiple lines and strings)

'DELETE'
);
}
Expand All @@ -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'
);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above (multiple lines and strings)


$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);
}

Expand Down
Loading