From cc98a778e47e631a0aefd1df3048c914ccc78d06 Mon Sep 17 00:00:00 2001 From: Daniel Paul Carbone Date: Tue, 28 Mar 2017 10:06:53 -0500 Subject: [PATCH] Major overhaul - Objects and arrays are now "null" by default - No longer attempting to create Query or WriteMeta objects on error - Lots of fixes in PSR-7 objects - Minor documentation updates --- src/ACL/ACLClient.php | 40 ++-- src/AbstractCollection.php | 6 +- src/AbstractModel.php | 2 +- src/AbstractOptions.php | 4 +- src/Agent/AgentClient.php | 72 +------ src/Agent/AgentSelf.php | 8 +- src/Agent/AgentSelfConfig.php | 10 +- src/Agent/AgentSelfCoord.php | 2 +- src/Agent/AgentServiceRegistration.php | 21 +- src/Catalog/CatalogClient.php | 38 ++-- src/Catalog/CatalogRegistration.php | 6 +- src/Catalog/CatalogService.php | 2 +- src/Config.php | 4 +- src/ConsulHttpParamContainerTrait.php | 2 +- src/Coordinate/Coordinate.php | 2 +- src/Coordinate/CoordinateClient.php | 10 +- src/Coordinate/CoordinateDatacenterMap.php | 23 ++- src/Coordinate/CoordinateEntry.php | 6 +- src/Event/EventClient.php | 23 ++- src/Event/UserEvent.php | 2 +- src/FileDebugLogger.php | 2 +- src/HasStringTags.php | 2 +- src/Health/HealthClient.php | 32 +-- src/Health/ServiceEntry.php | 24 ++- src/KV/KVClient.php | 50 ++--- src/KV/KVPair.php | 2 +- src/KV/KVTree.php | 4 +- src/Logger.php | 26 +-- src/Operator/OperatorClient.php | 8 +- src/Operator/RaftConfiguration.php | 15 +- src/PreparedQuery/PreparedQueryClient.php | 51 ++--- src/PreparedQuery/PreparedQueryDefinition.php | 8 +- .../PreparedQueryExecuteResponse.php | 18 +- src/PreparedQuery/ServiceQuery.php | 4 +- src/Request.php | 160 ++++++++------- src/RequestBody.php | 194 ++++++++---------- src/Session/SessionClient.php | 45 ++-- src/Session/SessionEntry.php | 2 +- src/Uri.php | 146 +++++++------ .../AbstractDefinitionTestCases.php | 16 +- 40 files changed, 555 insertions(+), 537 deletions(-) diff --git a/src/ACL/ACLClient.php b/src/ACL/ACLClient.php index ab96923..c72d4bb 100644 --- a/src/ACL/ACLClient.php +++ b/src/ACL/ACLClient.php @@ -43,14 +43,16 @@ public function create(ACLEntry $acl, WriteOptions $writeOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); - if (null !== $err) - return [null, $wm, $err]; + return [null, $err]; + + $wm = $this->buildWriteMeta($duration); list($data, $err) = $this->decodeBody($response->getBody()); + if (null !== $err) + return ['', $wm, $err]; - return [$data, $wm, $err]; + return [$data, $wm, null]; } /** @@ -68,7 +70,10 @@ public function update(ACLEntry $acl, WriteOptions $writeOptions = null) list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - return [$this->buildWriteMeta($duration), $err]; + if (null !== $err) + return [null, $err]; + + return [$this->buildWriteMeta($duration), null]; } /** @@ -86,7 +91,10 @@ public function destroy($id, WriteOptions $writeOptions = null) list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - return [$this->buildWriteMeta($duration), $err]; + if (null !== $err) + return [null, $err]; + + return [$this->buildWriteMeta($duration), null]; } /** @@ -105,14 +113,16 @@ public function cloneACL($id, WriteOptions $writeOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); - if (null !== $err) - return [null, $wm, $err]; + return [null, null, $err]; + + $wm = $this->buildWriteMeta($duration); list($data, $err) = $this->decodeBody($response->getBody()); + if (null !== $err) + return ['', $wm, $err]; - return [$data, $wm, $err]; + return [$data, $wm, null]; } /** @@ -131,9 +141,10 @@ public function info($id, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) @@ -163,10 +174,11 @@ public function listACLs(QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); + if (null !== $err) + return [null, null, $err]; + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) diff --git a/src/AbstractCollection.php b/src/AbstractCollection.php index 4b5dc26..5b50caa 100644 --- a/src/AbstractCollection.php +++ b/src/AbstractCollection.php @@ -25,13 +25,13 @@ abstract class AbstractCollection implements \JsonSerializable, \ArrayAccess, \Iterator, \Countable { /** @var array */ - protected $_storage = array(); + protected $_storage = []; /** * AbstractResponseModel constructor. * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { foreach($data as $k => $v) { @@ -227,7 +227,7 @@ protected function _triggerOutOfBoundsError($key, $level = E_USER_NOTICE) */ protected function _findKeyMatches($key) { - $possibleMatches = array(); + $possibleMatches = []; if (is_string($key)) { $regex = sprintf('{^.*%s.*$}i', substr($key, 0, 2)); diff --git a/src/AbstractModel.php b/src/AbstractModel.php index 0331400..015bb19 100644 --- a/src/AbstractModel.php +++ b/src/AbstractModel.php @@ -30,7 +30,7 @@ abstract class AbstractModel implements \JsonSerializable * * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { foreach($data as $k => $v) { diff --git a/src/AbstractOptions.php b/src/AbstractOptions.php index d3ea544..358532f 100644 --- a/src/AbstractOptions.php +++ b/src/AbstractOptions.php @@ -23,13 +23,13 @@ abstract class AbstractOptions extends AbstractCollection { /** @var array */ - protected $_definition = array(); + protected $_definition = []; /** * AbstractConsulConfig constructor. * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { $this->_definition = $this->getDefinition(); parent::__construct($data + $this->_definition); diff --git a/src/Agent/AgentClient.php b/src/Agent/AgentClient.php index 48a84e9..ec64781 100644 --- a/src/Agent/AgentClient.php +++ b/src/Agent/AgentClient.php @@ -41,10 +41,10 @@ public function self() /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); @@ -95,7 +95,7 @@ public function checks() if (null !== $err) return [null, $err]; - $checks = array(); + $checks = []; foreach($data as $k => $v) { $checks[$k] = new AgentCheck($v); @@ -125,7 +125,7 @@ public function services() if (null !== $err) return [null, $err]; - $services = array(); + $services = []; foreach($data as $k => $v) { $services[$k] = new AgentService($v); @@ -155,7 +155,7 @@ public function members() if (null !== $err) return [null, $err]; - $members = array(); + $members = []; foreach($data as $v) { $members[] = new AgentMember($v); @@ -172,8 +172,7 @@ public function members() */ public function serviceRegister(AgentServiceRegistration $agentServiceRegistration) { - $r = new Request('put', 'v1/agent/service/register', $this->c); - $r->body = ($agentServiceRegistration); + $r = new Request('put', 'v1/agent/service/register', $this->c, $agentServiceRegistration); list($_, $_, $err) = $this->requireOK($this->doRequest($r)); @@ -241,8 +240,7 @@ public function failTTL($checkID, $note) */ public function updateTTL($checkID, $output, $status) { - $r = new Request('put', sprintf('v1/agent/check/update/%s', $checkID), $this->c); - $r->body = (new AgentCheckUpdate(['Output' => $output, 'Status' => $status])); + $r = new Request('put', sprintf('v1/agent/check/update/%s', $checkID), $this->c, new AgentCheckUpdate(['Output' => $output, 'Status' => $status])); list($_, $_, $err) = $this->requireOK($this->doRequest($r)); @@ -255,8 +253,7 @@ public function updateTTL($checkID, $output, $status) */ public function checkRegister(AgentCheckRegistration $agentCheckRegistration) { - $r = new Request('put', 'v1/agent/check/register', $this->c); - $r->body = ($agentCheckRegistration); + $r = new Request('put', 'v1/agent/check/register', $this->c, $agentCheckRegistration); list($_, $_, $err) = $this->requireOK($this->doRequest($r)); @@ -363,57 +360,6 @@ public function disableNodeMaintenance() return $err; } - /** - * Set non-ttl check's state to passing with optional note - * - * @param string $checkID - * @param string $note - * @return \DCarbone\PHPConsulAPI\Error|null - */ - public function checkPass($checkID, $note = '') - { - $r = new Request('get', sprintf('v1/agent/check/pass/%s', $checkID), $this->c); - $r->params->set('note', $note); - - list($_, $_, $err) = $this->requireOK($this->doRequest($r)); - - return $err; - } - - /** - * Set non-ttl check's state to warning with optional note - * - * @param string $checkID - * @param string $note - * @return \DCarbone\PHPConsulAPI\Error|null - */ - public function checkWarn($checkID, $note = '') - { - $r = new Request('get', sprintf('v1/agent/check/warn/%s', $checkID), $this->c); - $r->params->set('note', $note); - - list($_, $_, $err) = $this->requireOK($this->doRequest($r)); - - return $err; - } - - /** - * Set non-ttl check's state to critical with optional note - * - * @param string $checkID - * @param string $note - * @return \DCarbone\PHPConsulAPI\Error|null - */ - public function checkFail($checkID, $note = '') - { - $r = new Request('get', sprintf('v1/agent/check/fail/%s', $checkID), $this->c); - $r->params->set('note', $note); - - list($_, $_, $err) = $this->requireOK($this->doRequest($r)); - - return $err; - } - /** * @return \DCarbone\PHPConsulAPI\Error|null */ diff --git a/src/Agent/AgentSelf.php b/src/Agent/AgentSelf.php index ee9f917..d19e363 100644 --- a/src/Agent/AgentSelf.php +++ b/src/Agent/AgentSelf.php @@ -35,14 +35,14 @@ class AgentSelf extends AbstractModel * AgentSelf constructor. * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - if (!($this->Config instanceof AgentSelfConfig)) + if (null !== $this->Config && !($this->Config instanceof AgentSelfConfig)) $this->Config = new AgentSelfConfig((array)$this->Config); - if (!($this->Coord instanceof AgentSelfCoord)) + if (null !== $this->Coord && !($this->Coord instanceof AgentSelfCoord)) $this->Coord = new AgentSelfCoord((array)$this->Coord); - if (!($this->Member instanceof AgentMember)) + if (null !== $this->Member && !($this->Member instanceof AgentMember)) $this->Member = new AgentMember((array)$this->Member); } diff --git a/src/Agent/AgentSelfConfig.php b/src/Agent/AgentSelfConfig.php index 2aad6d6..7f9682a 100644 --- a/src/Agent/AgentSelfConfig.php +++ b/src/Agent/AgentSelfConfig.php @@ -39,9 +39,9 @@ class AgentSelfConfig extends AbstractModel /** @var string */ public $DNSRecursor = ''; /** @var string[] */ - public $DNSRecursors = array(); + public $DNSRecursors = []; /** @var string[] */ - public $DNSConfig = array(); + public $DNSConfig = []; /** @var string */ public $Domain = ''; /** @var string */ @@ -55,13 +55,13 @@ class AgentSelfConfig extends AbstractModel /** @var string */ public $AdvertiseAddr = ''; /** @var string[] */ - public $Ports = array(); + public $Ports = []; /** @var bool */ public $LeaveOnTerm = false; /** @var bool */ public $SkipLeaveOnInt = false; /** @var string[] */ - public $Telemetry = array(); + public $Telemetry = []; /** @var int */ public $Protocol = 0; /** @var bool */ @@ -77,7 +77,7 @@ class AgentSelfConfig extends AbstractModel /** @var string */ public $KeyFile = ''; /** @var string[] */ - public $StartJoin = array(); + public $StartJoin = []; /** @var string */ public $UiDir = ''; /** @var string */ diff --git a/src/Agent/AgentSelfCoord.php b/src/Agent/AgentSelfCoord.php index 144ef3a..01829a1 100644 --- a/src/Agent/AgentSelfCoord.php +++ b/src/Agent/AgentSelfCoord.php @@ -25,7 +25,7 @@ class AgentSelfCoord extends AbstractModel { /** @var array */ - public $Vec = array(); + public $Vec = []; /** @var float */ public $Error = 0.0; /** @var float */ diff --git a/src/Agent/AgentServiceRegistration.php b/src/Agent/AgentServiceRegistration.php index 0307e5e..9d6a931 100644 --- a/src/Agent/AgentServiceRegistration.php +++ b/src/Agent/AgentServiceRegistration.php @@ -41,25 +41,30 @@ class AgentServiceRegistration extends AbstractModel /** @var \DCarbone\PHPConsulAPI\Agent\AgentCheck */ public $Check = null; /** @var \DCarbone\PHPConsulAPI\Agent\AgentCheck[] */ - public $Checks = array(); + public $Checks = []; /** * AgentServiceRegistration constructor. * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - if (!($this->Check instanceof AgentCheck)) + if (null !== $this->Check && !($this->Check instanceof AgentCheck)) $this->Check = new AgentCheck((array)$this->Check); - for ($i = 0, $cnt = count($this->Checks); $i < $cnt; $i++) + if (0 < count($this->Checks)) { - if ($this->Checks[$i] instanceof AgentCheck) - continue; - - $this->Checks[$i] = new AgentCheck($this->Checks[$i]); + $this->Checks = array_filter($this->Checks); + if (0 < ($cnt = count($this->Checks))) + { + for ($i = 0, $cnt = count($this->Checks); $i < $cnt; $i++) + { + if (!($this->Checks[$i] instanceof AgentCheck)) + $this->Checks[$i] = new AgentCheck($this->Checks[$i]); + } + } } } diff --git a/src/Catalog/CatalogClient.php b/src/Catalog/CatalogClient.php index cc6c106..792376f 100644 --- a/src/Catalog/CatalogClient.php +++ b/src/Catalog/CatalogClient.php @@ -41,9 +41,10 @@ public function register(CatalogRegistration $catalogRegistration, WriteOptions $r->setWriteOptions($writeOptions); list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); + if (null !== $err) + return [null, $err]; - return [$wm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** @@ -60,9 +61,10 @@ public function deregister(CatalogDeregistration $catalogDeregistration, WriteOp $r->setWriteOptions($writeOptions); list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); + if (null !== $err) + return [null, $err]; - return [$wm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** @@ -99,17 +101,17 @@ public function nodes(QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - $nodes = array(); + $nodes = []; foreach($data as $v) { $node = new CatalogNode($v); @@ -134,10 +136,10 @@ public function services(QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); @@ -163,17 +165,17 @@ public function service($service, $tag = '', QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); + if (null !== $err) + return [null, null, $err]; + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; - list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - $services = array(); + $services = []; foreach($data as $v) { $service = new CatalogService($v); @@ -199,10 +201,10 @@ public function node($node, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); diff --git a/src/Catalog/CatalogRegistration.php b/src/Catalog/CatalogRegistration.php index cef8fb3..25af943 100644 --- a/src/Catalog/CatalogRegistration.php +++ b/src/Catalog/CatalogRegistration.php @@ -42,12 +42,12 @@ class CatalogRegistration extends AbstractModel * * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - if (!($this->Service instanceof AgentService)) + if (null !== $this->Service && !($this->Service instanceof AgentService)) $this->Service = new AgentService((array)$this->Service); - if (!($this->Check instanceof AgentCheck)) + if (null !== $this->Check && !($this->Check instanceof AgentCheck)) $this->Check = new AgentCheck((array)$this->Check); } diff --git a/src/Catalog/CatalogService.php b/src/Catalog/CatalogService.php index abfeef9..1b7fdee 100644 --- a/src/Catalog/CatalogService.php +++ b/src/Catalog/CatalogService.php @@ -29,7 +29,7 @@ class CatalogService extends CatalogNode /** @var string */ public $ServiceAddress = ''; /** @var string[] */ - public $ServiceTags = array(); + public $ServiceTags = []; /** @var int */ public $ServicePort = 0; /** @var bool */ diff --git a/src/Config.php b/src/Config.php index 315cfe6..a873135 100644 --- a/src/Config.php +++ b/src/Config.php @@ -93,14 +93,14 @@ class Config * Config constructor. * @param array $config */ - public function __construct(array $config = array()) + public function __construct(array $config = []) { foreach($config as $k => $v) { $this->{"set{$k}"}($v); } - if (!isset($this->HttpAuth)) + if (null !== $this->HttpAuth && !isset($this->HttpAuth)) $this->HttpAuth = new HttpAuth(); } diff --git a/src/ConsulHttpParamContainerTrait.php b/src/ConsulHttpParamContainerTrait.php index 59d1839..e193fd9 100644 --- a/src/ConsulHttpParamContainerTrait.php +++ b/src/ConsulHttpParamContainerTrait.php @@ -27,7 +27,7 @@ trait ConsulHttpParamContainerTrait */ public function buildHttpQueryArray() { - $params = array(); + $params = []; foreach($this as $k => $v) { if (null !== $v) diff --git a/src/Coordinate/Coordinate.php b/src/Coordinate/Coordinate.php index a779ad3..6436228 100644 --- a/src/Coordinate/Coordinate.php +++ b/src/Coordinate/Coordinate.php @@ -25,7 +25,7 @@ class Coordinate extends AbstractModel { /** @var int[] */ - public $Vec = array(); + public $Vec = []; /** @var float */ public $Error = 0.0; /** @var float */ diff --git a/src/Coordinate/CoordinateClient.php b/src/Coordinate/CoordinateClient.php index 02210dd..178de0b 100644 --- a/src/Coordinate/CoordinateClient.php +++ b/src/Coordinate/CoordinateClient.php @@ -47,7 +47,7 @@ public function datacenters() if (null !== $err) return [null, $err]; - $datacenters = array(); + $datacenters = []; foreach($data as $v) { $datacenters[] = new CoordinateDatacenterMap($v); @@ -71,16 +71,16 @@ public function nodes(QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list ($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - $coordinates = array(); + $coordinates = []; foreach($data as $coord) { $coordinates[] = new CoordinateEntry($coord); diff --git a/src/Coordinate/CoordinateDatacenterMap.php b/src/Coordinate/CoordinateDatacenterMap.php index 405327d..b8a1b0d 100644 --- a/src/Coordinate/CoordinateDatacenterMap.php +++ b/src/Coordinate/CoordinateDatacenterMap.php @@ -27,20 +27,33 @@ class CoordinateDatacenterMap extends AbstractModel /** @var string */ public $Datacenter = ''; /** @var Coordinate[] */ - public $Coordinates = array(); + public $Coordinates = []; /** * CoordinateDatacenterMap constructor. * * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - for ($i = 0, $cnt = count($this->Coordinates); $i < $cnt; $i++) + + // If we have data... + if (0 < count($this->Coordinates)) { - if (!($this->Coordinates[$i] instanceof Coordinate)) - $this->Coordinates[$i] = new Coordinate((array)$this->Coordinates[$i]); + // ...remove null + $this->Coordinates = array_filter($this->Coordinates); + + // ...and if we still have data + if (0 < ($cnt = count($this->Coordinates))) + { + // ensure we have objects. + for ($i = 0; $i < $cnt; $i++) + { + if (!($this->Coordinates[$i] instanceof Coordinate)) + $this->Coordinates[$i] = new Coordinate((array)$this->Coordinates[$i]); + } + } } } diff --git a/src/Coordinate/CoordinateEntry.php b/src/Coordinate/CoordinateEntry.php index a3a385b..6c078d2 100644 --- a/src/Coordinate/CoordinateEntry.php +++ b/src/Coordinate/CoordinateEntry.php @@ -33,10 +33,12 @@ class CoordinateEntry extends AbstractModel * CoordinateEntry constructor. * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - $this->Coord = new Coordinate((array)$this->Coord); + + if (null !== $this->Coord && !($this->Coord instanceof Coordinate)) + $this->Coord = new Coordinate((array)$this->Coord); } /** diff --git a/src/Event/EventClient.php b/src/Event/EventClient.php index d5d000b..e2c6583 100644 --- a/src/Event/EventClient.php +++ b/src/Event/EventClient.php @@ -38,7 +38,12 @@ class EventClient extends AbstractClient */ public function fire(UserEvent $event, WriteOptions $writeOptions = null) { - $r = new Request('put', sprintf('v1/event/fire/%s', $event->Name), $this->c); + $r = new Request( + 'put', + sprintf('v1/event/fire/%s', $event->Name), + $this->c, + '' !== $event->Payload ? $event->Payload : null); + $r->setWriteOptions($writeOptions); if ('' !== ($nf = $event->NodeFilter)) @@ -47,15 +52,13 @@ public function fire(UserEvent $event, WriteOptions $writeOptions = null) $r->params->set('service', $sf); if ('' !== ($tf = $event->TagFilter)) $r->params->set('tag', $tf); - if ('' !== ($payload = $event->Payload)) - $r->body = $payload; /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); - if (null !== $err) - return [null, $wm, $err]; + return [null, null, $err]; + + $wm = $this->buildWriteMeta($duration); list($data, $err) = $this->decodeBody($response->getBody()); if ($err !== null) @@ -82,17 +85,17 @@ public function eventList($name = '', QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - $events = array(); + $events = []; foreach($data as $event) { $events[] = new UserEvent($event); diff --git a/src/Event/UserEvent.php b/src/Event/UserEvent.php index 9d29219..23a6086 100644 --- a/src/Event/UserEvent.php +++ b/src/Event/UserEvent.php @@ -48,7 +48,7 @@ class UserEvent extends AbstractModel * @param array $data * @param bool $_decodeValue */ - public function __construct(array $data = array(), $_decodeValue = false) + public function __construct(array $data = [], $_decodeValue = false) { parent::__construct($data); if ((bool)$_decodeValue && isset($this->Payload)) diff --git a/src/FileDebugLogger.php b/src/FileDebugLogger.php index 2f42ae9..47de892 100644 --- a/src/FileDebugLogger.php +++ b/src/FileDebugLogger.php @@ -62,7 +62,7 @@ public function __construct($exceptionOnError = true) * * @return null */ - public function log($level, $message, array $context = array()) + public function log($level, $message, array $context = []) { if (file_exists($this->_file) && is_writable($this->_file)) { diff --git a/src/HasStringTags.php b/src/HasStringTags.php index d5ea261..10c51e2 100644 --- a/src/HasStringTags.php +++ b/src/HasStringTags.php @@ -23,7 +23,7 @@ trait HasStringTags { /** @var string[] */ - public $Tags = array(); + public $Tags = []; /** * @return string[] diff --git a/src/Health/HealthClient.php b/src/Health/HealthClient.php index 8bd2296..8598f46 100644 --- a/src/Health/HealthClient.php +++ b/src/Health/HealthClient.php @@ -52,17 +52,17 @@ public function node($node, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - $checks = array(); + $checks = []; foreach($data as $check) { $checks[] = new HealthCheck($check); @@ -96,17 +96,17 @@ public function checks($service, QueryOptions $queryOptions = null) $r->setQueryOptions($queryOptions); list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - $checks = array(); + $checks = []; foreach($data as $check) { $checks[] = new HealthCheck($check); @@ -146,17 +146,17 @@ public function service($service, $tag = '', $passingOnly = false, QueryOptions /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - $services = array(); + $services = []; foreach($data as $service) { $services[] = new ServiceEntry($service); @@ -193,17 +193,17 @@ public function state($state, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - $checks = array(); + $checks = []; foreach($data as $check) { $checks[] = new HealthCheck($check); diff --git a/src/Health/ServiceEntry.php b/src/Health/ServiceEntry.php index c10fd67..77ecc32 100644 --- a/src/Health/ServiceEntry.php +++ b/src/Health/ServiceEntry.php @@ -31,22 +31,34 @@ class ServiceEntry extends AbstractModel /** @var \DCarbone\PHPConsulAPI\Agent\AgentService */ public $Service = null; /** @var \DCarbone\PHPConsulAPI\Health\HealthCheck[] */ - public $Checks = array(); + public $Checks = []; /** * ServiceEntry constructor. * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - $this->Service = new AgentService((array)$this->Service); - if (isset($this->Checks)) + if (null !== $this->Service && !($this->Service instanceof AgentService)) + $this->Service = new AgentService((array)$this->Service); + + // If we have data... + if (0 < count($this->Checks)) { - for ($i = 0, $cnt = count($this->Checks); $i < $cnt; $i++) + // ...remove null + $this->Checks = array_filter($this->Checks); + + // ...and if we still have data + if (0 < ($cnt = count($this->Checks))) { - $this->Checks[$i] = new AgentCheck((array)$this->Checks[$i]); + // ensure we have objects. + for ($i = 0; $i < $cnt; $i++) + { + if (!($this->Checks[$i]) instanceof AgentCheck) + $this->Checks[$i] = new AgentCheck((array)$this->Checks[$i]); + } } } } diff --git a/src/KV/KVClient.php b/src/KV/KVClient.php index 4013dc5..20e2d9f 100644 --- a/src/KV/KVClient.php +++ b/src/KV/KVClient.php @@ -53,10 +53,10 @@ public function get($key, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->doRequest($r); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); $code = $response->getStatusCode(); @@ -108,17 +108,17 @@ public function valueList($prefix = '', QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - $kvPairs = array(); + $kvPairs = []; foreach($data as $v) { $kvp = new KVPair($v); @@ -158,10 +158,10 @@ public function keys($prefix = null, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); @@ -178,16 +178,16 @@ public function keys($prefix = null, QueryOptions $queryOptions = null) */ public function put(KVPair $p, WriteOptions $writeOptions = null) { - $r = new Request('put', sprintf('v1/kv/%s', $p->Key), $this->c); + $r = new Request('put', sprintf('v1/kv/%s', $p->Key), $this->c, $p->Value); $r->setWriteOptions($writeOptions); - $r->body = $p->Value; if (0 !== $p->Flags) $r->params->set('flags', $p->Flags); list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); + if (null !== $err) + return [null, $err]; - return [$wm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** @@ -204,9 +204,10 @@ public function delete($key, WriteOptions $writeOptions = null) $r->setWriteOptions($writeOptions); list ($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); + if (null !== $err) + return [null, $err]; - return [$wm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** @@ -226,9 +227,10 @@ public function cas(KVPair $p, WriteOptions $writeOptions = null) $r->params->set('flags', $p->Flags); list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); + if (null !== $err) + return [null, $err]; - return [$wm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** @@ -248,9 +250,10 @@ public function acquire(KVPair $p, WriteOptions $writeOptions = null) $r->params->set('flags', $p->Flags); list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); + if (null !== $err) + return [null, $err]; - return [$wm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** @@ -270,9 +273,10 @@ public function release(KVPair $p, WriteOptions $writeOptions = null) $r->params->set('flags', $p->Flags); list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); + if (null !== $err) + return [null, $err]; - return [$wm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** @@ -290,7 +294,7 @@ public function tree($prefix = '', QueryOptions $queryOptions = null) if (null !== $err) return [null, $err]; - $treeHierarchy = array(); + $treeHierarchy = []; foreach($valueList as $path=>$kvp) { $slashPos = strpos($path, '/'); diff --git a/src/KV/KVPair.php b/src/KV/KVPair.php index a9320cd..98c8ee8 100644 --- a/src/KV/KVPair.php +++ b/src/KV/KVPair.php @@ -44,7 +44,7 @@ class KVPair extends AbstractModel * @param array $data * @param bool $_decodeValue */ - public function __construct(array $data = array(), $_decodeValue = false) + public function __construct(array $data = [], $_decodeValue = false) { parent::__construct($data); if ((bool)$_decodeValue && isset($this->Value)) diff --git a/src/KV/KVTree.php b/src/KV/KVTree.php index 42efe99..8c7e9fa 100644 --- a/src/KV/KVTree.php +++ b/src/KV/KVTree.php @@ -26,7 +26,7 @@ class KVTree implements \RecursiveIterator, \Countable, \JsonSerializable, \Arra private $_prefix; /** @var KVTree[]|KVPair[] */ - private $_children = array(); + private $_children = []; /** * KVTree constructor. @@ -258,7 +258,7 @@ public function unserialize($serialized) */ public function jsonSerialize() { - $json = array($this->_prefix => array()); + $json = array($this->_prefix => []); foreach($this->_children as $k=>$child) { if ($child instanceof KVTree) diff --git a/src/Logger.php b/src/Logger.php index b94286e..dc6a069 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -26,7 +26,7 @@ abstract class Logger { /** @var LoggerInterface[] */ - private static $_loggers = array(); + private static $_loggers = []; /** @var FileDebugLogger */ private static $_debugLogger = null; @@ -76,7 +76,7 @@ public static function setLogLevel($logLevel) */ public static function setLoggers(array $loggers) { - self::$_loggers = array(); + self::$_loggers = []; foreach($loggers as $i => $logger) { @@ -108,7 +108,7 @@ public static function addLogger($logger) */ public static function resetLoggers() { - self::$_loggers = array(); + self::$_loggers = []; } /** @@ -116,7 +116,7 @@ public static function resetLoggers() * @param string $message * @param array $context */ - public static function log($logLevel, $message, array $context = array()) + public static function log($logLevel, $message, array $context = []) { $logLevel = self::sanitizeLevel($logLevel); @@ -143,7 +143,7 @@ public static function log($logLevel, $message, array $context = array()) * @param string $message * @param array $context */ - public static function emergency($message, array $context = array()) + public static function emergency($message, array $context = []) { static::log(LogLevel::EMERGENCY, $message, $context); } @@ -157,7 +157,7 @@ public static function emergency($message, array $context = array()) * @param string $message * @param array $context */ - public static function alert($message, array $context = array()) + public static function alert($message, array $context = []) { static::log(LogLevel::ALERT, $message, $context); } @@ -170,7 +170,7 @@ public static function alert($message, array $context = array()) * @param string $message * @param array $context */ - public static function critical($message, array $context = array()) + public static function critical($message, array $context = []) { static::log(LogLevel::CRITICAL, $message, $context); } @@ -182,7 +182,7 @@ public static function critical($message, array $context = array()) * @param string $message * @param array $context */ - public static function error($message, array $context = array()) + public static function error($message, array $context = []) { static::log(LogLevel::ERROR, $message, $context); } @@ -196,7 +196,7 @@ public static function error($message, array $context = array()) * @param string $message * @param array $context */ - public static function warning($message, array $context = array()) + public static function warning($message, array $context = []) { static::log(LogLevel::WARNING, $message, $context); } @@ -207,7 +207,7 @@ public static function warning($message, array $context = array()) * @param string $message * @param array $context */ - public static function notice($message, array $context = array()) + public static function notice($message, array $context = []) { static::log(LogLevel::NOTICE, $message, $context); } @@ -220,7 +220,7 @@ public static function notice($message, array $context = array()) * @param string $message * @param array $context */ - public static function info($message, array $context = array()) + public static function info($message, array $context = []) { static::log(LogLevel::INFO, $message, $context); } @@ -231,7 +231,7 @@ public static function info($message, array $context = array()) * @param string $message * @param array $context */ - public static function debug($message, array $context = array()) + public static function debug($message, array $context = []) { static::log(LogLevel::DEBUG, $message, $context); } @@ -240,7 +240,7 @@ public static function debug($message, array $context = array()) * @param string $message * @param array $context */ - public static function warn($message, array $context = array()) + public static function warn($message, array $context = []) { self::log(LogLevel::WARNING, $message, $context); } diff --git a/src/Operator/OperatorClient.php b/src/Operator/OperatorClient.php index 51f4800..08a194a 100644 --- a/src/Operator/OperatorClient.php +++ b/src/Operator/OperatorClient.php @@ -42,17 +42,17 @@ public function raftGetConfiguration(QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) return [null, $qm, $err]; - return [new RaftConfiguration($data), $qm, $err]; + return [new RaftConfiguration($data), $qm, null]; } /** diff --git a/src/Operator/RaftConfiguration.php b/src/Operator/RaftConfiguration.php index f4ebb62..9422868 100644 --- a/src/Operator/RaftConfiguration.php +++ b/src/Operator/RaftConfiguration.php @@ -34,14 +34,21 @@ class RaftConfiguration extends AbstractModel * * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - if (isset($this->Servers)) + + if (0 < count($this->Servers)) { - for ($i = 0, $cnt = count($this->Servers); $i < $cnt; $i++) + $this->Servers = array_filter($this->Servers); + + if (0 < ($cnt = count($this->Servers))) { - $this->Servers[$i] = new RaftServer((array)$this->Servers[$i]); + for ($i = 0; $i < $cnt; $i++) + { + if (!($this->Servers[$i] instanceof RaftServer)) + $this->Servers[$i] = new RaftServer((array)$this->Servers[$i]); + } } } } diff --git a/src/PreparedQuery/PreparedQueryClient.php b/src/PreparedQuery/PreparedQueryClient.php index 3eeae92..e306d16 100644 --- a/src/PreparedQuery/PreparedQueryClient.php +++ b/src/PreparedQuery/PreparedQueryClient.php @@ -31,7 +31,7 @@ class PreparedQueryClient extends AbstractClient * @param PreparedQueryDefinition $query * @param WriteOptions|null $writeOptions * @return array( - * @type string|null prepared query id or null on error + * @type string prepared query id * @type \DCarbone\PHPConsulAPI\WriteMeta write meta data * @type \DCarbone\PHPConsulAPI\Error|null error, if any * ) @@ -43,12 +43,10 @@ public function create(PreparedQueryDefinition $query, WriteOptions $writeOption /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); - if (null !== $err) - return [null, $wm, $err]; + return ['', null, $err]; - return [$response->getBody()->getContents(), $wm, $err]; + return [(string)$response->getBody(), $this->buildWriteMeta($duration), null]; } /** @@ -66,14 +64,19 @@ public function update(PreparedQueryDefinition $query, WriteOptions $writeOption /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); + if (null !== $err) + return [null, $err]; - return [$wm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** * @param QueryOptions|null $queryOptions - * @return array + * @return array( + * @type \DCarbone\PHPConsulAPI\PreparedQuery\PreparedQueryDefinition[]|null + * @type \DCarbone\PHPConsulAPI\QueryMeta|null + * @type \DCarbone\PHPConsulAPI\Error|null + * ) */ public function listQueries(QueryOptions $queryOptions = null) { @@ -82,10 +85,10 @@ public function listQueries(QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($body, $err) = $this->decodeBody($response->getBody()); if (null !== $err) @@ -96,14 +99,16 @@ public function listQueries(QueryOptions $queryOptions = null) { $list[] = new PreparedQueryDefinition($d); } - return $list; + return [$list, $qm, null]; } /** * @param string $queryID * @param QueryOptions|null $queryOptions * @return array( - * + * @type \DCarbone\PHPConsulAPI\PreparedQuery\PreparedQueryDefinition[]|null + * @type \DCarbone\PHPConsulAPI\QueryMeta|null + * @type \DCarbone\PHPConsulAPI\Error|null * ) */ public function get($queryID, QueryOptions $queryOptions = null) @@ -113,10 +118,10 @@ public function get($queryID, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($body, $err) = $this->decodeBody($response->getBody()); if (null !== $err) @@ -127,7 +132,7 @@ public function get($queryID, QueryOptions $queryOptions = null) { $queryDefinitions[] = new PreparedQueryDefinition($d); } - return $queryDefinitions; + return [$queryDefinitions, $qm, null]; } /** @@ -145,14 +150,12 @@ public function delete($queryID, WriteOptions $writeOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildWriteMeta($duration); - if (null !== $err) - return [null, $qm, $err]; + return [null, $err]; list($_, $err) = $this->decodeBody($response->getBody()); - return [$qm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** @@ -171,10 +174,10 @@ public function execute($queryIDOrName, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($body, $err) = $this->decodeBody($response->getBody()); if (null !== $err) diff --git a/src/PreparedQuery/PreparedQueryDefinition.php b/src/PreparedQuery/PreparedQueryDefinition.php index 17ac647..5924f50 100644 --- a/src/PreparedQuery/PreparedQueryDefinition.php +++ b/src/PreparedQuery/PreparedQueryDefinition.php @@ -43,14 +43,14 @@ class PreparedQueryDefinition extends AbstractModel * PreparedQueryDefinition constructor. * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - if (!($this->Service instanceof ServiceQuery)) + if (null !== $this->Service && !($this->Service instanceof ServiceQuery)) $this->Service = new ServiceQuery((array)$this->Service); - if (!($this->DNS instanceof QueryDNSOptions)) + if (null !== $this->DNS && !($this->DNS instanceof QueryDNSOptions)) $this->DNS = new QueryDNSOptions((array)$this->DNS); - if (!($this->Template instanceof QueryTemplate)) + if (null !== $this->Template && !($this->Template instanceof QueryTemplate)) $this->Template = new QueryTemplate((array)$this->Template); } diff --git a/src/PreparedQuery/PreparedQueryExecuteResponse.php b/src/PreparedQuery/PreparedQueryExecuteResponse.php index 93593af..75879d2 100644 --- a/src/PreparedQuery/PreparedQueryExecuteResponse.php +++ b/src/PreparedQuery/PreparedQueryExecuteResponse.php @@ -40,19 +40,25 @@ class PreparedQueryExecuteResponse extends AbstractModel * PreparedQueryExecuteResponse constructor. * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - if (!($this->DNS instanceof QueryDNSOptions)) + if (null !== $this->DNS && !($this->DNS instanceof QueryDNSOptions)) $this->DNS = new QueryDNSOptions((array)$this->DNS); - for ($i = 0, $cnt = count($this->Nodes); $i < $cnt; $i++) + if (0 < count($this->Nodes)) { - if ($this->Nodes[$i] instanceof ServiceEntry) - continue; + $this->Nodes = array_filter($this->Nodes); + if (0 < ($cnt = count($this->Nodes))) + { + for ($i = 0; $i < $cnt; $i++) + { + if (!($this->Nodes[$i] instanceof ServiceEntry)) + $this->Nodes[$i] = new ServiceEntry((array)$this->Nodes[$i]); - $this->Nodes[$i] = new ServiceEntry((array)$this->Nodes[$i]); + } + } } } diff --git a/src/PreparedQuery/ServiceQuery.php b/src/PreparedQuery/ServiceQuery.php index ff4e29e..e78839c 100644 --- a/src/PreparedQuery/ServiceQuery.php +++ b/src/PreparedQuery/ServiceQuery.php @@ -41,10 +41,10 @@ class ServiceQuery extends AbstractModel * ServiceQuery constructor. * @param array $data */ - public function __construct(array $data = array()) + public function __construct(array $data = []) { parent::__construct($data); - if (!($this->Failover instanceof QueryDatacenterOptions)) + if (null !== $this->Failover && !($this->Failover instanceof QueryDatacenterOptions)) $this->Failover = new QueryDatacenterOptions((array)$this->Failover); } diff --git a/src/Request.php b/src/Request.php index f07db20..c213e05 100644 --- a/src/Request.php +++ b/src/Request.php @@ -26,43 +26,35 @@ */ class Request implements RequestInterface { - /** @var Params */ + // PHPConsulAPI properties + + /** @var \DCarbone\PHPConsulAPI\Config */ + private $config; + /** @var \DCarbone\PHPConsulAPI\Params */ public $params; - /** @var mixed */ - public $body = null; + /** @var string */ + private $path; + /** @var array */ + private $_normalizedHeaders = ['accept' => 'Accept', 'content-type' => 'Content-Type']; /** @var StreamInterface|null */ - private $compiledBody = null; + private $_compiledBody = null; - /** @var string */ - private $protocolVersion = '1.1'; + // PSR-7 properties below /** @var string */ - private $method; - - /** @var string */ - private $path; - + private $protocolVersion = '1.1'; + /** @var array */ + private $headers = ['Accept' => ['application/json'], 'Content-Type' => ['application/json']]; + /** @var \Psr\Http\Message\StreamInterface */ + private $body = null; /** @var string */ private $requestTarget = null; - - /** @var Uri */ + /** @var string */ + private $method = 'POST'; + /** @var \Psr\Http\Message\UriInterface */ private $uri = null; - /** @var array */ - private $headers = array( - 'Content-Type' => ['application/json'], - 'Accept' => ['application/json'], - ); - /** @var array */ - private $_normalizedHeaderNameMap = array( - 'content-type' => 'Content-Type', - 'accept' => 'Accept' - ); - - /** @var Config */ - private $c; - /** * Request constructor. * @param string $method @@ -72,7 +64,7 @@ class Request implements RequestInterface */ public function __construct($method, $path, Config $config, $body = null) { - $this->c = $config; + $this->config = $config; $this->params = new Params(); $this->method = strtoupper($method); @@ -95,6 +87,11 @@ public function __construct($method, $path, Config $config, $body = null) $this->body = $body; } + public function __clone() + { + $this->_compiledBody = null; + } + /** * @param QueryOptions|null $queryOptions */ @@ -120,7 +117,7 @@ public function setQueryOptions(QueryOptions $queryOptions = null) if ('' !== ($token = $queryOptions->getToken())) { - if ($this->c->isTokenInHeader()) + if ($this->config->isTokenInHeader()) $this->headers['X-Consul-Token'] = $token; else $this->params['token'] = $token; @@ -158,8 +155,9 @@ public function getProtocolVersion() */ public function withProtocolVersion($version) { - $this->protocolVersion = $version; - return $this; + $clone = clone $this; + $clone->protocolVersion = $version; + return $clone; } /** @@ -175,7 +173,7 @@ public function getHeaders() */ public function hasHeader($name) { - return isset($this->_normalizedHeaderNameMap[strtolower($name)]); + return isset($this->_normalizedHeaders[strtolower($name)]); } /** @@ -183,11 +181,11 @@ public function hasHeader($name) */ public function getHeader($name) { - $name = strtolower($name); - if (isset($this->_normalizedHeaderNameMap[$name])) - return $this->headers[$this->_normalizedHeaderNameMap[$name]]; + $lower = strtolower($name); + if (!isset($this->_normalizedHeaders[$lower])) + return []; - return []; + return $this->headers[$this->_normalizedHeaders[$lower]]; } /** @@ -195,11 +193,11 @@ public function getHeader($name) */ public function getHeaderLine($name) { - $name = strtolower($name); - if (isset($this->_normalizedHeaderNameMap[$name])) - return implode(',', $this->headers[$this->_normalizedHeaderNameMap[$name]]); + $lower = strtolower($name); + if (!isset($this->_normalizedHeaders[$name])) + return ''; - return ''; + return implode(',', $this->headers[$this->_normalizedHeaders[$lower]]); } /** @@ -207,13 +205,19 @@ public function getHeaderLine($name) */ public function withHeader($name, $value) { - if (!is_array($value)) - $value = [(string)$value]; + $type = gettype($value); + if ('string' !== $type && 'array' !== $type) + throw new \InvalidArgumentException(sprintf('$value must be array or string, %s seen.', gettype($value))); + + $lower = strtolower($name); $clone = clone $this; + $clone->_normalizedHeaders[$lower] = $name; - $clone->headers[$name] = $value; - $clone->_normalizedHeaderNameMap[strtolower($name)] = $name; + if ('string' === $type) + $clone->headers[$name] = [$value]; + else + $clone->headers[$name] = $value; return $clone; } @@ -223,24 +227,26 @@ public function withHeader($name, $value) */ public function withAddedHeader($name, $value) { + $type = gettype($value); + if ('string' !== $type && 'array' !== $type) + throw new \InvalidArgumentException('$value must be array or string, %s seen.', gettype($value)); + $lower = strtolower($name); - if (isset($this->_normalizedHeaderNameMap[$lower])) - $name = $this->_normalizedHeaderNameMap[$lower]; - if (!is_array($value)) - $value = [(string)$value]; + if (isset($this->_normalizedHeaders[$lower])) + $headerValues = $this->headers[$this->_normalizedHeaders[$lower]]; + else + $headerValues = []; + + if ('string' === $type) + $headerValues[] = $value; + else + $headerValues = array_merge($headerValues, $value); $clone = clone $this; - if (isset($this->headers[$name])) - { - $clone->headers[$name] = array_unique(array_merge($this->headers[$name], $value)); - } - else - { - $clone->headers[$name] = $value; - $clone->_normalizedHeaderNameMap[strtolower($name)] = $name; - } + $clone->_normalizedHeaders[$lower] = $name; + $clone->headers[$name] = $headerValues; return $clone; } @@ -250,12 +256,11 @@ public function withAddedHeader($name, $value) */ public function withoutHeader($name) { - $lower = strtolower($name); - $clone = clone $this; - if (isset($clone->_normalizedHeaderNameMap[$lower])) - unset($clone->headers[$this->_normalizedHeaderNameMap[$lower]], $clone->_normalizedHeaderNameMap[$lower]); + $lower = strtolower($name); + if (isset($clone->_normalizedHeaders[$lower])) + unset($clone->headers[$clone->_normalizedHeaders[$lower]], $clone->_normalizedHeaders[$lower]); return $clone; } @@ -265,10 +270,10 @@ public function withoutHeader($name) */ public function getBody() { - if (!isset($this->compiledBody)) - $this->compiledBody = new RequestBody($this->body); + if (isset($this->body) && !isset($this->_compiledBody)) + $this->_compiledBody = new RequestBody($this->body); - return $this->compiledBody; + return $this->_compiledBody; } /** @@ -277,7 +282,7 @@ public function getBody() public function withBody(StreamInterface $body) { $clone = clone $this; - $clone->compiledBody = $body; + $clone->body = $body; return $clone; } @@ -329,9 +334,20 @@ public function getMethod() */ public function withMethod($method) { - $clone = clone $this; - $clone->method = strtoupper($method); - return $clone; + static $allowable = ['GET', 'PUT', 'POST', 'DELETE']; + $upper = strtoupper($method); + if (in_array($upper, $allowable, true)) + { + $clone = clone $this; + $clone->method = $upper; + return $clone; + } + + throw new \InvalidArgumentException( + '"%s" is not an allowable request method. Allowable: ["%s"]', + $upper, + implode('", "', $allowable) + ); } /** @@ -340,7 +356,7 @@ public function withMethod($method) public function getUri() { if (null === $this->uri) - $this->uri = new Uri($this->path, $this->c, $this->params); + $this->uri = new Uri($this->path, $this->config, $this->params); return $this->uri; } @@ -356,10 +372,8 @@ public function withUri(UriInterface $uri, $preserveHost = false) $clone = clone $this; $clone->uri = $uri; - if (!$preserveHost) - { - // TODO: Do this... - } + if ($preserveHost) + $clone->uri = $this->uri->withHost($this->uri->getHost()); return $clone; } diff --git a/src/RequestBody.php b/src/RequestBody.php index 36a7559..9b1365e 100644 --- a/src/RequestBody.php +++ b/src/RequestBody.php @@ -24,9 +24,17 @@ */ class RequestBody implements StreamInterface { - /** @var null|resource */ - private $h = null; + const STATE_OPEN = 0; + const STATE_CLOSED = 1; + const STATE_DETACHED = 2; + + /** @var int */ + private $_state; + /** @var null|resource */ + private $stream = null; + /** @var null|array */ + private $meta = null; /** @var int */ private $size = 0; @@ -51,7 +59,7 @@ public function __construct($contents, $encoding = '8bit') case 'object': case 'array': - $str = json_encode(json_encode($contents)); + $str = json_encode($contents); break; case 'boolean': @@ -59,9 +67,14 @@ public function __construct($contents, $encoding = '8bit') break; } - $this->h = fopen('php://memory', 'w+'); - fwrite($this->h, $str); + $this->stream = fopen('php://memory', 'w+'); + fwrite($this->stream, $str); + $this->size = mb_strlen($str, $encoding); + + $this->meta = stream_get_meta_data($this->stream); + + $this->_state = self::STATE_OPEN; } /** @@ -69,13 +82,18 @@ public function __construct($contents, $encoding = '8bit') */ public function __toString() { - if ('resource' === gettype($this->h)) + if (null === $this->stream) + return ''; + + + $this->rewind(); + $str = ''; + while(!$this->eof() && $data = $this->read(8192)) { - rewind($this->h); - return fread($this->h, $this->size); + $str .= $data; } - return ''; + return $str; } /** @@ -83,8 +101,13 @@ public function __toString() */ public function close() { - if ('resource' === gettype($this->h)) - fclose($this->h); + if (self::STATE_OPEN === $this->_state) + { + fclose($this->stream); + $this->stream = null; + $this->size = 0; + $this->_state = self::STATE_CLOSED; + } } /** @@ -92,15 +115,15 @@ public function close() */ public function detach() { - if ('resource' === gettype($this->h)) - { - $h = $this->h; - $this->h = null; - return $h; - } + if (self::STATE_OPEN === $this->_state) + $stream = $this->stream; + else + $stream = null; - $this->h = null; - return null; + $this->stream = null; + $this->size = 0; + $this->_state = self::STATE_DETACHED; + return $stream; } /** @@ -108,6 +131,9 @@ public function detach() */ public function getSize() { + if (self::STATE_OPEN !== $this->_state) + return null; + return $this->size; } @@ -116,10 +142,10 @@ public function getSize() */ public function tell() { - if ('resource' === gettype($this->h)) - return ftell($this->h); + if (self::STATE_OPEN === $this->_state) + return ftell($this->stream); - return 0; + throw new \RuntimeException(); } /** @@ -127,10 +153,10 @@ public function tell() */ public function eof() { - if ('resource' === gettype($this->h)) - return feof($this->h); + if (null === $this->stream) + return true; - return true; + return feof($this->stream); } /** @@ -138,7 +164,7 @@ public function eof() */ public function isSeekable() { - return (bool)$this->getMetadata('seekable'); + return self::STATE_OPEN === $this->_state; } /** @@ -146,19 +172,10 @@ public function isSeekable() */ public function seek($offset, $whence = SEEK_SET) { - if ('resource' === gettype($this->h)) - { - if (false === fseek($this->h, $offset, $whence)) - { - throw new \RuntimeException('Unable execute seek, please verify values are in line with PHP fseek'. - ' arguments: http://www.php.net/manual/en/function.fseek.php'); - } - } + if ($this->isSeekable()) + fseek($this->stream, $offset, $whence); else - { - throw new \RuntimeException('The underlying stream has been closed or is in an unstable state. Seek'. - ' operations cannot be performed.'); - } + throw $this->createStateException(__METHOD__); } /** @@ -166,23 +183,10 @@ public function seek($offset, $whence = SEEK_SET) */ public function rewind() { - if ('resource' === gettype($this->h)) - { - if ($this->isSeekable()) - { - if (false === rewind($this->h)) - throw new \RuntimeException('Unable to rewind stream, something very bad has happened...'); - } - else - { - throw new \RuntimeException('Stream is not seekable, cannot perform rewind.'); - } - } + if ($this->isSeekable()) + rewind($this->stream); else - { - throw new \RuntimeException('The underlying stream has been closed or is in an unstable state. Rewind'. - ' operations cannot be performed.'); - } + throw $this->createStateException(__METHOD__); } /** @@ -190,16 +194,7 @@ public function rewind() */ public function isWritable() { - $mode = $this->getMetadata('mode'); - if (null === $mode) - return false; - - $c = substr($mode, 0, 1); - return 0 === strpos($mode, 'r+') - || 'w' === $c - || 'a' === $c - || 'x' === $c - || 'c' === $c; + return false; } /** @@ -207,13 +202,7 @@ public function isWritable() */ public function write($string) { - if ($this->isWritable()) - return fwrite($this->h, $string); - - throw new \RuntimeException(sprintf( - 'Stream is not in writable state, unable to write %s.', - substr($string, 0, 500) - )); + throw new \RuntimeException('PHPConsulAPI request bodies are immutable.'); } /** @@ -221,17 +210,7 @@ public function write($string) */ public function isReadable() { - $mode = $this->getMetadata('mode'); - if (null === $mode) - return false; - - $c = substr($mode, 0, 1); - $c2 = substr($mode, 0, 2); - return 'r' === $c - || 'w+' === $c2 - || 'a+' === $c2 - || 'x+' === $c2 - || 'c+' === $c2; + return self::STATE_OPEN === $this->_state; } /** @@ -239,15 +218,10 @@ public function isReadable() */ public function read($length) { - if ($this->isReadable()) - { - if (feof($this->h)) - return ''; - - return (string)fread($this->h, $length); - } + if (self::STATE_OPEN === $this->_state) + return (string)fread($this->stream, $length); - throw new \RuntimeException('Stream is not in readable state.'); + throw $this->createStateException(__METHOD__); } /** @@ -255,20 +229,18 @@ public function read($length) */ public function getContents() { - if ($this->isReadable()) + if (self::STATE_OPEN === $this->_state) { - if (feof($this->h)) - return ''; - - $contents = ''; - while (false !== ($d = fread($this->h, 8192))) + $str = ''; + while(!$this->eof() && $data = $this->read(8192)) { - $contents = sprintf('%s%s', $contents, $d); + $str .= $data; } - return $contents; + + return $str; } - throw new \RuntimeException('Stream is not in readable state.'); + throw $this->createStateException(__METHOD__); } /** @@ -276,17 +248,29 @@ public function getContents() */ public function getMetadata($key = null) { - if ('resource' === gettype($this->h)) + if (self::STATE_OPEN === $this->_state) { - $m = stream_get_meta_data($this->h); - if (null === $key) - return $m; + return $this->meta; + + if (isset($this->meta[$key])) + return $this->meta[$key]; - if (isset($m[$key])) - return $m[$key]; + return null; } return null; } + + /** + * @param string $action + * @return \RuntimeException + */ + private function createStateException($action) + { + if (self::STATE_DETACHED === $this->_state) + return new \RuntimeException(sprintf('Cannot "%s", request body is in a detached state', $action)); + + return new \RuntimeException('Cannot "%s", request body is closed', $action); + } } diff --git a/src/Session/SessionClient.php b/src/Session/SessionClient.php index 1103e56..6e7adcc 100644 --- a/src/Session/SessionClient.php +++ b/src/Session/SessionClient.php @@ -45,17 +45,17 @@ public function createNoChecks(SessionEntry $sessionEntry = null, WriteOptions $ if (null === $sessionEntry) $sessionEntry = new SessionEntry; else - $sessionEntry->Checks = array(); + $sessionEntry->Checks = []; $r = new Request('put', 'v1/session/create', $this->c, $sessionEntry); $r->setWriteOptions($writeOptions); /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); - if (null !== $err) - return ['', $wm, $err]; + return ['', null, $err]; + + $wm = $this->buildWriteMeta($duration); list($data, $err) = $this->decodeBody($response->getBody()); if (null !== $err) @@ -80,10 +80,10 @@ public function create(SessionEntry $sessionEntry = null, WriteOptions $writeOpt /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); - if (null !== $err) - return ['', $wm, $err]; + return ['', null, $err]; + + $wm = $this->buildWriteMeta($duration); list($data, $err) = $this->decodeBody($response->getBody()); @@ -116,9 +116,10 @@ public function destroy($id, WriteOptions $writeOptions = null) $r->setWriteOptions($writeOptions); list($duration, $_, $err) = $this->requireOK($this->doRequest($r)); - $wm = $this->buildWriteMeta($duration); + if (null !== $err) + return [null, $err]; - return [$wm, $err]; + return [$this->buildWriteMeta($duration), null]; } /** @@ -146,10 +147,10 @@ public function renew($id, WriteOptions $writeOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list ($duration, $response, $err) = $this->doRequest($r); - $wm = $this->buildWriteMeta($duration); - if (null !== $err) - return [null, $wm, $err]; + return [null, null, $err]; + + $wm = $this->buildWriteMeta($duration); $code = $response->getStatusCode(); @@ -199,10 +200,10 @@ public function info($id, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); @@ -240,10 +241,10 @@ public function node($node, QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); @@ -268,10 +269,10 @@ public function listSessions(QueryOptions $queryOptions = null) /** @var \Psr\Http\Message\ResponseInterface $response */ list($duration, $response, $err) = $this->requireOK($this->doRequest($r)); - $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); - if (null !== $err) - return [null, $qm, $err]; + return [null, null, $err]; + + $qm = $this->buildQueryMeta($duration, $response, $r->getUri()); list($data, $err) = $this->decodeBody($response->getBody()); @@ -287,7 +288,7 @@ public function listSessions(QueryOptions $queryOptions = null) */ private function _hydrateEntries(array $data) { - $entries = array(); + $entries = []; foreach($data as $entry) { $entries[] = new SessionEntry($entry); diff --git a/src/Session/SessionEntry.php b/src/Session/SessionEntry.php index 7d5f384..e9e0bd1 100644 --- a/src/Session/SessionEntry.php +++ b/src/Session/SessionEntry.php @@ -33,7 +33,7 @@ class SessionEntry extends AbstractModel /** @var string */ public $Node = ''; /** @var string[] */ - public $Checks = array(); + public $Checks = []; /** @var int */ public $LockDelay = 0; /** @var string */ diff --git a/src/Uri.php b/src/Uri.php index f446cfe..a4d7085 100644 --- a/src/Uri.php +++ b/src/Uri.php @@ -22,39 +22,39 @@ * Class Uri * @package DCarbone\PHPConsulAPI\Http */ -class Uri implements UriInterface, \JsonSerializable +class Uri implements UriInterface { /** @var string */ private $scheme = ''; - /** @var HttpAuth */ - private $userInfo; /** @var string */ private $host = ''; /** @var int */ - private $port = null; + private $port = 0; /** @var string */ private $path = ''; /** @var string */ private $query = ''; /** @var string */ private $fragment = ''; + /** @var string */ + private $userInfo = ''; /** @var string */ - private $compiled = null; + private $_compiled = null; /** * Uri constructor. * @param string $path - * @param Config $c - * @param Params $p + * @param Config $config + * @param Params $params */ - public function __construct($path, Config $c, Params $p) + public function __construct($path, Config $config, Params $params) { - $this->scheme = $c->Scheme; - $this->userInfo = $c->HttpAuth; + $this->scheme = $config->Scheme; + $this->userInfo = $config->HttpAuth; $this->path = $path; - $a = $c->Address; + $a = $config->Address; if (false === ($pos = strpos($a, ':'))) { @@ -66,29 +66,12 @@ public function __construct($path, Config $c, Params $p) $this->port = (int)substr($a, $pos + 1); } - $this->query = (string)$p; - } - - /** - * @return array - */ - public function __sleep() - { - return [ - 'scheme', - 'userInfo', - 'host', - 'port', - 'path', - 'query', - 'fragment' - ]; + $this->query = (string)$params; } public function __clone() { - if (null !== $this->userInfo) - $this->userInfo = clone $this->userInfo; + $this->_compiled = null; } /** @@ -105,18 +88,18 @@ public function getScheme() public function getAuthority() { $ui = $this->getUserInfo(); - $h = $this->getHost(); - $p = $this->getPort(); + $host = $this->getHost(); + $port = $this->getPort(); if ('' === $ui) - $uri = $h; + $uri = $host; else - $uri = sprintf('%s@%s', $ui, $h); + $uri = sprintf('%s@%s', $ui, $host); - if (null === $p) + if (null === $port || 0 === $port) return $uri; - return sprintf('%s:%d', $uri, $p); + return sprintf('%s:%d', $uri, $port); } /** @@ -172,9 +155,15 @@ public function getFragment() */ public function withScheme($scheme) { - $clone = clone $this; - $clone->scheme = trim((string)$scheme, " \t\n\r\0\x0B:/"); - return $clone; + $scheme = strtolower($scheme); + if ('http' === $scheme || 'https' === $scheme) + { + $clone = clone $this; + $clone->scheme = $scheme; + return $clone; + } + + throw new \InvalidArgumentException(sprintf('Scheme must be "http" or "https", saw "%s"', $scheme)); } /** @@ -192,8 +181,16 @@ public function withUserInfo($user, $password = null) */ public function withHost($host) { + if (null === $host) + { + $clone = clone $this; + $clone->host = ''; + return $clone; + } + + // TODO: Some kind of hostname validation $clone = clone $this; - $clone->host = trim((string)$host, " \t\n\r\0\x0B/"); + $clone->host = $host; return $clone; } @@ -202,8 +199,16 @@ public function withHost($host) */ public function withPort($port) { + if (null !== $port && (!is_int($port) || 0 >= $port || 65535 < $port)) + { + throw new \InvalidArgumentException( + sprintf('Port must be integer greater than 0 and less than 65535, saw "%s"', + is_int($port) ? (string)$port : gettype($port)) + ); + } + $clone = clone $this; - $clone->port = null === $port ? null : (int)$port; + $clone->port = $port; return $clone; } @@ -212,9 +217,21 @@ public function withPort($port) */ public function withPath($path) { - $clone = clone $this; - $clone->path = trim((string)$path, " \t\n\r\0\x0B"); - return $clone; + if (is_string($path)) + { + $clone = clone $this; + $clone->path = ltrim($path, "/"); + return $clone; + } + + if (null === $path) + { + $clone = clone $this; + $clone->path = ''; + return $clone; + } + + throw new \InvalidArgumentException(sprintf('Path must be string or null, saw "%s"', gettype($path))); } /** @@ -222,9 +239,22 @@ public function withPath($path) */ public function withQuery($query) { - $clone = clone $this; - $clone->query = trim((string)$query, " \t\n\r\0\x0B?"); - return $clone; + // TODO: Some validation...? + if (null === $query) + { + $clone = clone $this; + $clone->query = ''; + return $clone; + } + + if (is_string($query)) + { + $clone = clone $this; + $clone->query = $query; + return $clone; + } + + throw new \InvalidArgumentException(sprintf('Query must be string or null, saw "%s"', gettype($query))); } /** @@ -242,7 +272,7 @@ public function withFragment($fragment) */ public function __toString() { - if (null === $this->compiled) + if (null === $this->_compiled) { $s = $this->getScheme(); $a = $this->getAuthority(); @@ -282,25 +312,9 @@ public function __toString() if ('' !== $f) $uri = sprintf('%s#%s', $uri, $f); - $this->compiled = $uri; + $this->_compiled = $uri; } - return $this->compiled; - } - - /** - * @inheritDoc - */ - function jsonSerialize() - { - return [ - 'scheme' => $this->scheme, - 'userInfo' => $this->userInfo, - 'host' => $this->host, - 'port' => $this->port, - 'path' => $this->path, - 'query' => $this->query, - 'fragment' => $this->fragment - ]; + return $this->_compiled; } } \ No newline at end of file diff --git a/tests/DefinitionTests/AbstractDefinitionTestCases.php b/tests/DefinitionTests/AbstractDefinitionTestCases.php index d64d645..6633ea7 100644 --- a/tests/DefinitionTests/AbstractDefinitionTestCases.php +++ b/tests/DefinitionTests/AbstractDefinitionTestCases.php @@ -338,7 +338,7 @@ protected function _assertCorrectPropertyZeroValue(\ReflectionClass $reflectionC case $propertyVarType instanceof Object_: $fqsn = (string)$propertyVarType->getFqsen(); - $failMessage = sprintf($failMessageTemplate, sprintf('an instance of %s', $fqsn)); + $failMessage = sprintf($failMessageTemplate, 'null'); $isInterface = interface_exists($fqsn, true); $isClass = class_exists($fqsn); @@ -350,18 +350,8 @@ protected function _assertCorrectPropertyZeroValue(\ReflectionClass $reflectionC $fqsn )); - $refl = new \ReflectionClass($fqsn); - if ($refl->isInterface()) - { - if (is_object($defaultValue)) - $this->assertInstanceOf($fqsn, $defaultValue, $failMessage); - else - $this->assertNull($defaultValue, sprintf('%s or null', $failMessage)); - } - else - { - $this->assertInstanceOf($fqsn, $defaultValue, $failMessage); - } + $this->assertNull($defaultValue, $failMessage); + break; case $propertyVarType instanceof String_: