Skip to content

Commit

Permalink
Syncing 2019 updates
Browse files Browse the repository at this point in the history
  • Loading branch information
douglasmiller committed Mar 10, 2021
2 parents 18d69ff + 988630a commit 4d131cb
Show file tree
Hide file tree
Showing 25 changed files with 816 additions and 150 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ sudo: false
dist: trusty
install:
- composer install --dev
script: vendor/phpunit/phpunit/phpunit tests
script: vendor/bin/phpunit tests
130 changes: 130 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@

# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
dx@recurly.com.
All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series
of actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.

Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

4 changes: 4 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ however, we may not get to these right away. Although we try to be quick, our pr
writing code. If you want a timely response (especially if you have an emergency), we recommend
you contact our [official support team](https://support.recurly.com/).

## Code of Conduct

Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.

#### Table Of Contents

* [I don't want to read this whole thing, I just have a question!!!](#i-dont-want-to-read-this-whole-thing-i-just-have-a-question)
Expand Down
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Recurly
[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg)](CODE_OF_CONDUCT.md)

This repository houses the official php client for Recurly's V3 API.

Expand Down Expand Up @@ -35,6 +36,19 @@ $api_key = 'myApiKey';
$client = new \Recurly\Client($api_key);
```

#### Logging

The client constructor optionally accepts a logger provided by the programmer. The logger you pass should implement the [PSR-3 Logger Interface](https://www.php-fig.org/psr/psr-3/). By default, the client creates an instance of the `\Recurly\Logger` which is a basic implementation that prints log messages to `php://stdout` with the `\Psr\Log\LogLevel::WARNING` level.

```php
// Create an instance of the Recurly\Logger
$logger = new \Recurly\Logger('Recurly', \Psr\Log\LogLevel::INFO);

$client = new \Recurly\Client($api_key, $logger);
```

> *SECURITY WARNING*: The log level should never be set to DEBUG in production. This could potentially result in sensitive data in your logging system.
### Operations

The `\Recurly\Client` contains every operation you can perform on the site as a list of methods. Each method is documented explaining the types and descriptions for each input and return type. For example, to use the [get_plan](https://developers.recurly.com/api/latest/index.html#operation/get_plan) endpoint, call the `Client#getPlan()` method:
Expand Down Expand Up @@ -116,6 +130,10 @@ $accounts = $client->listAccounts([ 'order' => 'asc', 'past_due' => true ]);
$account = $accounts->getFirst();
```

#### A Note on Headers

In accordance with [section 4.2 of RFC 2616](https://www.ietf.org/rfc/rfc2616.txt), HTTP header fields are case-insensitive.

### Creating Resources

For creating or updating resources, pass a plain associative array to one of the `create*` or `update*` methods:
Expand Down Expand Up @@ -162,6 +180,8 @@ try {
}
```

### HTTP Metadata

Sometimes you might want to get some additional information about the underlying HTTP request and response. Instead of returning this information directly and forcing the programmer to unwrap it, we inject this metadata into the top level resource that was returned. You can access the response by calling `getResponse()` on any Resource.

> **Warning**:
Expand All @@ -174,6 +194,19 @@ echo "Request ID:" . $response->getRequestId() . PHP_EOL;
echo "Rate limit remaining:" . $response->getRateLimitRemaining() . PHP_EOL;
```

Information about the request is also included in the `\Recurly\Response` class and can be accessed using the `getRequest()` method on the Response.

```php
$account = $client->getAccount("code-douglas");
$response = $account->getResponse();
$request = $response->getRequest();
echo "Request path:" . $request->getPath() . PHP_EOL;
echo "Request body as JSON:" . $request->getBodyAsJson() . PHP_EOL;
foreach($request->getHeaders() as $k => $v) {
echo "Request header: $k => $v" . PHP_EOL;
}
```

This also works on `Empty` resources (for when there is no return body):

```php
Expand Down
93 changes: 76 additions & 17 deletions lib/recurly/base_client.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace Recurly;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

abstract class BaseClient
{
use RecurlyTraits;
Expand All @@ -13,16 +16,28 @@ abstract class BaseClient
'params',
'headers'
];
private $_logger;

/**
* Constructor
*
* @param string $api_key The API key to use when making requests
*/
public function __construct(string $api_key)
public function __construct(string $api_key, LoggerInterface $logger = null)
{
$this->_api_key = $api_key;
$this->http = new HttpAdapter;
if (is_null($logger)) {
$logger = new \Recurly\Logger('Recurly', LogLevel::WARNING);
}
$this->_logger = $logger;

// Send Security Warning to logger debug
$msg = "The Recurly logger should not be initialized";
$msg .= "\nbeyond the level INFO. It is currently configured to emit";
$msg .= "\nheaders and request / response bodies. This has the potential to leak";
$msg .= "\nPII and other sensitive information and should never be used in production.";
$this->_logger->debug("SECURITY WARNING: {$msg}");
}

/**
Expand All @@ -45,7 +60,13 @@ abstract protected function apiVersion(): string;
protected function makeRequest(string $method, string $path, array $body = [], array $options = []): \Recurly\RecurlyResource
{
$this->_validateOptions($options);
$response = $this->_getResponse($method, $path, $body, $options);
$path = $this->_buildPath($path, $options);
$formattedBody = $this->_formatDateTimes($body);
$options['core_headers'] = $this->_coreHeaders();

$request = new \Recurly\Request($method, $path, $formattedBody, $options);

$response = $this->_getResponse($request);
$resource = $response->toResource();
return $resource;
}
Expand All @@ -54,25 +75,42 @@ protected function makeRequest(string $method, string $path, array $body = [], a
/**
* Performs the HTTP request to the Recurly API
*
* @param string $method HTTP method to use
* @param string $path Tokenized path to request
* @param array $body The request body
* @param array $options Additional request parameters (including query parameters)
* @param \Recurly\Request $request The \Recurly\Request object
*
* @return \Recurly\Response A Recurly Response object
*/
private function _getResponse(string $method, string $path, array $body = [], array $options = []): \Recurly\Response
private function _getResponse(\Recurly\Request $request): \Recurly\Response
{
$headers = $this->_buildHeaders($options);
$request = new \Recurly\Request($method, $path, $body, $options);

$url = $this->_buildPath($path, $options);
$formattedBody = $this->_formatDateTimes($body);
list($result, $response_header) = $this->http->execute($method, $url, $formattedBody, $headers);
$this->_logger->info(
'Request', [
'method' => $request->getMethod(),
'path' => $request->getPath()
]
);
$this->_logger->debug(
'Request', [
'request_body' => $request->getBodyAsJson(),
'request_headers' => $request->getHeaders()
]
);
$start = microtime(true);
list($result, $response_header) = $this->http->execute($request->getMethod(), $request->getPath(), $request->getBodyAsJson(), $request->getHeaders());
$end = microtime(true);

// TODO: The $request should be added to the $response
$response = new \Recurly\Response($result, $request);
$response->setHeaders($response_header);
$this->_logger->info(
'Response', [
'time_ms' => intval(($end - $start) * 1000),
'status' => $response->getStatusCode()
]
);
$this->_logger->debug(
'Response', [
'response_body' => $response->getRawResponse(),
'response_headers' => $response->getHeaders()
]
);

return $response;
}
Expand Down Expand Up @@ -100,7 +138,10 @@ public function nextPage(string $path, array $options = []): \Recurly\Page
*/
public function pagerCount(string $path, ?array $options = []): \Recurly\Response
{
return $this->_getResponse('HEAD', $path, [], $options);
$path = $this->_buildPath($path, $options);
$options['core_headers'] = $this->_coreHeaders();
$request = new \Recurly\Request('HEAD', $path, [], $options);
return $this->_getResponse($request);
}

/**
Expand Down Expand Up @@ -240,12 +281,30 @@ private function _buildHeaders(array $options): array
$agent = self::getUserAgent();
return array_merge(
$headers, [
"User-Agent" => $agent,
"Authorization" => "Basic {$auth_token}",
"Accept" => "application/vnd.recurly.{$this->apiVersion()}",
"Content-Type" => "application/json",
"Accept-Encoding" => "gzip",
]
);
}

/**
* Generates core headers to be sent with the HTTP request
*
* @return array Array representation of the core request HTTP headers
*/
private function _coreHeaders(): array
{
$auth_token = self::encodeApiKey($this->_api_key);
$agent = self::getUserAgent();
return [
"User-Agent" => $agent,
"Authorization" => "Basic {$auth_token}",
"Accept" => "application/vnd.recurly.{$this->apiVersion()}",
"Content-Type" => "application/json",
"Accept-Encoding" => "gzip",
]
);
];
}
}
Loading

0 comments on commit 4d131cb

Please sign in to comment.