Skip to content
This repository was archived by the owner on Oct 30, 2024. It is now read-only.

Commit 1e5869c

Browse files
committed
Configurable ConnectionOptions ctor
1 parent 9f18d6a commit 1e5869c

2 files changed

Lines changed: 79 additions & 2 deletions

File tree

examples/connect.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
<?php
22
require_once __DIR__.'/../vendor/autoload.php';
33

4-
$connectionOptions = new \Nats\ConnectionOptions();
5-
$connectionOptions->setHost('localhost')->setPort(4222);
4+
$connectionOptions = new \Nats\ConnectionOptions(
5+
[
6+
'host' => '127.0.0.1',
7+
'port' => 4222,
8+
]
9+
);
10+
611
$c = new Nats\Connection($connectionOptions);
712
$c->connect();
813
$c->close();

src/Nats/ConnectionOptions.php

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
<?php
22
namespace Nats;
33

4+
use Traversable;
5+
46
/**
57
* ConnectionOptions Class.
68
*
@@ -79,6 +81,49 @@ class ConnectionOptions
7981
*/
8082
private $reconnect = true;
8183

84+
/**
85+
* Allows to define parameters which can be set by passing them to the class constructor.
86+
*
87+
* @var array
88+
*/
89+
private $configurable = [
90+
'host',
91+
'port',
92+
'user',
93+
'pass',
94+
'token',
95+
'lang',
96+
'version',
97+
'verbose',
98+
'pedantic',
99+
'reconnect',
100+
];
101+
102+
103+
/**
104+
* ConnectionOptions constructor.
105+
*
106+
* <code>
107+
* use Nats\ConnectionOptions;
108+
*
109+
* $options = new ConnectionOptions([
110+
* 'host' => '127.0.0.1',
111+
* 'port' => 4222,
112+
* 'user' => 'nats',
113+
* 'pass' => 'nats',
114+
* 'lang' => 'php',
115+
* // ...
116+
* ]);
117+
* </code>
118+
*
119+
* @param Traversable|array $options The connection options.
120+
*/
121+
public function __construct($options = null)
122+
{
123+
if (empty($options) === false) {
124+
$this->initialize($options);
125+
}
126+
}
82127

83128
/**
84129
* Get the URI for a server.
@@ -374,4 +419,31 @@ public function setReconnect($reconnect)
374419

375420
return $this;
376421
}
422+
423+
/**
424+
* Initialize the parameters.
425+
*
426+
* @param Traversable|array $options The connection options.
427+
*
428+
* @throws Exception When $options are an invalid type.
429+
* @return void
430+
*/
431+
protected function initialize($options)
432+
{
433+
if (is_array($options) === false && ($options instanceof Traversable) === false) {
434+
throw new Exception('The $options argument must be either an array or Traversable');
435+
}
436+
437+
foreach ($options as $key => $value) {
438+
if (in_array($key, $this->configurable, true) === false) {
439+
continue;
440+
}
441+
442+
$method = 'set'.ucfirst($key);
443+
444+
if (method_exists($this, $method) === true) {
445+
$this->$method($value);
446+
}
447+
}
448+
}
377449
}

0 commit comments

Comments
 (0)