Fix conflitti master

This commit is contained in:
Armando Caprio
2021-07-09 10:04:19 +02:00
37 changed files with 1644 additions and 368 deletions

40
.github/workflows/lint.yml vendored Normal file
View File

@@ -0,0 +1,40 @@
name: Lint
on:
push:
branches: [ '*' ]
pull_request:
branches: [ '*' ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php-versions: ['7.0', '7.1', '7.2', '7.3', '7.4']
steps:
- uses: actions/checkout@v2
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
- name: Cache Composer dependencies
uses: actions/cache@v2
with:
path: /tmp/composer-cache
key: ${{ runner.os }}-php${{ matrix.php-versions }}-${{ hashFiles('**/composer.lock') }}
- name: Install dependencies
uses: php-actions/composer@v5
with:
command: install
args: --prefer-dist --no-progress --no-suggest --verbose
php_version: ${{ matrix.php-versions }}
version: 1
- name: Run lint
run: make lint

40
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,40 @@
name: Test
on:
push:
branches: [ '*' ]
pull_request:
branches: [ '*' ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php-versions: ['7.0', '7.1', '7.2', '7.3', '7.4']
steps:
- uses: actions/checkout@v2
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
- name: Cache Composer dependencies
uses: actions/cache@v2
with:
path: /tmp/composer-cache
key: ${{ runner.os }}-php${{ matrix.php-versions }}-${{ hashFiles('**/composer.lock') }}
- name: Install dependencies
uses: php-actions/composer@v5
with:
command: install
args: --prefer-dist --no-progress --no-suggest --verbose
php_version: ${{ matrix.php-versions }}
version: 1
- name: Run tests
run: make test

View File

@@ -1,15 +0,0 @@
language: php
php:
- 7.0
- 7.1
before_install:
- composer self-update
install:
- travis_retry composer install --no-interaction --prefer-source
script:
- make lint
- make test

View File

@@ -1,17 +1,14 @@
THIS := $(realpath $(lastword $(MAKEFILE_LIST)))
HERE := $(shell dirname $(THIS))
.PHONY: all fix lint test .PHONY: all fix lint test
all: lint test all: lint test
fix: fix:
php $(HERE)/vendor/bin/php-cs-fixer fix --config=$(HERE)/.php_cs php vendor/bin/php-cs-fixer fix --config=.php_cs
lint: lint:
php $(HERE)/vendor/bin/php-cs-fixer fix --config=$(HERE)/.php_cs --dry-run php vendor/bin/php-cs-fixer fix --config=.php_cs --dry-run
php $(HERE)/vendor/bin/phpmd src/ text cleancode,codesize,controversial,design,naming,unusedcode php vendor/bin/phpmd src/ text cleancode,codesize,controversial,design,naming,unusedcode
php $(HERE)/vendor/bin/phpmd tests/ text cleancode,codesize,controversial,design,naming,unusedcode php vendor/bin/phpmd tests/ text cleancode,codesize,controversial,design,naming,unusedcode
test: test:
php $(HERE)/vendor/bin/phpunit --configuration $(HERE)/phpunit.xml php vendor/bin/phpunit --configuration phpunit.xml

View File

@@ -3,13 +3,13 @@
"description": "PHP binding for v4 of the Cloudflare Client API.", "description": "PHP binding for v4 of the Cloudflare Client API.",
"type": "library", "type": "library",
"require": { "require": {
"guzzlehttp/guzzle": "^6.2.2", "guzzlehttp/guzzle": "^7.0.1",
"php": ">=7.0.0", "php": ">=7.2.5",
"psr/http-message": "~1.0", "psr/http-message": "~1.0",
"ext-json": "*" "ext-json": "*"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "5.7.5", "phpunit/phpunit": "^5.7",
"phpmd/phpmd" : "@stable", "phpmd/phpmd" : "@stable",
"friendsofphp/php-cs-fixer": "^2.6" "friendsofphp/php-cs-fixer": "^2.6"
}, },

534
composer.lock generated

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@@ -1,14 +1,10 @@
<?php <?php
/**
* User: junade
* Date: 13/01/2017
* Time: 18:26
*/
namespace Cloudflare\API\Adapter; namespace Cloudflare\API\Adapter;
use Cloudflare\API\Auth\Auth; use Cloudflare\API\Auth\Auth;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
class Guzzle implements Adapter class Guzzle implements Adapter
@@ -74,36 +70,24 @@ class Guzzle implements Adapter
return $this->request('delete', $uri, $data, $headers); return $this->request('delete', $uri, $data, $headers);
} }
/**
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function request(string $method, string $uri, array $data = [], array $headers = []) public function request(string $method, string $uri, array $data = [], array $headers = [])
{ {
if (!in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) { if (!in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
throw new \InvalidArgumentException('Request method must be get, post, put, patch, or delete'); throw new \InvalidArgumentException('Request method must be get, post, put, patch, or delete');
} }
try {
$response = $this->client->$method($uri, [ $response = $this->client->$method($uri, [
'headers' => $headers, 'headers' => $headers,
($method === 'get' ? 'query' : 'json') => $data, ($method === 'get' ? 'query' : 'json') => $data,
]); ]);
} catch (RequestException $err) {
$this->checkError($response); throw ResponseException::fromRequestException($err);
}
return $response; return $response;
} }
private function checkError(ResponseInterface $response)
{
$json = json_decode($response->getBody());
if (json_last_error() !== JSON_ERROR_NONE) {
throw new JSONException();
}
if (isset($json->errors) && count($json->errors) >= 1) {
throw new ResponseException($json->errors[0]->message, $json->errors[0]->code);
}
if (isset($json->success) && !$json->success) {
throw new ResponseException('Request was unsuccessful.');
}
}
} }

View File

@@ -8,6 +8,37 @@
namespace Cloudflare\API\Adapter; namespace Cloudflare\API\Adapter;
use GuzzleHttp\Exception\RequestException;
class ResponseException extends \Exception class ResponseException extends \Exception
{ {
/**
* Generates a ResponseException from a Guzzle RequestException.
*
* @param RequestException $err The client request exception (typicall 4xx or 5xx response).
* @return ResponseException
*/
public static function fromRequestException(RequestException $err): self
{
if (!$err->hasResponse()) {
return new ResponseException($err->getMessage(), 0, $err);
}
$response = $err->getResponse();
$contentType = $response->getHeaderLine('Content-Type');
// Attempt to derive detailed error from standard JSON response.
if (strpos($contentType, 'application/json') !== false) {
$json = json_decode($response->getBody());
if (json_last_error() !== JSON_ERROR_NONE) {
return new ResponseException($err->getMessage(), 0, new JSONException(json_last_error_msg(), 0, $err));
}
if (isset($json->errors) && count($json->errors) >= 1) {
return new ResponseException($json->errors[0]->message, $json->errors[0]->code, $err);
}
}
return new ResponseException($err->getMessage(), 0, $err);
}
} }

View File

@@ -0,0 +1,58 @@
<?php
namespace Cloudflare\API\Configurations;
class Certificate implements Configurations
{
const ORIGIN_RSA = 'origin-rsa';
const ORIGIN_ECC = 'origin-ecc';
const KEYLESS_CERTIFICATE = 'keyless-certificate';
private $config = [];
public function getArray(): array
{
return $this->config;
}
/**
* Array of hostnames or wildcard names (e.g., *.example.com) bound to the certificate
* Example: $hostnames = ["example.com", "foo.example.com"]
* @param array $hostnames
*/
public function setHostnames(array $hostnames)
{
$this->config['hostnames'] = $hostnames;
}
/**
* The number of days for which the certificate should be valid
* Default value: 5475
* Valid values: 7, 30, 90, 365, 730, 1095, 5475
* @param int $validity
*/
public function setRequestedValidity(int $validity)
{
$this->config['requested_validity'] = $validity;
}
/**
* Signature type desired on certificate ("origin-rsa" (rsa), "origin-ecc" (ecdsa), or "keyless-certificate" (for Keyless SSL servers)
* Valid values: origin-rsa, origin-ecc, keyless-certificate
* @param string $type
*/
public function setRequestType(string $type)
{
$this->config['request_type'] = $type;
}
/**
* The Certificate Signing Request (CSR). Must be newline-encoded.
*
* @param string $csr
*/
public function setCsr(string $csr)
{
$this->config['csr'] = $csr;
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Cloudflare\API\Configurations;
class DNSAnalytics implements Configurations
{
protected $configs = [];
public function getArray(): array
{
return $this->configs;
}
public function setDimensions(array $dimensions)
{
if (count($dimensions) !== 0) {
$this->configs['dimensions'] = implode(',', $dimensions);
}
}
public function setMetrics(array $metrics)
{
if (count($metrics) !== 0) {
$this->configs['metrics'] = implode(',', $metrics);
}
}
public function setSince(string $since)
{
if ($since) {
$this->configs['since'] = $since;
}
}
public function setUntil(string $until)
{
if ($until) {
$this->configs['until'] = $until;
}
}
public function setSorting(array $sorting)
{
if (count($sorting) !== 0) {
$this->configs['sort'] = implode(',', $sorting);
}
}
public function setFilters(string $filters)
{
if ($filters) {
$this->configs['filters'] = $filters;
}
}
public function setLimit(int $limit)
{
if ($limit) {
$this->configs['limit'] = $limit;
}
}
public function setTimeDelta(string $timeDelta)
{
if ($timeDelta) {
$this->configs['time_delta'] = $timeDelta;
}
}
}

View File

@@ -117,7 +117,7 @@ class PageRulesActions implements Configurations
public function setEdgeCacheTTL(int $value) public function setEdgeCacheTTL(int $value)
{ {
if ($value > 2419200) { if ($value > 2678400) {
throw new ConfigurationsException('Edge Cache TTL too high.'); throw new ConfigurationsException('Edge Cache TTL too high.');
} }

View File

@@ -0,0 +1,86 @@
<?php
namespace Cloudflare\API\Endpoints;
use Cloudflare\API\Adapter\Adapter;
use Cloudflare\API\Configurations\Certificate as CertificateConfig;
use Cloudflare\API\Traits\BodyAccessorTrait;
class Certificates implements API
{
use BodyAccessorTrait;
private $adapter;
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
}
/**
* List all existing Origin CA certificates for a given zone
*
* @param string $zoneID
* @return array
*/
public function listCertificates(string $zoneID): \stdClass
{
$certificates = $this->adapter->get('certificates', ['zone_id' => $zoneID]);
$this->body = json_decode($certificates->getBody());
return (object)['result' => $this->body->result];
}
/**
* Get an existing Origin CA certificate by its serial number
*
* @param string $certificateID
* @param string $zoneID
* @return mixed
*/
public function getCertificate(string $certificateID, string $zoneID)
{
$certificates = $this->adapter->get('certificates/'.$certificateID, ['zone_id' => $zoneID]);
$this->body = json_decode($certificates->getBody());
return (object)['result' => $this->body->result];
}
/**
* Revoke an existing Origin CA certificate by its serial number
*
* @param string $certificateID
* @param string $zoneID
* @return bool
*/
public function revokeCertificate(string $certificateID, string $zoneID): bool
{
$certificates = $this->adapter->delete('certificates/'.$certificateID, ['zone_id' => $zoneID]);
$this->body = json_decode($certificates->getBody());
if (isset($this->body->result->id)) {
return true;
}
return false;
}
/**
* Create an Origin CA certificate
*
* @param CertificateConfig $config
* @return bool
*/
public function createCertificate(CertificateConfig $config): bool
{
$certificate = $this->adapter->post('certificates', $config->getArray());
$this->body = json_decode($certificate->getBody());
if (isset($this->body->result->id)) {
return true;
}
return false;
}
}

View File

@@ -30,18 +30,50 @@ class CustomHostnames implements API
* @param string $hostname * @param string $hostname
* @param string $sslMethod * @param string $sslMethod
* @param string $sslType * @param string $sslType
* @param array $sslSettings
* @param string $customOriginServer
* @param bool $wildcard
* @param string $bundleMethod
* @param array $customSsl
* @return \stdClass * @return \stdClass
*/ */
public function addHostname(string $zoneID, string $hostname, string $sslMethod = 'http', string $sslType = 'dv'): \stdClass public function addHostname(
{ string $zoneID,
string $hostname,
string $sslMethod = 'http',
string $sslType = 'dv',
array $sslSettings = [],
string $customOriginServer = '',
bool $wildcard = false,
string $bundleMethod = '',
array $customSsl = []
): \stdClass {
$options = [ $options = [
'hostname' => $hostname, 'hostname' => $hostname,
'ssl' => [ 'ssl' => [
'method' => $sslMethod, 'method' => $sslMethod,
'type' => $sslType 'type' => $sslType,
] 'settings' => $sslSettings,
'wildcard' => $wildcard,
],
]; ];
if (!empty($customOriginServer)) {
$options['custom_origin_server'] = $customOriginServer;
}
if (!empty($bundleMethod)) {
$options['ssl']['bundle_method'] = $bundleMethod;
}
if (!empty($customSsl['key'])) {
$options['ssl']['custom_key'] = $customSsl['key'];
}
if (!empty($customSsl['certificate'])) {
$options['ssl']['custom_certificate'] = $customSsl['certificate'];
}
$zone = $this->adapter->post('zones/'.$zoneID.'/custom_hostnames', $options); $zone = $this->adapter->post('zones/'.$zoneID.'/custom_hostnames', $options);
$this->body = json_decode($zone->getBody()); $this->body = json_decode($zone->getBody());
return $this->body->result; return $this->body->result;
@@ -111,16 +143,33 @@ class CustomHostnames implements API
/** /**
* @SuppressWarnings(PHPMD.BooleanArgumentFlag) * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
* *
* @param string $zoneID * @param string $zoneID
* @param string $hostnameID * @param string $hostnameID
* @param string $sslMethod * @param string $sslMethod
* @param string $sslType * @param string $sslType
* @param array $sslSettings
* @param string $customOriginServer
* @param bool|null $wildcard
* @param string $bundleMethod
* @param array $customSsl
* @return \stdClass * @return \stdClass
*/ */
public function updateHostname(string $zoneID, string $hostnameID, string $sslMethod = '', string $sslType = ''): \stdClass public function updateHostname(
{ string $zoneID,
string $hostnameID,
string $sslMethod = '',
string $sslType = '',
array $sslSettings = [],
string $customOriginServer = '',
bool $wildcard = null,
string $bundleMethod = '',
array $customSsl = []
): \stdClass {
$query = []; $query = [];
$options = [];
if (!empty($sslMethod)) { if (!empty($sslMethod)) {
$query['method'] = $sslMethod; $query['method'] = $sslMethod;
@@ -130,9 +179,35 @@ class CustomHostnames implements API
$query['type'] = $sslType; $query['type'] = $sslType;
} }
if (!empty($sslSettings)) {
$query['settings'] = $sslSettings;
}
if (!is_null($wildcard)) {
$query['wildcard'] = $wildcard;
}
if (!empty($bundleMethod)) {
$query['bundle_method'] = $bundleMethod;
}
if (!empty($customSsl['key'])) {
$query['custom_key'] = $customSsl['key'];
}
if (!empty($customSsl['certificate'])) {
$query['custom_certificate'] = $customSsl['certificate'];
}
if (!empty($query)) {
$options = [ $options = [
'ssl' => $query 'ssl' => $query
]; ];
}
if (!empty($customOriginServer)) {
$options['custom_origin_server'] = $customOriginServer;
}
$zone = $this->adapter->patch('zones/'.$zoneID.'/custom_hostnames/'.$hostnameID, $options); $zone = $this->adapter->patch('zones/'.$zoneID.'/custom_hostnames/'.$hostnameID, $options);
$this->body = json_decode($zone->getBody()); $this->body = json_decode($zone->getBody());
@@ -150,4 +225,16 @@ class CustomHostnames implements API
$this->body = json_decode($zone->getBody()); $this->body = json_decode($zone->getBody());
return $this->body; return $this->body;
} }
/**
* @param string $zoneID
* @return \stdClass
*/
public function getFallbackOrigin(string $zoneID): \stdClass
{
$zone = $this->adapter->get('zones/'.$zoneID.'/custom_hostnames/fallback_origin');
$this->body = json_decode($zone->getBody());
return $this->body->result;
}
} }

View File

@@ -56,7 +56,7 @@ class DNS implements API
$options['ttl'] = $ttl; $options['ttl'] = $ttl;
} }
if (!empty($priority)) { if (is_numeric($priority)) {
$options['priority'] = (int)$priority; $options['priority'] = (int)$priority;
} }

View File

@@ -0,0 +1,144 @@
<?php
/**
* Created by Visual Studio Code.
* User: elliot.alderson
* Date: 2020-02-06
* Time: 03:40 AM
*/
namespace Cloudflare\API\Endpoints;
use Cloudflare\API\Adapter\Adapter;
use Cloudflare\API\Traits\BodyAccessorTrait;
use Cloudflare\API\Configurations\DNSAnalytics as Configs;
class DNSAnalytics implements API
{
use BodyAccessorTrait;
private $adapter;
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
}
/**
* Retrieves a list of summarised aggregate metrics over a given time period.
*
* @param string $zoneID ID of zone to get report for
* @param string $dimensions Comma separated names of dimensions
* @param string $metrics Comma separated names of dimension to get metrics for
* @param string $sort Comma separated names of dimension to sort by prefixed by order - (descending) or + (ascending)
* @param string $filters Segmentation filter in 'attribute operator value' format
* @param string $since Start date and time of requesting data period in the ISO8601 format
* @param string $until End date and time of requesting data period in the ISO8601 format
* @param string $limit Limit number of returned metrics
* @return array
*/
public function getReportTable(
string $zoneID,
array $dimensions = [],
array $metrics = [],
array $sort = [],
string $filters = '',
string $since = '',
string $until = '',
int $limit = 100
): \stdClass {
if (count($dimensions) === 0) {
throw new EndpointException(
'At least one dimension is required for getting a report.'
);
}
if (count($metrics) === 0) {
throw new EndpointException(
'At least one metric is required for getting a report.'
);
}
if (!$since) {
throw new EndpointException(
'Start date is required for getting a report.'
);
}
if (!$until) {
throw new EndpointException(
'End date is required for getting a report.'
);
}
$options = [
'dimensions' => implode(',', $dimensions),
'metrics' => implode(',', $metrics),
'since' => $since,
'until' => $until
];
if (count($sort) !== 0) {
$options['sort'] = implode(',', $sort);
}
if ($filters) {
$options['filters'] = $filters;
}
if ($limit) {
$options['limit'] = $limit;
}
$endpoint = 'zones/' . $zoneID . '/dns_analytics/report';
$report = $this->adapter->get($endpoint, $options);
$this->body = json_decode($report->getBody());
return $this->body->result;
}
/**
* Retrieves a list of aggregate metrics grouped by time interval.
*
* @param string $zoneID ID of zone to get report for
* @param string $dimensions Comma separated names of dimensions
* @param string $metrics Comma separated names of dimension to get metrics for
* @param string $sort Comma separated names of dimension to sort by prefixed by order - (descending) or + (ascending)
* @param string $filters Segmentation filter in 'attribute operator value' format
* @param string $since Start date and time of requesting data period in the ISO8601 format
* @param string $until End date and time of requesting data period in the ISO8601 format
* @param string $limit Limit number of returned metrics
* @param string $timeDelta Unit of time to group data by
* @return array
*/
public function getReportByTime(
string $zoneID,
array $dimensions = [],
array $metrics = [],
array $sort = [],
string $filters = '',
string $since = '',
string $until = '',
int $limit = 100,
string $timeDelta = ''
): \stdClass {
$options = new Configs();
$options->setDimensions($dimensions);
$options->setMetrics($metrics);
$options->setSince($since);
$options->setUntil($until);
$options->setSorting($sort);
$options->setFilters($filters);
$options->setLimit($limit);
$options->setTimeDelta($timeDelta);
$endpoint = 'zones/' . $zoneID . '/dns_analytics/report/bytime';
$report = $this->adapter->get($endpoint, $options->getArray());
$this->body = json_decode($report->getBody());
return $this->body->result;
}
}

View File

@@ -106,6 +106,37 @@ class ZoneSettings implements API
return false; return false;
} }
public function getBrowserCacheTtlSetting($zoneID)
{
$return = $this->adapter->get(
'zones/' . $zoneID . '/settings/browser_cache_ttl'
);
$body = json_decode($return->getBody());
if ($body->success) {
return $body->result->value;
}
return false;
}
public function updateBrowserCacheTtlSetting($zoneID, $value)
{
$return = $this->adapter->patch(
'zones/' . $zoneID . '/settings/browser_cache_ttl',
[
'value' => $value
]
);
$body = json_decode($return->getBody());
if ($body->success) {
return true;
}
return false;
}
public function updateMinifySetting($zoneID, $html, $css, $javascript) public function updateMinifySetting($zoneID, $html, $css, $javascript)
{ {
$return = $this->adapter->patch( $return = $this->adapter->patch(

View File

@@ -217,7 +217,7 @@ class Zones implements API
*/ */
public function cachePurgeEverything(string $zoneID): bool public function cachePurgeEverything(string $zoneID): bool
{ {
$user = $this->adapter->delete('zones/' . $zoneID . '/purge_cache', ['purge_everything' => true]); $user = $this->adapter->post('zones/' . $zoneID . '/purge_cache', ['purge_everything' => true]);
$this->body = json_decode($user->getBody()); $this->body = json_decode($user->getBody());
@@ -247,7 +247,7 @@ class Zones implements API
$options['hosts'] = $hosts; $options['hosts'] = $hosts;
} }
$user = $this->adapter->delete('zones/' . $zoneID . '/purge_cache', $options); $user = $this->adapter->post('zones/' . $zoneID . '/purge_cache', $options);
$this->body = json_decode($user->getBody()); $this->body = json_decode($user->getBody());

View File

@@ -1,12 +1,6 @@
<?php <?php
/** use Cloudflare\API\Adapter\ResponseException;
* User: junade
* Date: 13/01/2017
* Time: 23:35
*/
use GuzzleHttp\Psr7\Response;
class GuzzleTest extends TestCase class GuzzleTest extends TestCase
{ {
@@ -89,48 +83,15 @@ class GuzzleTest extends TestCase
$this->assertEquals('Testing a DELETE request.', $body->json->{'X-Delete-Test'}); $this->assertEquals('Testing a DELETE request.', $body->json->{'X-Delete-Test'});
} }
public function testErrors()
{
$class = new ReflectionClass(\Cloudflare\API\Adapter\Guzzle::class);
$method = $class->getMethod('checkError');
$method->setAccessible(true);
$body =
'{
"result": null,
"success": false,
"errors": [{"code":1003,"message":"Invalid or missing zone id."}],
"messages": []
}'
;
$response = new Response(200, [], $body);
$this->expectException(\Cloudflare\API\Adapter\ResponseException::class);
$method->invokeArgs($this->client, [$response]);
$body =
'{
"result": null,
"success": false,
"errors": [],
"messages": []
}'
;
$response = new Response(200, [], $body);
$this->expectException(\Cloudflare\API\Adapter\ResponseException::class);
$method->invokeArgs($this->client, [$response]);
$body = 'this isnt json.';
$response = new Response(200, [], $body);
$this->expectException(\Cloudflare\API\Adapter\JSONException::class);
$method->invokeArgs($this->client, [$response]);
}
public function testNotFound() public function testNotFound()
{ {
$this->expectException(\GuzzleHttp\Exception\RequestException::class); $this->expectException(ResponseException::class);
$this->client->get('https://httpbin.org/status/404'); $this->client->get('https://httpbin.org/status/404');
} }
public function testServerError()
{
$this->expectException(ResponseException::class);
$this->client->get('https://httpbin.org/status/500');
}
} }

View File

@@ -0,0 +1,81 @@
<?php
use Cloudflare\API\Adapter\ResponseException;
use Cloudflare\API\Adapter\JSONException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
/**
* @SuppressWarnings(PHPMD.StaticAccess)
*/
class ResponseExceptionTest extends TestCase
{
public function testFromRequestExceptionNoResponse()
{
$reqErr = new RequestException('foo', new Request('GET', '/test'));
$respErr = ResponseException::fromRequestException($reqErr);
$this->assertInstanceOf(ResponseException::class, $respErr);
$this->assertEquals($reqErr->getMessage(), $respErr->getMessage());
$this->assertEquals(0, $respErr->getCode());
$this->assertEquals($reqErr, $respErr->getPrevious());
}
public function testFromRequestExceptionEmptyContentType()
{
$resp = new Response(404);
$reqErr = new RequestException('foo', new Request('GET', '/test'), $resp);
$respErr = ResponseException::fromRequestException($reqErr);
$this->assertInstanceOf(ResponseException::class, $respErr);
$this->assertEquals($reqErr->getMessage(), $respErr->getMessage());
$this->assertEquals(0, $respErr->getCode());
$this->assertEquals($reqErr, $respErr->getPrevious());
}
public function testFromRequestExceptionUnknownContentType()
{
$resp = new Response(404, ['Content-Type' => ['application/octet-stream']]);
$reqErr = new RequestException('foo', new Request('GET', '/test'), $resp);
$respErr = ResponseException::fromRequestException($reqErr);
$this->assertInstanceOf(ResponseException::class, $respErr);
$this->assertEquals($reqErr->getMessage(), $respErr->getMessage());
$this->assertEquals(0, $respErr->getCode());
$this->assertEquals($reqErr, $respErr->getPrevious());
}
public function testFromRequestExceptionJSONDecodeError()
{
$resp = new Response(404, ['Content-Type' => ['application/json; charset=utf-8']], '[what]');
$reqErr = new RequestException('foo', new Request('GET', '/test'), $resp);
$respErr = ResponseException::fromRequestException($reqErr);
$this->assertInstanceOf(ResponseException::class, $respErr);
$this->assertEquals($reqErr->getMessage(), $respErr->getMessage());
$this->assertEquals(0, $respErr->getCode());
$this->assertInstanceOf(JSONException::class, $respErr->getPrevious());
$this->assertEquals($reqErr, $respErr->getPrevious()->getPrevious());
}
public function testFromRequestExceptionJSONWithErrors()
{
$body = '{
"result": null,
"success": false,
"errors": [{"code":1003, "message":"This is an error"}],
"messages": []
}';
$resp = new Response(404, ['Content-Type' => ['application/json; charset=utf-8']], $body);
$reqErr = new RequestException('foo', new Request('GET', '/test'), $resp);
$respErr = ResponseException::fromRequestException($reqErr);
$this->assertInstanceOf(ResponseException::class, $respErr);
$this->assertEquals('This is an error', $respErr->getMessage());
$this->assertEquals(1003, $respErr->getCode());
$this->assertEquals($reqErr, $respErr->getPrevious());
}
}

View File

@@ -0,0 +1,22 @@
<?php
use PHPUnit\Framework\TestCase;
use Cloudflare\API\Configurations\Certificate;
class CertificateTest extends TestCase
{
public function testGetArray()
{
$certificate = new Certificate();
$certificate->setHostnames(['foo.com', '*.bar.com']);
$certificate->setRequestType(Certificate::ORIGIN_ECC);
$certificate->setRequestedValidity(365);
$certificate->setCsr('some-csr-encoded-text');
$array = $certificate->getArray();
$this->assertEquals(['foo.com', '*.bar.com'], $array['hostnames']);
$this->assertEquals('origin-ecc', $array['request_type']);
$this->assertEquals(365, $array['requested_validity']);
$this->assertEquals('some-csr-encoded-text', $array['csr']);
}
}

View File

@@ -0,0 +1,120 @@
<?php
use Cloudflare\API\Endpoints\Certificates;
class CertificatesTest extends TestCase
{
public function testListCertificates()
{
$response = $this->getPsr7JsonResponseForFixture('Endpoints/listCertificates.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('get')->willReturn($response);
$mock->expects($this->once())
->method('get')
->with(
$this->equalTo('certificates'),
$this->equalTo(
[
'zone_id' => '023e105f4ecef8ad9ca31a8372d0c353',
]
)
);
$certEndpoint = new Certificates($mock);
$result = $certEndpoint->listCertificates('023e105f4ecef8ad9ca31a8372d0c353');
$this->assertObjectHasAttribute('result', $result);
$cert = $result->result[0];
$this->assertEquals('328578533902268680212849205732770752308931942346', $cert->id);
$this->assertEquals('origin-rsa', $cert->request_type);
$this->assertEquals(5475, $cert->requested_validity);
$this->assertEquals(['example.com', '*.example.com'], $cert->hostnames);
$this->assertEquals('some-cert-data', $cert->certificate);
$this->assertEquals('some-csr-data', $cert->csr);
}
public function testGetCertificate()
{
$response = $this->getPsr7JsonResponseForFixture('Endpoints/getCertificate.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('get')->willReturn($response);
$mock->expects($this->once())
->method('get')
->with(
$this->equalTo('certificates/6666699999996666699999999966666666'),
$this->equalTo(['zone_id' => '023e105f4ecef8ad9ca31a8372d0c353']),
$this->equalTo([])
);
$certEndpoint = new Certificates($mock);
$response = $certEndpoint->getCertificate(
'6666699999996666699999999966666666',
'023e105f4ecef8ad9ca31a8372d0c353'
);
$this->assertObjectHasAttribute('result', $response);
$cert = $response->result;
$this->assertEquals('6666699999996666699999999966666666', $cert->id);
$this->assertEquals('origin-ecc', $cert->request_type);
$this->assertEquals(5475, $cert->requested_validity);
$this->assertEquals(['foo.example.com', 'bar.example.com'], $cert->hostnames);
$this->assertEquals('some-cert-data-foobar', $cert->certificate);
$this->assertEquals('some-csr-data-foobar', $cert->csr);
}
public function testRevokeCertificate()
{
$response = $this->getPsr7JsonResponseForFixture('Endpoints/getCertificate.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('delete')->willReturn($response);
$mock->expects($this->once())
->method('delete')
->with(
$this->equalTo('certificates/11112222233333444455555'),
$this->equalTo(['zone_id' => '023e105f4ecef8ad9ca31a8372d0c353']),
$this->equalTo([])
);
$certEndpoint = new Certificates($mock);
$result = $certEndpoint->revokeCertificate(
'11112222233333444455555',
'023e105f4ecef8ad9ca31a8372d0c353'
);
$this->assertTrue($result);
}
public function testCreateCertificate()
{
$certificate = new \Cloudflare\API\Configurations\Certificate();
$certificate->setHostnames(['foo.example.com', 'bar.exapmle.com']);
$certificate->setRequestType(\Cloudflare\API\Configurations\Certificate::ORIGIN_ECC);
$certificate->setRequestedValidity(365);
$certificate->setCsr('some-csr-data-barbar');
$response = $this->getPsr7JsonResponseForFixture('Endpoints/getCertificate.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('post')->willReturn($response);
$mock->expects($this->once())
->method('post')
->with(
$this->equalTo('certificates'),
$this->equalTo($certificate->getArray()),
$this->equalTo([])
);
$certEndpoint = new Certificates($mock);
$result = $certEndpoint->createCertificate($certificate);
$this->assertTrue($result);
}
}

View File

@@ -14,6 +14,8 @@ class CustomHostnamesTest extends TestCase
{ {
$response = $this->getPsr7JsonResponseForFixture('Endpoints/createCustomHostname.json'); $response = $this->getPsr7JsonResponseForFixture('Endpoints/createCustomHostname.json');
$customSsl = $this->getCustomSsl();
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock(); $mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('post')->willReturn($response); $mock->method('post')->willReturn($response);
@@ -23,15 +25,41 @@ class CustomHostnamesTest extends TestCase
$this->equalTo('zones/023e105f4ecef8ad9ca31a8372d0c353/custom_hostnames'), $this->equalTo('zones/023e105f4ecef8ad9ca31a8372d0c353/custom_hostnames'),
$this->equalTo([ $this->equalTo([
'hostname' => 'app.example.com', 'hostname' => 'app.example.com',
'custom_origin_server' => 'origin.example.com',
'ssl' => [ 'ssl' => [
'method' => 'http', 'method' => 'http',
'type' => 'dv' 'type' => 'dv',
] 'settings' => [
'http2' => 'on',
'http3' => 'on',
'min_tls_version' => '1.2',
],
'bundle_method' => 'optimal',
'custom_key' => $customSsl['key'],
'custom_certificate' => $customSsl['certificate'],
'wildcard' => true,
],
]) ])
); );
$hostname = new CustomHostnames($mock); $hostname = new CustomHostnames($mock);
$hostname->addHostname('023e105f4ecef8ad9ca31a8372d0c353', 'app.example.com', 'http', 'dv'); $sslSettings = [
'http2' => 'on',
'http3' => 'on',
'min_tls_version' => '1.2'
];
$hostname->addHostname(
'023e105f4ecef8ad9ca31a8372d0c353',
'app.example.com',
'http',
'dv',
$sslSettings,
'origin.example.com',
true,
'optimal',
$customSsl
);
$this->assertEquals('0d89c70d-ad9f-4843-b99f-6cc0252067e9', $hostname->getBody()->result->id); $this->assertEquals('0d89c70d-ad9f-4843-b99f-6cc0252067e9', $hostname->getBody()->result->id);
} }
@@ -93,6 +121,8 @@ class CustomHostnamesTest extends TestCase
{ {
$response = $this->getPsr7JsonResponseForFixture('Endpoints/updateHostname.json'); $response = $this->getPsr7JsonResponseForFixture('Endpoints/updateHostname.json');
$customSsl = $this->getCustomSsl();
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock(); $mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('patch')->willReturn($response); $mock->method('patch')->willReturn($response);
@@ -101,15 +131,45 @@ class CustomHostnamesTest extends TestCase
->with( ->with(
$this->equalTo('zones/023e105f4ecef8ad9ca31a8372d0c353/custom_hostnames/0d89c70d-ad9f-4843-b99f-6cc0252067e9'), $this->equalTo('zones/023e105f4ecef8ad9ca31a8372d0c353/custom_hostnames/0d89c70d-ad9f-4843-b99f-6cc0252067e9'),
$this->equalTo([ $this->equalTo([
'custom_origin_server' => 'origin.example.com',
'ssl' => [ 'ssl' => [
'method' => 'http', 'method' => 'http',
'type' => 'dv' 'type' => 'dv',
'settings' => [
'http2' => 'on',
'http3' => 'on',
'min_tls_version' => '1.2'
],
'bundle_method' => 'optimal',
'custom_key' => $customSsl['key'],
'custom_certificate' => $customSsl['certificate'],
'wildcard' => true,
] ]
]) ])
); );
$zones = new \Cloudflare\API\Endpoints\CustomHostnames($mock); $zones = new \Cloudflare\API\Endpoints\CustomHostnames($mock);
$result = $zones->updateHostname('023e105f4ecef8ad9ca31a8372d0c353', '0d89c70d-ad9f-4843-b99f-6cc0252067e9', 'http', 'dv'); $sslSettings = [
'http2' => 'on',
'http3' => 'on',
'min_tls_version' => '1.2'
];
$result = $zones->updateHostname(
'023e105f4ecef8ad9ca31a8372d0c353',
'0d89c70d-ad9f-4843-b99f-6cc0252067e9',
'http',
'dv',
$sslSettings,
'origin.example.com',
true,
'optimal',
[
'key' => $customSsl['key'],
'certificate' => $customSsl['certificate'],
]
);
$this->assertObjectHasAttribute('id', $result); $this->assertObjectHasAttribute('id', $result);
$this->assertObjectHasAttribute('hostname', $result); $this->assertObjectHasAttribute('hostname', $result);
@@ -135,4 +195,88 @@ class CustomHostnamesTest extends TestCase
$this->assertEquals('0d89c70d-ad9f-4843-b99f-6cc0252067e9', $result->id); $this->assertEquals('0d89c70d-ad9f-4843-b99f-6cc0252067e9', $result->id);
$this->assertEquals('0d89c70d-ad9f-4843-b99f-6cc0252067e9', $zones->getBody()->id); $this->assertEquals('0d89c70d-ad9f-4843-b99f-6cc0252067e9', $zones->getBody()->id);
} }
public function testGetHostnameFallbackOrigin()
{
$response = $this->getPsr7JsonResponseForFixture('Endpoints/getCustomHostnameFallbackOrigin.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('get')->willReturn($response);
$mock->expects($this->once())
->method('get')
->with(
$this->equalTo('zones/023e105f4ecef8ad9ca31a8372d0c353/custom_hostnames/fallback_origin')
);
$zones = new \Cloudflare\API\Endpoints\CustomHostnames($mock);
$result = $zones->getFallbackOrigin('023e105f4ecef8ad9ca31a8372d0c353');
$this->assertObjectHasAttribute('origin', $result);
$this->assertObjectHasAttribute('status', $result);
}
private function getCustomSsl(): array
{
$customKey = <<<KEY
-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDZfoCUkzkZLCzo
OFTtlXU9OYqNFx06J/GOKCwDCyfkY5RY1x6BVrVpTqf/JaU42DZmCjIiEugBg4bu
eu9/w21prIWgRKEe8mjrw83+3QSIyQrs+78rqwDptUfL+IyhYln6SBjqPQ569Y0w
x6A896PDMYPHgnWtclGwsxDNKJ2eWsH+C4UkLUeVM4BILEJ00YUjayowL/0sflTJ
yY58c9fVV27aGBJ4znreYkBojPQ0fzVZ3HJfYD+DgYUUkuzN/WohOLTNTxvzt/i2
GNxP8tZzi0E/t4KtGTsIVmROKaCXnmozQyv0VES5TNZL1nxLvVuPca9DKXwVst2o
v5czEM8fAgMBAAECggEBANgG/aIVpWYqaaRyp3CgviWE7Oh9J+um1xgzMJwJTaNd
gXDIoyUmweQKW3Vjp/uRTl8GC4uqqcUvJivj8dU+gIOw970bzcmWT7616vsV/rX6
sp524wh1vt9jzx97DfwSW3rsd8rZwHNDSO1FqxRDiOaNXO4i183iud8/zRVqHTy1
5girngsGl7ebTt3LDHDQQ86kND2nVr8xZuFaqs8Td41AsF6DGbB709wMUqoM/obO
iUtXCZ5Rrm2a78OUi0cqWsuxdhJjtOW0PBvrPTlSq+1EuQWAWV8HN1JI58YnLcLy
SKZpsu5wxWdKMgX0NCkfLjDZCAPlBaZLPPp986GHavECgYEA8hM6tIfGBnXuxBvI
y2lJG3sHGs83pnCqYg9dDrr+m3JOPQu6l9MEPEtsrOiI0Ktu/L+kV5uyBDRvB6ff
BD6BJ2CiG86UvMpKojBeAlZBLXr1SnWzIPC+3fBzkVSo1MiRs3nTNRfeblkRxC3e
LWtl96obA1GOgpifrh6ZB2RfvrcCgYEA5gFL4+oDUDcRtc1Pw+AFwPTey+3rkVU+
FHvRGeU+m6dtxXF+BYFpDs/ONfmHzsdBSwkYxta/x8rKP5uyjl9p0QSdhysrJibO
sWsoux35QxEZiyplCV2+zMK/79EhS2CuiudAidF6NxK+/g9EwXRlGDDlnFDB2epe
kyL97K4zCtkCgYEA68Bgbsq/xzD5XFG2xqr9wN6a97gQ+W5F8QQHW74vEZJLsdYH
Xa7rNBE8gFRiUd5zU4EL+yotPz0VWH5bilWZEJFirvQMFKRp9PRnyZzZEwLpeh+Q
WSc8qwZudn3dgoTmqMSfNdjODed+jvEgrFkoz/8BGcVGpdcfw8IWxIUzXZcCgYAY
/OsRx8q0XEdASR3xWdVGMVRDM4X0NB6aexkshwtWPcpfOQVH89dGFK2Cj6mBfYRK
cqKOd6Y+Pnnajz/G1/bXDnlOxhHaAz1RaSLzsT3zW1g7FlADxHuGI2JW25GSbt6H
mLgaQPfWI+M8FsyRd+PDzQwk/2EQG7ZKpfKQVByXgQKBgQDkKciB6Wb2hLNTKzK8
Kr42U70H++QT8AqZX2F79PjgYcRFZqGXLuq/hEuiOhXfl8DFur3fC5JN8AeLC5/j
bsrBsljYfVvtLQzilugs1oEe94LTrYjR2oQt0W24bqpGQHuv1ILuUBuodERkxSFL
/cMkj3wSfC341hFaJEuG1+PcxA==
-----END PRIVATE KEY-----
KEY;
$customCertificate = <<<CERTIFICATE
-----BEGIN CERTIFICATE-----
MIIDmTCCAoGgAwIBAgIULyaeNqp0tOut/wvuxNyKmUxOGYEwDQYJKoZIhvcNAQEL
BQAwXDELMAkGA1UEBhMCWFgxFTATBgNVBAcMDERlZmF1bHQgQ2l0eTEcMBoGA1UE
CgwTRGVmYXVsdCBDb21wYW55IEx0ZDEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29t
MB4XDTIxMDYxNDIzMzU0MVoXDTIyMDYxNDIzMzU0MVowXDELMAkGA1UEBhMCWFgx
FTATBgNVBAcMDERlZmF1bHQgQ2l0eTEcMBoGA1UECgwTRGVmYXVsdCBDb21wYW55
IEx0ZDEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEA2X6AlJM5GSws6DhU7ZV1PTmKjRcdOifxjigsAwsn5GOU
WNcegVa1aU6n/yWlONg2ZgoyIhLoAYOG7nrvf8NtaayFoEShHvJo68PN/t0EiMkK
7Pu/K6sA6bVHy/iMoWJZ+kgY6j0OevWNMMegPPejwzGDx4J1rXJRsLMQzSidnlrB
/guFJC1HlTOASCxCdNGFI2sqMC/9LH5UycmOfHPX1Vdu2hgSeM563mJAaIz0NH81
WdxyX2A/g4GFFJLszf1qITi0zU8b87f4thjcT/LWc4tBP7eCrRk7CFZkTimgl55q
M0Mr9FREuUzWS9Z8S71bj3GvQyl8FbLdqL+XMxDPHwIDAQABo1MwUTAdBgNVHQ4E
FgQUbAfyBm0wpM7FqUb1yqeaF4voY/gwHwYDVR0jBBgwFoAUbAfyBm0wpM7FqUb1
yqeaF4voY/gwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAO2Dd
k/seFjp83caYE/NVdDy5B7l5JeVtruaUdlGbb0xtVhiIdoY43ukhHFw8zuWMW9RX
SUbrzwacfKLDBikcefk9go6cMimqYIRF8Hntph1gjjqB0papUm2WVYbsBRv2okys
ej0dGSeUEsWjKRTSMkJsbbiEv6oveeSki069zl+tln0UhbHedkIY3rJsFIyoddSu
g96r5HPHksnObm1JCym0xd09+msliDkBmq87mxok9m5aEqWX4XvdGfYERV/eD5vC
KcW4DoM1KZd8E6tlniglc1jC0pzKfho7Uoe6UtObgHZGNwRYwYy+BHvHYY46ctSI
NdZ7G/lUyrBFhsRrhw==
-----END CERTIFICATE-----
CERTIFICATE;
return [
'key' => $customKey,
'certificate' => $customCertificate,
];
}
} }

View File

@@ -0,0 +1,91 @@
<?php
/**
* Created by Visual Studio Code.
* User: elliot.alderson
* Date: 10/02/2020
* Time: 04:28 AM
*/
class DNSAnalyticsTest extends TestCase
{
public function testGetDNSAnalyticsReportTable()
{
$response = $this->getPsr7JsonResponseForFixture(
'Endpoints/getDNSAnalyticsReportTable.json'
);
$mock = $this->getMockBuilder(
\Cloudflare\API\Adapter\Adapter::class
)->getMock();
$mock->method('get')->willReturn($response);
$mock
->expects($this->once())
->method('get')
->with(
$this->equalTo(
'zones/023e105f4ecef8ad9ca31a8372d0c353/dns_analytics/report'
)
);
$analytics = new \Cloudflare\API\Endpoints\DNSAnalytics($mock);
$since = '2020-02-01T00:00:00Z';
$until = '2020-02-28T23:59:59Z';
$filters = 'responseCode==NOERROR AND queryType==A';
$result = $analytics->getReportTable(
'023e105f4ecef8ad9ca31a8372d0c353',
['queryName', 'queryType', 'responseCode'],
['queryCount'],
['-queryCount'],
$filters,
$since,
$until
);
$this->assertEquals(1, $result->rows);
$this->assertEquals($since, $result->query->since);
$this->assertEquals($until, $result->query->until);
}
public function testGetDNSAnalyticsReportByTime()
{
$response = $this->getPsr7JsonResponseForFixture(
'Endpoints/getDNSAnalyticsReportByTime.json'
);
$mock = $this->getMockBuilder(
\Cloudflare\API\Adapter\Adapter::class
)->getMock();
$mock->method('get')->willReturn($response);
$mock
->expects($this->once())
->method('get')
->with(
$this->equalTo(
'zones/023e105f4ecef8ad9ca31a8372d0c353/dns_analytics/report/bytime'
)
);
$analytics = new \Cloudflare\API\Endpoints\DNSAnalytics($mock);
$since = '2020-02-01T00:00:00Z';
$until = '2020-02-28T23:59:59Z';
$filters = 'responseCode==NOERROR AND queryType==A';
$result = $analytics->getReportByTime(
'023e105f4ecef8ad9ca31a8372d0c353',
['queryName', 'queryType', 'responseCode'],
['queryCount'],
['-queryCount'],
$filters,
$since,
$until,
2
);
$this->assertEquals(2, $result->rows);
$this->assertEquals($since, $result->query->since);
$this->assertEquals($until, $result->query->until);
}
}

View File

@@ -32,6 +32,57 @@ class DNSTest extends TestCase
$dns->addRecord('023e105f4ecef8ad9ca31a8372d0c353', 'A', 'example.com', '127.0.0.1', '120', false); $dns->addRecord('023e105f4ecef8ad9ca31a8372d0c353', 'A', 'example.com', '127.0.0.1', '120', false);
} }
public function testAddMXRecordPriority10()
{
$response = $this->getPsr7JsonResponseForFixture('Endpoints/addRecord.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('post')->willReturn($response);
$mock->expects($this->once())
->method('post')
->with(
$this->equalTo('zones/023e105f4ecef8ad9ca31a8372d0c353/dns_records'),
$this->equalTo([
'type' => 'MX',
'name' => 'example.com',
'content' => '127.0.0.1',
'ttl' => 120,
'proxied' => false,
'priority' => 10,
])
);
$dns = new \Cloudflare\API\Endpoints\DNS($mock);
$dns->addRecord('023e105f4ecef8ad9ca31a8372d0c353', 'MX', 'example.com', '127.0.0.1', '120', false, 10);
}
public function testAddMXRecordPriority0()
{
$response = $this->getPsr7JsonResponseForFixture('Endpoints/addRecord.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('post')->willReturn($response);
$mock->expects($this->once())
->method('post')
->with(
$this->equalTo('zones/023e105f4ecef8ad9ca31a8372d0c353/dns_records'),
$this->equalTo([
'type' => 'MX',
'name' => 'example.com',
'content' => '127.0.0.1',
'ttl' => 120,
'proxied' => false,
'priority' => 0,
])
);
$dns = new \Cloudflare\API\Endpoints\DNS($mock);
$dns->addRecord('023e105f4ecef8ad9ca31a8372d0c353', 'MX', 'example.com', '127.0.0.1', '120', false, 0);
}
public function testListRecords() public function testListRecords()
{ {
$response = $this->getPsr7JsonResponseForFixture('Endpoints/listRecords.json'); $response = $this->getPsr7JsonResponseForFixture('Endpoints/listRecords.json');

View File

@@ -36,4 +36,34 @@ class ZoneSettingsTest extends TestCase
$this->assertSame('on', $result); $this->assertSame('on', $result);
} }
public function testGetBrowserCacheTtlSetting()
{
$response = $this->getPsr7JsonResponseForFixture('Endpoints/getBrowserCacheTtlSetting.json');
$mock = $this->getMockBuilder(Adapter::class)->getMock();
$mock->method('get')->willReturn($response);
$mock->expects($this->once())->method('get');
$zones = new ZoneSettings($mock);
$result = $zones->getBrowserCacheTtlSetting('023e105f4ecef8ad9ca31a8372d0c353');
$this->assertSame(14400, $result);
}
public function testUpdateBrowserCacheTtlSetting()
{
$response = $this->getPsr7JsonResponseForFixture('Endpoints/updateBrowserCacheTtlSetting.json');
$mock = $this->getMockBuilder(Adapter::class)->getMock();
$mock->method('patch')->willReturn($response);
$mock->expects($this->once())->method('patch');
$zones = new ZoneSettings($mock);
$result = $zones->updateBrowserCacheTtlSetting('023e105f4ecef8ad9ca31a8372d0c353', 16070400);
$this->assertTrue($result);
}
} }

View File

@@ -194,10 +194,10 @@ class ZonesTest extends TestCase
$response = $this->getPsr7JsonResponseForFixture('Endpoints/cachePurgeEverything.json'); $response = $this->getPsr7JsonResponseForFixture('Endpoints/cachePurgeEverything.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock(); $mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('delete')->willReturn($response); $mock->method('post')->willReturn($response);
$mock->expects($this->once()) $mock->expects($this->once())
->method('delete') ->method('post')
->with( ->with(
$this->equalTo('zones/c2547eb745079dac9320b638f5e225cf483cc5cfdda41/purge_cache'), $this->equalTo('zones/c2547eb745079dac9320b638f5e225cf483cc5cfdda41/purge_cache'),
$this->equalTo(['purge_everything' => true]) $this->equalTo(['purge_everything' => true])
@@ -215,10 +215,10 @@ class ZonesTest extends TestCase
$response = $this->getPsr7JsonResponseForFixture('Endpoints/cachePurgeHost.json'); $response = $this->getPsr7JsonResponseForFixture('Endpoints/cachePurgeHost.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock(); $mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('delete')->willReturn($response); $mock->method('post')->willReturn($response);
$mock->expects($this->once()) $mock->expects($this->once())
->method('delete') ->method('post')
->with( ->with(
$this->equalTo('zones/c2547eb745079dac9320b638f5e225cf483cc5cfdda41/purge_cache'), $this->equalTo('zones/c2547eb745079dac9320b638f5e225cf483cc5cfdda41/purge_cache'),
$this->equalTo( $this->equalTo(
@@ -242,10 +242,10 @@ class ZonesTest extends TestCase
$response = $this->getPsr7JsonResponseForFixture('Endpoints/cachePurge.json'); $response = $this->getPsr7JsonResponseForFixture('Endpoints/cachePurge.json');
$mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock(); $mock = $this->getMockBuilder(\Cloudflare\API\Adapter\Adapter::class)->getMock();
$mock->method('delete')->willReturn($response); $mock->method('post')->willReturn($response);
$mock->expects($this->once()) $mock->expects($this->once())
->method('delete') ->method('post')
->with( ->with(
$this->equalTo('zones/c2547eb745079dac9320b638f5e225cf483cc5cfdda41/purge_cache'), $this->equalTo('zones/c2547eb745079dac9320b638f5e225cf483cc5cfdda41/purge_cache'),
$this->equalTo(['files' => [ $this->equalTo(['files' => [

View File

@@ -0,0 +1,17 @@
{
"success": true,
"errors": [],
"messages": [],
"result": {
"id": "12341234123412341234",
"certificate": "some-cert-data-foofoo",
"hostnames": [
"foo.example.com",
"bar.example.com"
],
"expires_on": "2014-01-01T05:20:00.12345Z",
"request_type": "origin-ecc",
"requested_validity": 365,
"csr": "some-csr-data-barbar"
}
}

View File

@@ -0,0 +1,11 @@
{
"success": true,
"errors": [],
"messages": [],
"result": {
"id": "browser_cache_ttl",
"value": 14400,
"editable": true,
"modified_on": "2014-01-01T05:20:00.12345Z"
}
}

View File

@@ -0,0 +1,17 @@
{
"success": true,
"errors": [],
"messages": [],
"result": {
"id": "6666699999996666699999999966666666",
"certificate": "some-cert-data-foobar",
"hostnames": [
"foo.example.com",
"bar.example.com"
],
"expires_on": "2014-01-01T05:20:00.12345Z",
"request_type": "origin-ecc",
"requested_validity": 5475,
"csr": "some-csr-data-foobar"
}
}

View File

@@ -0,0 +1,18 @@
{
"success": true,
"errors": [
{}
],
"messages": [
{}
],
"result": {
"origin": "fallback.example.com",
"status": "pending_deployment",
"errors": [
"DNS records are not setup correctly. Origin should be a proxied A/AAAA/CNAME dns record"
],
"created_at": "2019-10-28T18:11:23.37411Z",
"updated_at": "2020-03-16T18:11:23.531995Z"
}
}

View File

@@ -0,0 +1,31 @@
{
"result": {
"rows": 2,
"data": [
{
"metrics": [[911, 993]]
}
],
"data_lag": 0,
"min": {},
"max": {},
"totals": {
"queryCount": 455312
},
"time_intervals": [
["2020-02-10T11:19:00Z", "2020-02-10T11:19:59Z"],
["2020-02-10T11:20:00Z", "2020-02-10T11:20:59Z"]
],
"query": {
"dimensions": [],
"metrics": ["queryCount"],
"since": "2020-02-01T00:00:00Z",
"until": "2020-02-28T23:59:59Z",
"time_delta": "minute",
"limit": 2
}
},
"success": true,
"errors": [],
"messages": []
}

View File

@@ -0,0 +1,34 @@
{
"result": {
"rows": 1,
"data": [
{
"dimensions": ["thrdld.sld.tld", "TXT", "NOERROR"],
"metrics": [2]
}
],
"data_lag": 0,
"min": {},
"max": {},
"totals": {
"queryCount": 2
},
"query": {
"dimensions": ["queryName", "queryType", "responseCode"],
"metrics": ["queryCount"],
"filters": "responseCode==NOERROR AND queryType==TXT",
"sort": [
{
"Id": "queryCount",
"Desc": true
}
],
"since": "2020-02-01T00:00:00Z",
"until": "2020-02-28T23:59:59Z",
"limit": 10000
}
},
"success": true,
"errors": [],
"messages": []
}

View File

@@ -0,0 +1,19 @@
{
"success": true,
"errors": [],
"messages": [],
"result": [
{
"id": "328578533902268680212849205732770752308931942346",
"certificate": "some-cert-data",
"hostnames": [
"example.com",
"*.example.com"
],
"expires_on": "2014-01-01T05:20:00.12345Z",
"request_type": "origin-rsa",
"requested_validity": 5475,
"csr": "some-csr-data"
}
]
}

View File

@@ -0,0 +1,8 @@
{
"success": true,
"errors": [],
"messages": [],
"result": {
"id": "11112222233333444455555"
}
}

View File

@@ -0,0 +1,11 @@
{
"success": true,
"errors": [],
"messages": [],
"result": {
"id": "browser_cache_ttl",
"value": 14400,
"editable": true,
"modified_on": "2014-01-01T05:20:00.12345Z"
}
}